I have 5 big categories and there are many small categories in them. If I click on the category menu, I can see the posts in order of date. But I want it to be displayed randomly. How can I make a post appear randomly?
I have 5 big categories and there are many small categories in them. If I click on the category menu, I can see the posts in order of date. But I want it to be displayed randomly. How can I make a post appear randomly?
Share Improve this question edited Nov 2, 2019 at 23:29 butlerblog 5,1213 gold badges28 silver badges44 bronze badges asked Nov 2, 2019 at 17:27 songsong 31 bronze badge1 Answer
Reset to default 0You could hook into the pre_get_posts
action hook and set the posts' order to random only for specific categories. Here's a basic example on how to achieve so:
function sort_posts_randomly( $query ) {
if ( ! is_admin() && $query->is_main_query() ) {
if ( is_category( 'category id, slug, or name' ) ) {
// Sort the posts randomly
$query->set( 'orderby', 'rand' );
}
}
}
add_action( 'pre_get_posts', 'sort_posts_randomly' );
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745035660a4607501.html
评论列表(0条)