how to show posts of category random by session

You don’t need complicated filters to modify the SQL query, just use the order parameter of WP_Query ( avoid query_posts, your code above will trigger multiple unused queries, making the page very slow )

$q = new WP_Query( [
    'order' => 'rand'
] );

You can pass an integer seed too:

$q = new WP_Query( [
    'order' => 'rand(5)'
] );

But there are significant caveats

Performance

Random is slooooow, the database has to do a lot of extra work. Instead, it’d be much faster to randomly pick something to search for in PHP, then search for that instead

Other Performance Problems

The code in your question uses query_posts, and at times will overwrite the main query, then overwrite the new query, then overwrite it yet again. A single query_posts call after all the checks would be significantly faster. A pre_get_posts filter would be even faster ( eliminates the original WP query that’s never used ).

You’re also relying heavily on post meta queries. Aside from random ordering, this is the worst thing you can do for performance and scaling on a WordPress site. I expect your sites server will take 5-10 seconds to load the homepage, possibly longer, with significant SEO and visitor retention issues as a result. You’re also going to face major issues serving pages to multiple users, the database will struggle to perform those queries for more than 4 or 5 concurrent visitors. Your host is likely to contact you as a result for high CPU usage, or you’ll need a lot of hosting hardware

It will also be impossible to cache what you’re doing. Full page caching systems will not work with this, neither will object caching, and browser cache may even get in your way.

Instead of showing 10 random posts, try showing the 10 oldest posts, or the 10 newest posts, or 10 posts from a randomly selected year, or the most commented on posts, or the most popular. Decide which one in PHP and cache the result. Choosing from 10 pre-selected queries is another option.

Leave a Comment