2

I understand that I can copy my theme's default blog template and change the code to make it display only posts from one category in the theme's style. I tried tinkering with it, but to no result yet. This is the code in the theme:

$posts = new WP_Query( array('post_type'=>'post', 'paged'=>$paged) );
            if( $posts->have_posts() ):
                echo '<div class="list-posts">';
                while( $posts->have_posts() ) : $posts->the_post();
                    get_template_part( 'content', get_post_format() ); 
                endwhile;
                echo '</div>';

                wp_reset_postdata();
            else:
                echo '<div class="alert alert-error">'.esc_html__('Sorry. There are no posts to display', 'gon').'</div>';
            endif;

I tried changing the values on while( $posts->have_posts() ) : $posts->the_post(); but to no success.

How can I make this work?

1 Answer 1

1

If your theme is creating a new query for the main page loop it is doing something very wrong. To get a category archive, all you should need is a template named according to one of these patterns, depending on your need:

  1. category-{slug}.php – If the category’s slug is news, WordPress will look for category-news.php.
  2. category-{id}.php – If the category’s ID is 6, WordPress will look for category-6.php.
  3. category.php

With a Loop in it that looks like this:

if( have_posts() ) {
  echo '<div class="list-posts">';
  while( have_posts() ) {
    $posts->the_post();
    get_template_part( 'content', get_post_format() ); 
  }
  echo '</div>';
  wp_reset_postdata();
} else {
  echo '<div class="alert alert-error">'.esc_html__('Sorry. There are no posts to display', 'gon').'</div>';
}

Plus, of course, whatever code your theme needs surrounding that. I can't really guess what that code looks like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.