How can I exclude only latest post in certain category from showing in loop?

I have two loops and queries.

At the top of page I have this code. It only shows the latest post from category named “featured”:

Read More
<?php
    $latest_featured_post = new WP_Query ( array ( 'category_name' => 'featured', 'posts_per_page' => 1 ) );
    while ($latest_featured_post->have_posts()) : $latest_featured_post->the_post();
?>

Now I want to exclude that post from the other, main, loop on the same page, because I don’t want it to show twice. I tried to achieve that by catching the ID of a latest post in a “featured” category and passing it to the ‘post__not_in’ argument but I did something wrong. This is my code

<?php 

        $category_id = get_cat_ID('Događaji');
        $exlude_latest_featured_post = array($latest_featured_post->ID);
        $args = array(
            'category__not_in' => array($category_id),
            'post__not_in' => $exlude_latest_featured_post,
        );

        query_posts( $args );
        while (have_posts()) : the_post(); ?>

    <?php get_template_part('loop/content'); ?> 

I tried to manually pass ID of the post (‘post__not_in’ => array(1337) for example) and it works. Which means that I made mistake with catching the “featured” latest post ID.

I was searching Google for the answer but I didn’t find anything helpful. Hope someone here has time and right answer

Thanks

Related posts

1 comment

  1. You can capture the featured post id withing the 1st loop via get_the_id function, then use it in the later loop:

    <?php
        $latest_featured_post = new WP_Query ( array ( 'category_name' => 'featured', 'posts_per_page' => 1 ) );
        while ($latest_featured_post->have_posts()) : 
            $latest_featured_post->the_post(); 
            $featuredID = get_the_id();
    ?>
    

    Your latter loop:

        $category_id = get_cat_ID('Događaji');
        $exlude_latest_featured_post = array($featuredID);
    

Comments are closed.