Home > Blockchain >  How to exclude categories from Archive.php WordPress
How to exclude categories from Archive.php WordPress

Time:10-25

I created a blognews.php page (it shows the last news with a monthly archive) with this code to exclude some categories.

$args  = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'category__in' => 54,
    'category__not_in' => 3 ,
    'order' => 'DESC'
);
$query = new WP_Query($args);

and it works, the articles under this category aren't displayed. But when I do the same thing to archive.php and I click a month, I see the posts under the excluded category. I tried this but it doesn't work:

<?php if ( have_posts() ) : ?>
<?php
query_posts( array( 'category__and' => array(54), 'posts_per_page' => 20, 'orderby' => 'title', 'order' => 'DESC' ) );
while ($query->have_posts()):
    $query->the_post();
            get_template_part( 'template-parts/content', 'excerpt' );

Is there an easy way to exclude more categories from the blognews.php page and the archive? What's wrong with my code? Or show only a specific category it will be good too.

CodePudding user response:

Add this code to the functions.php file

function exclude_category( $query ) {
    if ( $query->is_archive() && $query->is_main_query() ) {
        $query->set( 'cat', '-3' );
    }
}
add_action( 'pre_get_posts', 'exclude_category' );

Here all conditions where is_archive is true:

if ( $this->is_post_type_archive
$this->is_date
$this->is_author
$this->is_category
$this->is_tag
$this->is_tax )
$this->is_archive = true;
  • Related