phpwordpresscontent-management-systemarticlewordpress-featured-image

Exclude only first post from one category from the latest posts feed, wordpress


I administrate a website(www.teknologia.no) running Wordpress. As you can see on the front page I have a "main/featured" article on the top of the page showing the latest post from a specific category. And beneath it I have the main loop showing all the latest posts from all categories.

But as you can see and read from the title, when a posts is chosen to be places in the featured space on the top, it is also shown in the latest posts feed.

My question is as my title say: How can I exclude the newest/latest post in a certain category from appearing with the all the latests posts.

I know I can manually control this by changing the categories after a while and such, but I want it to be done automatically, and I don't know how.

Hope you can spare some time and help me :)


Solution

  • You would need to update the template's logic so that the main loop skips outputting the post that's output at the top.

    Without seeing your template code, it's hard to be specific, but something like this would probably work:

    In the top section, save the ID of the post that you're outputting:

    $exclude_post_id = get_the_ID();
    

    If you need to directly fetch the ID of the latest post in a given category, rather than saving it during the loop, you can do it like this instead, using WP_Query:

    $my_query = new WP_Query('category_name=my_category_name&showposts=1');
    while ($my_query->have_posts()):
        $my_query->next_post();
        $exclude_post_id = $my_query->post->ID;
    endwhile;
    

    Then, in the main loop, either alter the query to exclude that post:

    query_posts(array('post__not_in'=>$exclude_post_id));
    

    or manually exclude it inside the loop, something like this:

    if (have_posts()): 
        while (have_posts()):
            the_post();
            if ($post->ID == $exclude_post_id) continue;
            the_content();
        endwhile;
     endif;
    

    More information here, here and here.