You can add a query string to your URL and then alter the query if that string is set. What I’m going to do is to use pre_get_posts
to modify the main query.
function sort_by_views($query) {
if (
!is_admin() &&
$query->is_main_query() &&
$query->is_home() &&
isset( $_REQUEST['sort_by_views'] )
) {
$query->set( 'post_type', 'download');
$query->set( 'post_status', 'publish' );
$query->set( 'posts_per_page', $number );
$query->set( 'nopaging', false );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'meta_key', 'post_views_count' );
$query->set( 'order', 'DESC' );
}
}
add_action( 'pre_get_posts', 'sort_by_views' );
Now, if you navigate to http://example.com/?sort_by_views=blabla
, your posts will be ordered by the views count.
This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs.
One important note
Do not use query_posts
. Use WP_Query
instead. Using query_posts
will alter the main query’s data, which can mess with your content.