0

I'm having an issue with the order of search results loaded via AJAX, it never matches the order of the same query on the search results page. The AJAX response WP_Query instance uses the following arguments:

$query_args = [
    'cat'            => '-7',
    'orderby'        => 'relevance',
    'order'          => 'DESC',
    'post_type'      => ['features', 'how-to-guides', 'post', 'page', 'testimonials'],
    'posts_per_page' => 8,
    'post_status'    => 'publish',
    's'              => (isset($_GET['search_term']) === true) ? filter_input(INPUT_GET, 'search_term', FILTER_SANITIZE_SPECIAL_CHARS) : '',
    'meta_query'     => [
        [
            'compare'  => 'NOT EXISTS',
            'key'      => 'thank_you_page',
            'value'    => 'on',
            'type'     => 'CHAR'
        ]
    ],
    'tax_query'      => [
        [
             'field'    => 'slug',
             'operator' => 'NOT IN',
             'taxonomy' => 'resources-categories',
             'terms'    => ['hidden']
        ]
    ]
];

I've tried removing everything from the query apart from the order, orderby and it doesn't matter if the order is set to "DESC", "ASC" or if the orderby is set to "relevance", "title" etc, it has no impact on the order of the AJAX results.

Has anyone else ever encountered this issue before? If you have, did you find a way to make the order match the same query on the search results page?

0

Sorting your posts by relevance. The code below will output the posts ordered by relevance I have added some comments for some clarification let me know if it works.

function my_custom_query(){

// get only the posts without order them  
$my_query_posts = new WP_Query( array( 'numberposts' => 5 ) );

// check relevance posts
foreach( $my_query_posts->posts as $post )    
    $post->relevance = check_relevance( $post );

// sorting the posts 
usort( $my_query_posts->posts, 'compare' );

return $my_query_posts;

}

function check_relevance( $post ){
// check and calculate the relevance post
return rand( 0, 100 );

}

function my_compare( $a, $b ){

if(  $a->relevance ==  $b->relevance )
    return 0;

return ( $a->relevance > $b->relevance ) ? -1 : 1;

}

$posts = my_custom_query();

// output posts
while( $posts->have_posts() ){

$posts->the_post();

}
  • This appears to assign a random relevance weight to each $post between 0 and 100 and then order them based on this, it doesn't match them up to order found on the search results page. – Michael Jul 27 '17 at 14:39

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.