【问题标题】:How can I show related wordpress post from special parent category child?如何显示来自特殊父类别孩子的相关 wordpress 帖子?
【发布时间】:2019-09-11 22:45:31
【问题描述】:

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

我想显示来自父类别子项的相关帖子,例如,我在 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 )
) );

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

【问题讨论】:

  • 所以在 D 上,您想显示属于 A->B A->C 和 A->D 类别之一的相关帖子,对吗?
  • 不,如果我选择 D 从 D 中显示其他 如果我选择 B 从 B 中显示其他像这样,我有像 A 这样的其他父级,但我只想从 A 相关子级显示相关项目。

标签: php wordpress


【解决方案1】:

此代码将与父母一起获得分类,因此在您的情况下,它将获得孩子,但如果您的帖子是 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),
    ));
}

【讨论】:

    猜你喜欢
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多