Forums

Exclude Specific Post from While loop (6 posts)

  1. Tage
    Member
    Posted 3 months ago #

    I am trying to exclude a specific post (333) from a while loop. So far I have tried a few things to no avail. Could any of you smart people help me out?

    This is what I'm dealing with:

    $thumbs = new WP_Query();
    $thumbs->query('category_name=event');
    // The Loop
    while( $thumbs->have_posts() ) : $thumbs->the_post();?>

  2. Harry
    Member
    Posted 3 months ago #

    Below is a simple if statement that just checks if the Post ID is not equaled to 333. So it will output every post except that one *fingers crossed*.

    $thumbs = new WP_Query();
    $thumbs->query('category_name=event');
    // The Loop
    while( $thumbs->have_posts() ) : $thumbs->the_post();
      if($post->ID !== 333):
    ?>
    
    <!-- post format -->
    
    <?php
      endif;
    endwhile; ?>
  3. Tage
    Member
    Posted 3 months ago #

    Thanks harmck! Worked like a charm.

    I don't need this now, but if I wanted to exclude other posts from the query would I just use commas?

    if($post->ID !== 333, 444, 555)

    or some other way entirely?

    Thanks again!

  4. Harry
    Member
    Posted 3 months ago #

    Hi Tage,

    The above code would not accept multiple values. You would have to do is like below. But this is rather cumbersome.

    if($post->ID !== 333 || $post->ID !== 444 || $post->ID !== 555):

    So I have here's another example with the multiple post exclusion provision.

    $thumbs = new WP_Query();
    $thumbs->query('category_name=event');
    // The Loop
    while( $thumbs->have_posts() ) : $thumbs->the_post();
      $posts_to_exclude = array(333, 444, 555);
      if(!in_array($post->ID, $posts_to_exclude)):
    ?>
    
    <!-- post format -->
    
    <?php
      endif;
    endwhile; ?>

    So in the $posts_to_exclude array you can comma separate all the posts you want ignored.

    The if condition just shows the post if it is not in the array. If it is, it ignores it.

    Hope this is what you're looking for.

    Thanks
    Har

  5. Tage
    Member
    Posted 3 months ago #

    You are my new favorite person!

  6. Harry
    Member
    Posted 3 months ago #

    *blushes* Haha. Better not let your significant other read that!

Reply

You must log in to post.

About this Topic