0
votes

I'm trying to update the sorting of search results in wordpress / woocommerce

so, when there is a search as: mydomain.com/?s=cases&post_type=product

The results get sorted by the 'total_sale' meta_key

I have the following hook

function sv_update_default_search_to_sales( $query ){
    // check if the user is requesting an admin page
    // or current query is not the main query
    if ( is_admin() || ! $query->is_main_query() ){
        return;
    }

    // Query Update for Search Results pages with products
    if (is_search() && is_woocommerce() ){

        if(get_query_var('post_type') != 'product'){
            return;
        }

        $orderBy = get_query_var('orderby');

        if(empty($orderBy) || $orderBy == 'relevance'){
            $query->set('orderby', 'meta_value_num');
            $query->set('order', 'desc');
            $query->set('meta_key', 'total_sales');
            $query->set('meta_type', 'NUMERIC');
        }
    }
}

add_action( 'pre_get_posts', 'sv_update_default_search_to_sales', 1 );

When I output $wp_query after the query has been parsed, i can see the 'meta_key' has been set to blank.

 [meta_key] => 
 [orderby] => meta_value_num
 [order] => DESC
 [meta_type] => NUMERIC

I've seen on other codes examples where they set meta_key and meta_value for matching; however, i don't have a set value, i need to order the results by 'total_sales' meta key.

Im basically trying to recreate this type of query call:

$query = new WP_Query([
    'post_type' => 'product',
    'meta_key' => 'total_sales',
    'orderby' => 'meta_value_num'
]);
1

1 Answers

1
votes

OK, so after further debugging. I realized there were other plugins modifying the query that were set to fire after my action.

I don't know which plugin specifically was modifying it, but after the page is rendered I printed the filter with

global $wp_filter;

echo '<pre>';
   print_r($wp_filter['pre_get_posts']);
echo '</pre>';

Figured outthe action number: 90000 was the last action hooked, so I set mines to 90001

add_action( 'pre_get_posts', 'sv_update_default_search_to_sales', 900001 );

and it worked! x)