0

I'm trying to sort by total_sales when searching, I have this till now but does not seem to do anything

add_action( 'pre_get_posts', function ( $q )
{
    if (    !is_admin() // Target only front end queries
         && $q->is_main_query() // Target the main query only
         && ( $q->is_search() )
    ) {
        $q->set( 'meta_key', 'total_sales' );
        $q->set( 'order',    'DESC'         );
        $q->set( 'orderby',  'meta_value_num'  );
    }
});
2
  • There's nothing wrong with the code, as far as I can tell, but it does make a couple of assumptions: That total sales is post meta and the meta key is exactly total_sales, and that the 'search' you're performing is a proper WordPress search (with ?s= in the URL) and not something custom or a secondary query. Are you certain both those things are true? May 23, 2018 at 8:20
  • URL looks like this ?s=abstract+pattern&post_type=product and total_sales is in postmeta table, every product has it since I already sort them by this but in product-category, and I want same for searches
    – Alex
    May 23, 2018 at 9:57

1 Answer 1

0

Problem was that I had a plugin installed that deals with the searches, it's called Better Search.

function query_1($query){
    $query .= ",wp_postmeta.meta_value as total_saless ";
    return $query;
}
add_filter( 'bsearch_posts_match_field', 'query_1' );

function query_2($query){
    $query .= "AND wp_postmeta.meta_key='total_sales' ";
    return $query;
}
add_filter( 'bsearch_posts_where', 'query_2' );

function query_3($query){
    $query = " CAST(total_saless AS INTEGER) > 99999 DESC, score DESC ";
    return $query;
}
add_filter( 'bsearch_posts_orderby', 'query_3' );

All I had to do was to hook into it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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