I’m currently using the code below to list sticky posts on my index.php.
However, when no sticky posts are present, its loading the latest posts (up to the number specified in “settings > reading > blog posts show at most _ posts”.
How can I alter the script so that if there are no sticky posts, it exits out of the while?
query_posts(array('post__in'=>get_option('sticky_posts')));
if (have_posts()) :
while (have_posts()) : the_post();
That is because
get_option
will return an empty array if there are no sticky posts and the query will default to everything.And please don’t use
query_posts
.Ask for the existence of sticky posts, before you query the database:
And please read When should you use WP_Query vs query_posts() vs get_posts()? 🙂
For starters, before we get to the essential issue, there is
neverhardly ever a reason to usequery_posts
. It should be treated as if deprecated – mostly anyway.It does not reset, but overwrite the main query after that has already been executed anyway.
Much rather, use either the
get_posts
function or a new instance of theWP_Query
class:If, regardless of whether sticky posts were found, you’d like to alter the main query to return nothing (on the home page), make use of the
pre_get_posts
action: