WordPress.org

Ready to get started?Download WordPress

Forums

Exclude posts from WP_Query? (7 posts)

  1. christopherross
    Member
    Posted 5 years ago #

    I'm trying to fetch a list of posts on a page but exclude some specific id's from the results, so I've tried

    $my_query = new WP_Query('showposts=10&exclude=1,24,312')

    but the resulting object still contains the excluded posts. I've also tried:

    $my_query = new WP_Query('showposts=10&p=-1,-24,-312')

    to no avail. Can anybody suggest the proper way to do this?

    For example ... I want to fetch the 10 most recent posts in the list except for the posts with an id's of 1,24,312.

  2. stvwlf
    Member
    Posted 5 years ago #

    hi

    'post__not_in' => array(6,2,8)
    - exclusion, lets you specify the post IDs NOT to retrieve

    see http://codex.wordpress.org/Template_Tags/query_posts#Post_.26_Page_Parameters

    also, to confirm, use a single ampersand between parameters, not the "ampersand amp;" that the forum software displays a ampersand character as.

  3. desertmagic
    Member
    Posted 4 years ago #

    You were really close. Use cat= followed by a negative sign and whatever category id you want to exclude.

    new WP_Query("showposts=10&cat=-22,-12,-6")

  4. trefethen
    Member
    Posted 4 years ago #

    Can this exclusion be used as a text widget in the sidebar? I am trying to show specific category posts in the sidebar widget "Recent Posts" while excluding posts within other categories.

    Is there any easier way to go about this?

  5. MichaelH
    Member
    Posted 4 years ago #

    Consider downloading and installing Otto's PHP Code Widget, then put something like this there:

    <?php
    $args=array(
      'category__not_in' => array(22,12,6,4),
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => 5,
      'caller_get_posts'=> 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
        <?php
      endwhile;
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    ?>
  6. trefethen
    Member
    Posted 4 years ago #

    Thank you Michael.

    Would I replace the 22,12,6,4 within the () with the categories that I want to include in the sidebar?

    ~ John

  7. MichaelH
    Member
    Posted 4 years ago #

    To exclude categories 22,12,6,4
    'category__not_in' => array(22,12,6,4),

    To include categories 7,6,8,32
    'category__in' => array(7,6,8,32),

Topic Closed

This topic has been closed to new replies.

About this Topic