首页 > 解决方案 > 如何显示来自特殊父类别孩子的相关 wordpress 帖子?

问题描述

我在 Wordpress 主题的 Single.php 模板中工作,但在相关帖子中我有问题!

我想显示来自父类别子项的相关帖子,例如我在 Wordpress 中添加名称为 A 的父类别,在这个父类别中,我们有 B、C、D 和其他子类别,可以为 Wordpress 帖子区域中的每个帖子设置。

好吧,我在 D(或其他 A 孩子)类别中发布了新帖子,我想在相关帖子框中显示,其他来自 D(或其他 A 孩子)类别。

这是我的工作,但不好

$related = get_posts( array(
'category__in' => wp_get_post_categories( $post->ID ),
'numberposts'  => 3,
'post__not_in' => array( $post->ID )
) );

我是新手,请帮帮我,谢谢。

标签: phpwordpress

解决方案


此代码将与父母一起获得分类,因此在您的情况下,它将获得孩子,但如果您可以有一个 A->B 和 A->C 的帖子,它只会从选择的第一个类别中获得相关帖子,例如(A ->B)

$terms = wp_get_post_terms($post->ID, 'category');
if (count($terms)) {
    foreach ($terms as $term) {
        if ($term->parent != 0) {
            $relatedTerm = $term;
            break;
        }
    }
    $related = get_posts(array(
        'category__in' => $relatedTerm->term_id,
        'numberposts'  => 3,
        'post__not_in' => array($post->ID),
    ));
}

推荐阅读