首页 > 解决方案 > Wordpress - 从 url 按类别名称显示帖子

问题描述

我正在努力让我的 category.php 根据 url 中的 slug 按类别获取和显示正确的帖子。因此,例如 www.example.com/category/news 应该显示所有标记为“新闻”类别的帖子 - 但目前它显示所有奇怪的帖子......

我如何获取类别 ID,因为我知道这是传递到循环中的值而不是实际名称,然后只显示与来自 url 的类别 ID 匹配的帖子?

这捕获了类别名称 - 但我需要 id

<?php $page_object = get_queried_object(); ?>
<h1><?php echo $page_object->cat_name; ?></h1>

然后我可以传入:

<?php query_posts('cat=ID HERE'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>

因此希望捕获 /category/name 的 ID 并将其传递到代码中

有任何想法吗?

自己解决了 - 解决方案如下:

<?php $page_object = get_queried_object(); ?>
<?php $categoryID= $page_object->cat_ID; ?>

<?php query_posts("cat=$categoryID"); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>

标签: phpwordpress

解决方案


自己解决了 - 解决方案如下:

<?php $page_object = get_queried_object(); ?>
<?php $categoryID= $page_object->cat_ID; ?>

<?php query_posts("cat=$categoryID"); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>

推荐阅读