0

I want to display titles of all posts of the "News" category at http://example.com/news. I have setup permalinks as http://example.com/%category%/%postname%/. I use archive.php template which, according to WordPress Theme Handbook, is " used when visitors request posts by category".

This is what I have in archive.php

<?php if ( have_posts() ) : ?>

    <?php the_archive_title(); ?>

<?php endif; ?>

It returns not what I want:

Category: News

What is the correct way to return the list of posts belonging to the "News" category in this example? Is the archive.php correct template for that?

P.S. I know similar questions have been asked, but answers I've found contain a numerous different ways that seem to be a bit hacky. I'm looking to a correct native way to achieve the desired result.

1

Is the archive.php correct template for that?

archive.php is the most common file to load any kind of archive posts. But anytime the user loads a category archive page, WordPress template system looks for files in this order:

category-slug.php → category-id.php → category.php → archive.php → index.php

If you want to create a specific template for news category, you should use one of the following:

category-news.php: will work only for the news category

category.php: will work for all categories

To get the list of posts under News category, you should use the following code:

<?php if(have_posts()) : ?>

    <h1 class="archive-title">Category: <?php single_cat_title( '', false ); ?></h1>

<?php while(the_posts()) : the_post(); ?>

    <h2 class="post-title"><?php the_title(); ?></h2><br />
    <div class="post-content"><?php the_content(); ?></div>

<?php endwhile; ?>

<?php endif; ?>

For detailed information about category templates, I recommend you to read this article.

2
  • Thanks for the answer on template, but my main question is how do I get the list of posts belonging to the "News" category when I visit http://example.com/news url?
    – qwaz
    Mar 9 '20 at 11:59
  • @qwaz sorry, I totally misunderstood your question. I've updated my answer. ;) Mar 9 '20 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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