Skip to content
Advertisement

WordPress how to show all posts in the index page and exclude sticky posts

Since WordPress sticky posts feature allow the post checked as sticky in post publish panel to be placed at the top of the front page of posts.

I want to show all posts in index without sticky posts:

if ( have_posts() ) :
?>
    <div class="row my-4">
    <?php
        while ( have_posts() ) :
            the_post();

            /**
             * Include the Post-Format-specific template for the content.
             * If you want to overload this in a child theme then include a file
             * called content-___.php (where ___ is the Post Format name) and that will be used instead.
             */
            get_template_part( 'content', 'index' ); // Post format: content-index.php
        endwhile;
    ?>
    </div>
<?php
endif;

wp_reset_postdata();

Advertisement

Answer

You could use pre_get_posts action hook to manipulate the query. Since you need to modify the query on your index.php, the you could use the is_home conditional check.

add_action('pre_get_posts', 'your_theme_no_sticky_posts_query');

function your_theme_no_sticky_posts_query($query)
{
  if (is_home() && $query->is_main_query()) {
    $query->set('post__not_in', get_option('sticky_posts'));
  }
}

Code goes into the functions.php of your active theme.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement