Wordpress:如何通过循环显示特定类别的帖子?

时间:2016-11-22 21:45:09

标签: php wordpress

我有一个菜单栏,其中包含不同的主题(技术,食物等)。当我点击其中一个时,我想显示分配了该特定主题的所有帖子。我在网上找到的所有内容都通过使用ID指定主题来向我展示如何执行此操作。但是,我不想“硬编码”它,而是运行一个获取页面名称的函数,然后显示与该类别对应的帖子。基本上,我不是在查询参数中使用cat = 1,而是输入获取页面标题的代码,因为页面标题等于我想要显示的类别。我在下面发布了我的代码的第一部分。我的循环工作正常,并显示我想要的内容。我只需要弄清楚如何动态获取页面标题并将其指定为类别值。感谢您的帮助

<?php query_posts('cat=1'); ?>
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

2 个答案:

答案 0 :(得分:2)

如果您想使用自定义模板:

这个想法可以。您需要使用与类别slug相同的页面(在菜单中)。

然后使用:

获取page slug

<?php global $post; $post_slug=$post->post_name; ?>

完整的模板代码:     

global $post;
$post_slug=$post->post_name;

 $args = array( 'category_name' => $post_slug );
// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
    $the_query->the_post();
    echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}

或者您可以将这些类别添加到Appearance&gt;&gt;菜单中的菜单中,然后再添加

  1. category.php
  2. archive.php
  3. 将显示您需要修改的所有特定类别的帖子以满足您的要求。更多信息:https://codex.wordpress.org/Category_Templates

答案 1 :(得分:0)

我猜菜单上的这些主题是指向类别的链接(您可以在菜单中添加类别)。如果是,则在其中包含category.php模板文件将自动列出类别中的所有帖子,并将页面标题设置为类别

相关问题