我需要在wordpress自定义帖子类型的单个页面中添加相关的帖子功能。我的帖子属于多个类别,并且在显示其内容时,帖子在顶部显示两次,并且其本身也显示在相关内容中发布部分。我尝试使用此代码
<?php
$backup = $post; // backup the current object
$found_none = '<h2>No related posts found!</h2>';
$taxonomy = 'news-category';// e.g. post_tag, category, custom taxonomy
$param_type = 'news-category'; // e.g. tag__in, category__in, but genre__in will NOT work
$post_types = get_post_types( array('public' => true), 'names' );
$tax_args=array('orderby' => 'none');
$tags = wp_get_post_terms( $post->ID , $taxonomy, $tax_args);
if ($tags) {
foreach ($tags as $tag) {
$args=array(
"$param_type" => $tag->slug,
'post__not_in' => array($post->ID),
'post_type' => $post_types,
'showposts'=>-1,
'caller_get_posts'=>1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div class="related_post_item">
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
<div class="news_date"><?php echo get_the_date('F Y', $post->ID); ?></div>
<?php $found_none = ''; ?>
</div>
<?php endwhile;
}
}
}
if ($found_none) {
echo $found_none;
}
$post = $backup; // copy it back
wp_reset_query(); // to use the original query again
?>
每个帖子检查一个类别时,它的效果非常好,但我的帖子属于多个类别。如果检查了多个类别,如何正确检测相关帖子?
答案 0 :(得分:0)
嘿,我找到了一个简单的解决方案。跟踪当前帖子的ID,当显示我的循环时添加了以下代码
$exclude = $GLOBALS['current_id'];
$args=array(
"$param_type" => $tag->slug,
'post__not_in' => array($exclude),
'post_type' => $post_types,
'showposts'=>-1,
'caller_get_posts'=>1
);
就是这样!!