gocodebox / lifterlms-rest

LifterLMS REST API Feature Plugin
6 stars 7 forks source link

Avoid fatals when searching for courses/memberships but the query post type parameter is forced to be something else #299

Closed eri-trabiccolo closed 10 months ago

eri-trabiccolo commented 1 year ago

see https://github.com/gocodebox/lifterlms-groups/issues/214

Can be reproduced by using this code:

//Alter the WordPress search to return ONLY posts, no pages
if (!is_admin()) {
  function remove_pages_from_search($query) {
    if ($query->is_search) {
      $query->set('post_type', 'post');
    }
      return $query;
  }
  add_filter('pre_get_posts','remove_pages_from_search');
}

and searching an existing course/membership through our rest api, e.g. via: wp-json/llms/v1/courses/?search=a&page=1&per_page=10&orderby=relevance (make sure a is contained in a ourse content/title and in at least one post - post type post)

you'll get this kind of error logged:

[03-Nov-2022 18:25:27 UTC] PHP Fatal error:  Uncaught Error: Call to undefined method WP_Error::get() in /home/{redacted}/public_html/wp-content/plugins/lifterlms/libraries/lifterlms-rest/includes/abstracts/class-llms-rest-posts-controller.php:1695
Stack trace:
#0 /home/{redacted}/public_html/wp-content/plugins/lifterlms/libraries/lifterlms-rest/includes/abstracts/class-llms-rest-posts-controller.php(135): LLMS_REST_Posts_Controller->check_read_permission()
#1 /home/{redacted}/public_html/wp-content/plugins/lifterlms/libraries/lifterlms-rest/includes/abstracts/class-llms-rest-controller.php(465): LLMS_REST_Posts_Controller->check_read_object_permissions()
#2 /home/{redacted}/public_html/wp-content/plugins/lifterlms/libraries/lifterlms-rest/includes/abstracts/class-llms-rest-posts-controller.php(802): LLMS_REST_Controller->prepare_collection_items_for_response()
#3 /home/{redacted}/public_html/wp-content/plugins/lifterlms/libraries in /home/{redacted}/public_html/wp-content/plugins/lifterlms/libraries/lifterlms-rest/includes/abstracts/class-llms-rest-posts-controller.php on line 1695

Note: This call to get_object() https://github.com/gocodebox/lifterlms-rest/blob/1.0.0-beta-24/includes/abstracts/class-llms-rest-controller.php#L463 returns the WP_Error (404), because the queried posts are not courses as expected but posts