我对php和wordpress都是新手。我对Decode的子主题进行了一些成功的修改,但这是我第一次尝试插件。我试图显示从当前帖子的同一子类别中抽取的帖子列表。我可以生成同一父类别中的帖子列表,但我不知道如何将查询结果限制到最低级别(子)类别。下面的代码显示了我想要的列表类型,但没有设置我要查找的类别限制,并且始终在列表的正下方显示列表的精确副本。任何帮助都将不胜感激!
<?php
function list_subcategory_posts() {
$post_id = get_the_ID();
$categories = get_the_category();
foreach ($categories as $category) {
if (0 != $category->parent)
$child_cat = $category;
$current_post_type = get_post_type($post_id);
$args = array(
\'category__in\' => $child_cat,
\'post_type\' => $current_post_type,
\'posts_per_page\' => \'5\',
\'post__not_in\' => array( $post_id )
);
$query = new WP_Query($args);
if ( $query->have_posts() ) { ?>
<aside class="related-posts">
<h3>
<?php _e(\'Related Items\', \'decode\'); ?>
</h3>
<ul class="related-posts">
<?php while ( $query->have_posts()) { $query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php } ?>
</ul>
</aside>
<?php }
wp_reset_postdata();
}
}
add_action(\'related_posts\', \'list_subcategory_posts\');
?>
SO网友:Jake Moore
我只是通过修改第一个foreach语句来解决这个问题。
$post_id = get_the_ID();
$cat_ids = array();
$categories = get_the_category();
if ( $categories && !is_wp_error( $categories ) ) {
foreach( $categories as $category ) {
if( 0 == $category->parent )
{
continue;
}else{
array_push( $cat_ids, $category->term_id );
}
$current_post_type = get_post_type( $post_id );
$args = array(
\'category__in\' => $cat_ids,
\'post_type\' => $current_post_type,
\'posts_per_page\' => \'5\',
\'post__not_in\' => array( $post_id )
);