• Resolved c.note

    (@cnote)


    I’d like to order my results in a specific way (by post type desc) but the search endpoint doesn’t have an order option like the other end points. Is this possible and if so how do I achieve it? Any information would be much appreciated. Thank you

    • This topic was modified 1 year, 8 months ago by c.note.
Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    You can set “orderby” args through the “pre_get_posts” action hook for any posts query, including those made by the API. Any ordering criteria accepted by WP_Query’s “orderby” arg can be used. However, post type description isn’t one of them. Post type description is not even in the DB, it’s declared at run time when your post type is registered. Thus it’s not something you can use in any DB query, even if you made your own SQL query. A post’s type is available, but not the type’s description.

    To organize results by post type description, you’d need to do so through PHP once the DB query has completed, but before the API response is sent. It wouldn’t be a very efficient process, and it makes pagination virtually impossible.

    You’re much better off ordering by post type and not its description. This you can do through “pre_get_posts” by setting “orderby” to “type”. Unless you provide a second orderby criteria, all posts of a particular type will be ordered as they are found in the DB.

    Note that the default order is DESC, which may be the reverse of what you’d expect. You can also set this arg to ASC if need be.

    All post queries pass through this action hook. To avoid altering other queries, confirm you’re altering an API search query. Verify the is_search query var is true and that constant REST_REQUEST is defined and is also true.

    Thread Starter c.note

    (@cnote)

    Post type descending not description. I have the standard search as well as an API driven search which looks at post, page and a custom post type article. The descending is to ensure posts are at the top of the results.

    Its now working, I had a pre_get_posts for the search.php but it had a is_main_query so was being ignored when it was the API query.

    Thanks

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘WordPress Rest API search’ is closed to new replies.