Modify existing query and change order of posts

This is my query settings

        $recipe_args = array(
            'post_type'         => 'recipes',
            'post_status'       => 'publish',               
            'posts_per_page'    => $per_page,               
            'author'            => $author->ID, 
            'paged'             => $paged,
        );

        $recipes = new WP_Query( $recipe_args );

With this dropdown box I’d like to change the query results

        <select name="orderby" class="orderby">
                <option value="menu_order">Default sorting</option>
                <option value="popularity">Sort by popularity</option>
                <option value="rating">Sort by average rating</option>
                <option value="date">Sort by newness</option>
                <option value="price">Sort by price: low to high</option>
                <option value="price-desc">Sort by price: high to low</option>
        </select>

The url structure is …/author-name/?page=recipes (using the add_query_arg() function)

What should I do next, so that when an dropdown option is selected, that a new page gets loaded
e.g. …/author-name/?page=recipes&orderby=popularity where the following code gets added to the main WP_Query.

        $recipe_args['order'] = 'DESC';
        $recipe_args['orderby'] = 'meta_value_num';         
        $recipe_args['meta_query'][] = array(
                    'key'     => 'km_receipes_sales',
                    'compare' => '>=',
                    'value' => '0.01',
            );

Any help is much appreciated.

1 Answer
1

Was able to solve this by first registering the custom query var.
https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars

And then next I used the switch function:

global $wp_query;

switch ( $wp_query->query_vars['filter'] ) {
        case 'random':
            $recipe_args['orderby']  = 'rand';                  
        break;
}

Leave a Comment