show4real
show4real

Reputation: 21

how do i restrict wordpress from displaying a specific post on the post page

i have a post with the following ids $posts_id=array(1,2,3,4,5); i don't feel like displaying every post on the post page. i want to exclude some post ids from the post page. Taking for example i want to remove post id with 2 and 3 from getting displayed. how do i achieve this in wordpress. this is all i have.

        <?php while(have_posts()) : the_post(); ?>
        <?php the_content(); ?>
        <?php endwhile?>
        <?php get_footer();?>

Upvotes: 0

Views: 126

Answers (2)

Ankur Bhadania
Ankur Bhadania

Reputation: 4148

Use pre_get_posts() action. add this code in your themes function.php file

function exclude_post($query) {
    if( is_home() ) {
//add condition in which page you don't want to display post.
//WordPress by default home page is post page 
      $query->set('post__not_in', array(2,3));
//add post id which you want to remove from listing ex: array(2,3)
    }
    return $query;
}
add_filter( 'pre_get_posts', 'exclude_post' );

Edit Remove from other page

Used is_page (Page ID, title, slug of page ) to remove the post from particular page

function exclude_post($query) {
        if( is_home()  || is_page (Page ID, title, slug of page )) {
    //add condition in which page you don't want to display post.
    //WordPress by default home page is post page 
          $query->set('post__not_in', array(2,3));
    //add post id which you want to remove from listing ex: array(2,3)
        }
        return $query;
    }
    add_filter( 'pre_get_posts', 'exclude_post' );

Upvotes: 0

dingo_d
dingo_d

Reputation: 11680

Use pre_get_posts() action like this:

function exclude_single_posts_home($query) {
  if ($query->is_home() && $query->is_main_query()) {
    $query->set('post__not_in', array(2,3));
  }
}

add_action('pre_get_posts', 'exclude_single_posts_home');

And put this in your functions.php file.

This should affect your home page (if you've set your home to be posts page without having home.php the default page template should fall back to index.php).

Also check template hierarchy.

Upvotes: 1

Related Questions