最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

categories - How to get posts by category at %category% url?

programmeradmin3浏览0评论

I want to display titles of all posts of the "News" category at . I have setup permalinks as /%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.

I want to display titles of all posts of the "News" category at http://example/news. I have setup permalinks as http://example/%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.

Share Improve this question edited Mar 9, 2020 at 12:01 qwaz asked Mar 9, 2020 at 11:13 qwazqwaz 1155 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论