Php Wordpress输出类别单亲类别的子帖子
和我现在所拥有的有点纠结。所以我想循环浏览一个单亲类别,并输出所有带有链接的子类别帖子 我当前的代码如下,它为每个父类和子类创建了一个列表,因此: 我觉得是我的Php Wordpress输出类别单亲类别的子帖子,php,wordpress,wordpress-theming,Php,Wordpress,Wordpress Theming,和我现在所拥有的有点纠结。所以我想循环浏览一个单亲类别,并输出所有带有链接的子类别帖子 我当前的代码如下,它为每个父类和子类创建了一个列表,因此: 我觉得是我的$args可以解决这个问题 <?php $get_queried_object = get_queried_object(); $cats = get_categories( array( 'child_of' => $get_queried_object->term_id,
$args
可以解决这个问题
<?php
$get_queried_object = get_queried_object();
$cats = get_categories( array(
'child_of' => $get_queried_object->term_id,
'hide_empty' => false
) );
foreach ($cats as $cat) :
$args = array(
'category_name' => 'services', // Use the category id, can also replace with category_name which uses category slug
'cat' => $cat->term_id
);
$my_query = new WP_Query($args); ?>
<?php
if ($my_query->have_posts()) :
echo '<h5>'.$cat->name.'</h5>'; ?>
<ul>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_postdata(); ?>
</ul>
<?php else :
echo 'No Posts for '.$cat->name;
endif;
endforeach;
?>
这显示了下面,我把我们想要的放在右边,还显示了类别设置
使用
cat
而不是中的category\u,并且您还需要运行wp\u reset\u postdata()
然后再次使用主查询的当前post。请尝试下面的代码
<?php
$get_queried_object = get_queried_object();
$cats = get_categories( array(
'child_of' => $get_queried_object->term_id,
'hide_empty' => false
) );
foreach ($cats as $cat) :
$args = array(
'cat' => $cat->term_id
);
$my_query = new WP_Query($args);
if ($my_query->have_posts()) : ?>
<ul>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_postdata(); ?>
</ul>
<?php else :
echo 'No Posts for '.$cat->name;
endif;
endforeach;
?>
根据操作代码更新。
<?php
/**
* Template Name: Home
* Description: Page template with custom content
*
*/
get_header();
?>
<section>
<div class="container">
<div class="row">
<div class="col">
<?php
$cats = get_categories( array(
'child_of' => 2,
'hide_empty' => false
) );
foreach ($cats as $cat) :
$args = array(
'category_name' => 'services', // Use the category id, can also replace with category_name which uses category slug
'cat' => $cat->term_id
);
$my_query = new WP_Query($args); ?>
<?php
if ($my_query->have_posts()) :
echo '<h5>'.$cat->name.'</h5>'; ?>
<ul>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_postdata(); ?>
</ul>
<?php else :
echo 'No Posts for '.$cat->name."</br>";
endif;
endforeach;
?>
</div>
</div>
</div>
</section>
<?php
get_footer();
?>
感谢您的快速回复。已经尝试过了,但是它仍然在循环中输出父类别。我需要在查询中指定父类别(哪个slug是服务
)吗?好的,我会返回给你。现在关闭,但会输出服务
的每个子类别,然后用父类别列出最后一个列表。没有收到。你能详细解释一下吗?抱歉,我已经用你的代码更新了我的帖子,还有一个屏幕截图,显示了类别,我们目前得到了什么,需要什么。