O
O
ololoshka12020-06-10 15:48:50
WordPress
ololoshka1, 2020-06-10 15:48:50

How to exclude a post from categories?

How to exclude posts from a category?
There are posts on the main page. The category.php file displays all posts by category.
How to make sure that a certain post is not shown in category.php , but only on the main page.
For example, on the main page there is a post from the category, but on the page with categories, so that it would be excluded.

Here is the code to display all posts for a category.

<?php
if ( have_posts() ){
  while ( have_posts() ){
    the_post();
    // код вывода
  }
} 
?>
}

Also, this is how you can do it
<?php

if ( have_posts() ) : // если имеются записи в блоге.

  while (have_posts()) : the_post();  // запускаем цикл обхода материалов блога
?>
// Код страницы

<?php 

  endwhile;  // завершаем цикл.
endif;          
?>

As I understand it, in another cycle, it’s possible to remove an unnecessary post from the category of the page through post__not_in, please help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Yanchevsky, 2020-06-10
@ololoshka1

Try adding to functions.php

add_action( 'pre_get_posts', 'my_pre_get_posts' );
function my_pre_get_posts( $query ) {
  if( ! is_admin() && $query->is_main_query() ) {
    if( $query->is_category() ){
      $query->set( 'post__not_in', array( 1, 1095, 546, 38 ) );
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question