简体   繁体   中英

Show recent blog posts, but exclude current post

I want to display the 3 most recent posts at the bottom of my single-blog page, but without the current posts.

my code:

<div class="blog__posts">
    <h2><?php esc_html_e('andere blogberichten', 'dfib-theme'); ?></h2>
    <a href="<?php echo get_permalink( get_option( 'page_for_posts' ) ); ?>" class="btn btn-overview"><?php esc_html_e('alle blogberichten', 'dfib-theme'); ?></a>
    <div class="blog__posts--wrapper">
        <?php 
        $the_query = new WP_Query( array(
            'posts_per_page' => 2,
        )); 
        ?>
        <?php if ( $the_query->have_posts() ) : ?>
            <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
                <div class="blog__single">
                    <a href="<?php the_permalink(); ?>"><div class="blog__single--img" style="background-image: url(<?php echo get_the_post_thumbnail_url();?>);"></div></a>
                    <h2><?php the_title(); ?></h2>
                    <?php the_excerpt(); ?>
                    <a href="<?php the_permalink(); ?>">lees meer</a>
                </div>

            <?php endwhile; ?>
            <?php wp_reset_postdata(); ?>
        <?php else : ?>
            <p><?php __('No News'); ?></p>
        <?php endif; ?>
    </div>
</div>

It displays 3 posts, but when I visit the most recent post, the same post is displayed at the bottom again. Is there a way to exclude the current one every time?

I just found the solution on this website: https://pineco.de/snippets/exclude-current-post-from-wp_query/

I just added this piece to my query:

'post__not_in'  => array(get_the_ID())

You have to exclude the current post with the post__not_in .

Add post__not_in in WP_Query array like below.

<?php 
    $the_query = new WP_Query( array(
        'posts_per_page' => 2,
        'post__not_in'   => array( get_the_ID() )
    )); 
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM