[英]How to show posts from all categories on archive page on Wordpress?
我想在 archive.php 页面上显示所有类别的帖子。 我制作它的方式只适用于类别页面。 例如,如果我访问“myurl/category/test-category/”,该页面可以正常工作,但它只显示来自“测试类别”的帖子。 如果我访问“myurl/category/”,它只会返回一个空白页。
我的存档.php:
<?php get_header(); ?>
<div class="custom-container archive-wrapper">
<?php if(have_posts() ): while (have_posts() ): the_post(); ?>
<div class="blog-post-archive">
<div class="img-archive-wrapper d-xl-flex">
<img src="<?php echo wp_get_attachment_url(get_post_thumbnail_id( $post->ID ), 'medium' ); ?>" alt="Blog image" class="blog-image-archive">
<div class="blog-post-archive-infos">
<h2 class="archive-title"><?php the_title(); ?></h2>
<span class="post-date-archive"><?php echo get_the_date(); ?></span>
<p><?php the_excerpt( ) ?></p>
<a href="<?php the_permalink();?>" class="see-more-posts"> Ver mais</a>
</div>
</div>
</div>
<?php endwhile; else: endif; ?>
<div class="pagination__links">
<?php the_posts_pagination( ); ?>
</div>
</div>
<?php get_footer(); ?>
实际上,类别模板仅用于显示已定义类别中的帖子,因此“example.com/category/news”将显示“新闻”类别中的所有帖子,这是所需的行为。
如果您想显示“example.com/category”上的所有帖子,您有两种选择:
只需将名为“类别”go 的新页面添加到“设置”->“永久链接”,select“A static 页面”作为“您刚刚创建的页面”。 它将显示所有类别的所有帖子;
如果您不想创建新页面,请在主题根目录上添加一个文件“page_category.php”,其内容为:
<?php get_header(); ?>
<div class="custom-container archive-wrapper">
<?php
$uri = array_values(array_filter(explode('/', $_SERVER['REQUEST_URI'])));
$current_page_number = is_numeric(end($uri)) ? end($uri) : (get_query_var('paged') ? get_query_var('paged') : 1);
$wp_query = new WP_Query(array( 'post_type' => 'post', 'posts_per_page' => 10, 'paged' => $current_page_number ));
?>
<?php if(have_posts()): while (have_posts()): the_post(); ?>
<div class="blog-post-archive">
<div class="img-archive-wrapper d-xl-flex">
<img src="<?php echo wp_get_attachment_url(get_post_thumbnail_id( $post->ID ), 'medium' ); ?>" alt="Blog image" class="blog-image-archive">
<div class="blog-post-archive-infos">
<h2 class="archive-title"><?php the_title(); ?></h2>
<span class="post-date-archive"><?php echo get_the_date(); ?></span>
<p><?php the_excerpt() ?></p>
<a href="<?php the_permalink();?>" class="see-more-posts"> Ver mais</a>
</div>
</div>
</div>
<?php endwhile; wp_reset_postdata(); else: endif; ?>
<div class="pagination__links">
<?php
echo paginate_links( array(
'total' => $wp_query->max_num_pages,
'current' => max( 1, $current_page_number ),
) );
?>
</div>
</div>
<?php get_footer(); ?>
而且,在您的功能上。php:
add_action('template_include', function( $template ) {
$url_path = trim(parse_url(add_query_arg(array()), PHP_URL_PATH), '/');
if ( preg_match('/^category(\/page(\/[0-9]+)+)?$/', $url_path) ) {
// load the file if exists
$new_template = locate_template('page_category.php');
if ( '' != $new_template ) {
return $new_template ;
}
}
return $template;
});
您也可以通过Page Template来实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.