【问题标题】:Wordpress - Custom plugin to return related posts by categoryWordpress - 按类别返回相关帖子的自定义插件
【发布时间】:2015-05-29 16:06:52
【问题描述】:

我正在学习如何为 Wordpress 创建自定义插件,我正在尝试按类别获取相关帖子。

问题是,我要退回所有帖子,不管它是不是同一类别。

我在 $categoriesIds[] 上做了一个 var_dump,它为每个帖子提取了正确的类别。

我猜 WP_Query 有问题?

有人能指出代码中缺少什么吗?

function Add_related_posts($content) {

// If it's not a singular post, return the content
if (!is_singular('post')) {
    return $content;
}

// Get post categories
$categories = get_the_terms(get_the_ID(), 'category');
$categoriesIds = [];

foreach ($categories as $category) {
    $categoriesIds[] = $category->term_id;
}

$loop = new WP_Query(array(
    'category_in'    => $categoriesIds,
    'posts_per_page' => 4,
    'post_not_in'    => array(get_the_ID()),
    'orderby'        => 'rand'
));

// If there are posts
if ($loop->have_posts()) {
    $content .= 'RELATED POSTS:<br><ul>';
    while ($loop->have_posts()) {
        $loop->the_post();
        $content .= '<li><a href="'.get_permalink() .'">' . get_the_title() . '</a></li>';
    }
}
$content .= '</ul>';

// Restore data
wp_reset_query();

return $content;
}

【问题讨论】:

    标签: wordpress categories posts


    【解决方案1】:

    按预期提取类别。但是在 WP_Query 的争论中,你遇到了一个问题。 它应该是category__in,而不是category_in

    试试这个:

    'category__in'    => $categoriesIds,
    

    查看文档:http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

    【讨论】:

    • 哇!谢谢你……把我的头发拉出来了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多