Order posts randomly by query_vars[‘suppress_filters’] in wordpress

1 min



First of all i want to tell you why we use query_vars[‘suppress_filters’].
suppress_filters is optional argument. When its value is set to false that means you disable the function from not using any filters on it’s query. That mean any filter if applying to the query will be disabled and it gives you result in normal form.

Display posts randomly in wordpress
Display posts randomly in wordpress

In the code below i want to display the posts randomly on home page of website.

< ?php
add_action( 'pre_get_posts', 'myplugin_randomly_order_blog_posts' );
function myplugin_randomly_order_blog_posts( $query ) {
if ( $query-> is_home && empty($query->query_vars['suppress_filters']))
$query-> set( 'orderby', 'rand' );
}
? >

In the above code pre_get_posts is the action hook and it is executed before the posts are fetched from the database and it is used as we can change how posts are queried.
myplugin_randomly_order_blog_posts is the function which is called on add_action.
$query-> is_home checks if wordpress is loading home page.
empty($query->query_vars[‘suppress_filters’]) checks if $query->query_vars[‘suppress_filters’] has some value in it i.e true.
$query-> set( ‘orderby’, ‘rand’ ) is used to set the query to get the posts randomly as indicated by second parameter in set() i.e ‘rand’.



Like it? Share with your friends!

Junaid Rehman

I am a blogger and freelance web developer by profession. I love to blog and learn new things about programming and IT World.