0

I found this answer that helps with ordering query results by the post type in my search query. But the issue is that it helps when I go to

https://example.com/?s=query%20string

that is if I search using native php search. And that's great. But I also have the search via ajax - when I type, the ajax will call my callback function that is registered on a custom rest endpoint.

So I am wondering if there is any way that I can identify that custom query so that I can reuse that filter? In the conditional:

if ( ! is_admin() && is_search() && is_my_custom_search_query() ) { 

The alternative is to try to rewrite the CASE orderby to WP_Query which I am not sure is possible tbh.

Search query for ajax looks like:

  $query_string   = sanitize_text_field( wp_unslash( $_GET['searchString'] ) );
  $page_no        = intval( $_GET['pageNo'] );
  $posts_per_page = 9;
  $offset         = ( $page_no - 1 ) * $posts_per_page;

  $search_args = array(
      'posts_per_page' => $posts_per_page,
      'post_status'    => 'publish',
      'perm'           => 'readable',
      's'              => $query_string,
      'offset'         => $offset,
  );

  $search_results = new WP_Query( $search_args );
  • What is the code for searching via AJAX? – Jacob Peattie Oct 31 '17 at 9:47
  • I added it to the question. Also, I realized I can add the second parameter to the posts_orderby filter, which will expose the query. I will try to add a custom parameter to the WP_Query, and using that as an identifier. – dingo_d Oct 31 '17 at 9:50
0

Ok, found the answer! I added 'query_id'parameter in my query

$query_string   = sanitize_text_field( wp_unslash( $_GET['searchString'] ) );
$page_no        = intval( $_GET['pageNo'] );
$posts_per_page = 9;
$offset         = ( $page_no - 1 ) * $posts_per_page;

$search_args = array(
    'posts_per_page' => $posts_per_page,
    'post_status'    => 'publish',
    'perm'           => 'readable',
    's'              => $query_string,
    'offset'         => $offset,
    'query_id'       => 'my_custom_ajax_search',
);

$search_results = new WP_Query( $search_args );

After that in my filter

add_filter( 'posts_orderby', 'my_order_search_by_posttype', 10, 2 );

function my_order_search_by_posttype( $orderby, $wp_query ) {
    if ( ! is_admin() && ( is_search() || isset( $wp_query->query['query_id'] ) && $wp_query->query['query_id'] === 'my_custom_ajax_search' ) ) {
...
    }
}

And it works! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.