php - 获取来自相同类别的 wordpress 帖子
问题描述
我需要在单个 wordpress 帖子上输出与当前帖子具有相同类别的帖子列表。使用下面的代码,我只有第一类的所有帖子。如何从所有帖子的类别中获取帖子(有些帖子有 2 个或更多类别)。
<?php
global $post;
$current_category = get_the_category();
$same_category = new WP_Query(array(
'cat' => $current_category[0]->cat_ID,
'post__not_in' => array($post->ID),
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => -1,
));
?>
<?php while ( $same_category->have_posts() ) : $same_category->the_post(); ?>
<li>
<div class="borderline">
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</div>
</li>
<?php endwhile; ?>
解决方案
只需使用该wp_get_post_categories()
函数获取当前帖子的类别 ID,然后category__in
在查询中使用。
get_header();
while ( have_posts() ) {
the_post();
// Show current posts info
the_title();
the_content();
// Show posts of current post categories
$post_id = get_the_ID();
$post_categories = wp_get_post_categories( $post_id );
$query_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'category__in' => $post_categories,
);
$query_res = new WP_Query($query_args);
if ( $query_res->have_posts() ) {
while ( $query_res->have_posts() ) {
$query_res->the_post();
the_title();
}
} else {
echo 'Nothing to show!';
}
wp_reset_postdata();
}
get_footer();
推荐阅读
- python - 触发 ExternalTaskSensor 时气流卡住
- python - Sqlalchemy.exc.NoReferencedTableError
- java - 尽管有锁,Java 多线程中的意外结果
- openlayers - 格式 GPX.writeFeatures 不写入特征节点
- python - 在 jupyter notebook 中运行 %%cython 时出现“命令‘gcc’失败,退出状态为 1”
- c# - 在 Windows 窗体应用程序中,如果您将图像存储在 Properties.Settings 中,是否有任何方法可以枚举 ResourceManager?
- c# - 为什么在 CreateHostBuilder 中而不是在 ConfigureServices 中设置日志记录?
- php - Swagger-PHP OpenAPI 嵌套路由
- java - 如何使按钮转到另一个随机活动
- c++ - 将方法传递给新线程的问题