M
M
MisTFoR2021-07-08 22:45:08
WordPress
MisTFoR, 2021-07-08 22:45:08

How to display records of category 1 in archives?

Hello.
I have a page with archives. The code:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'entry' ); ?>
<?php endwhile; endif; ?>
<?php get_template_part( 'nav', 'below' ); ?>

Tried to change the code to:
<?php query_posts( 'cat=2' );
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'entry' ); ?>
<?php endwhile; endif; ?>
<?php get_template_part( 'nav', 'below' ); ?>

Everything works, but then all posts of this category are displayed in the archives (that is, instead of displaying, for example, all posts for June, it displays posts for all time)
How to solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Zolin, 2021-07-09
@MisTFoR

You can exclude unnecessary categories on the pre_get_posts hook

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

You can't use query_posts(), it's a kernel function, you're breaking the main query loop

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question