Your code is functional, however, it has several major flaws:
query_posts
query_posts
and wp_reset_query
are used, I would recommend never using this function, it has major problems, and encourages bad habits.
- if you want to modify the posts pulled in by WordPress, use the
pre_get_posts
filter, don’t replace the main query with a second and double the work done, modify it - If you want a new subquery for a small section of a site, use
WP_Query
andwp_reset_postdata
- Sometimes it’s useful to use
get_posts
, but keep in mind that this usesWP_Query
internally
Ordering by Random
Asking the database to order things randomly has a huge cost. The database has to take the entire posts table, randomly shuffle it to create a brand new table in memory, then run your query on the new table. It’s at a minimum as expensive as copying the entire posts table.
So never ask the database to order things randomly, instead, do it in PHP. E.g. ask for 10 posts then skip the first X posts, where X is a random number chosen via rand
, e.g. $random = rand(1,10)
. You can grab the posts WP_Query
fetches via $query->posts
the_content
there’s no need to fetch the content and pass it through the filter like that just so you can put it in a variable, the variable is unnecessary and overcomplicates things:
echo '<div class="top banner">';
the_content();
echo '</div><!--banner-->';
Caching
Fundamentally, this means you can never use browser cache, CDN, or page caching plugins with this code. Browser caches will always show the very first banner it encounters, CDNs will cache the first banner shown to a visitor, and page caches will do the same.
So instead, avoid showing things randomly, you want the same page request to always give the same result.
This means any “randomness” you might want has to be done in javascript. So fetch a few banner images, and have Javascript pick one in the browser.