我有很多作者,每个人都有一篇文章。我只希望具有特定术语(来自自定义分类法)的帖子能够被其他在帖子中具有相同术语的作者看到。换言之,如果帖子作者在自己的帖子中没有特定的术语,那么他们就看不到任何其他带有该术语的帖子。我希望这有意义?
仅允许具有特定术语的帖子仅供其帖子中具有相同术语的其他作者查看
1 个回复
SO网友:David Sword
你会这样做
$current_user = wp_get_current_user();
要获取当前用户,则需要他们的帖子$current_user_posts = get_posts(array(
\'author\' => $current_user->ID,
\'posts_per_page\' => -1
);
有了他们的帖子,你就可以循环浏览,并获取条款$current_user_terms = array();
foreach ($current_user_posts as $user_post) {
$user_terms = wp_get_post_terms($user_post->ID, \'custom_tax\', array("fields" => "ids"));
foreach ($user_terms as $user_term ) {
if (!in_array($user_term->term_id, $current_user_terms))
$current_user_terms[] = $user_term->term_id;
}
}
然后,通过修改查询以仅显示选定的术语,可以更改显示给当前用户的内容:$your_query = new WP_Query( array(
\'tax_query\' => array(
array(
\'taxonomy\' => \'custom_tax\',
\'field\' => \'term_id\',
\'terms\' => $current_user_terms,
)
)
));
if ( $the_query->have_posts() ) { ..
不过,听起来您希望这是Wordpress主查询,而不是自定义查询。你必须调查一下pre_get_posts 或者在启动主查询之前通过其他方式修改主查询。您还必须决定是否要在admin和前端中运行此功能,pre_get_posts
在前端和后端都能工作,所以is_admin()
在那个钩子里很方便。
此外,正如您所想象的,每个页面加载都会运行大量查询,因此您可能希望将其全部打包到一个函数中,然后使用缓存系统调用它,如Transients_API.
您可能还需要post_save 更新/缓存中断瞬态,以便在生成新术语时立即获得新视图
结束