2015-05-29 48 views
0

我正在学习如何为WordPress创建自定义插件,我试图按类别获取相关帖子。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; 
} 

回答

相关问题