我想在该页面上显示与当前帖子相同类别的所有帖子的链接。我在单曲中编写了以下代码。php文件。
<?php $categories_of_this_post = get_the_category(); ?>
<?php $fist_category_id = $categories_of_this_post[\'0\']->term_id; ?>
<?php $this_post_ID = get_the_ID(); ?>
<div class="related-posts">
<ol>
<?php query_posts( array ( \'cat\' => $fist_category_id, \'orderby\' => \'date\', \'order\' => \'ASC\' ) ); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<li>
<?php if (get_the_ID() != $this_post_ID) : ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php else : ?>
<?php the_title(); ?>
<?php endif; ?>
</li>
<?php endwhile; else: ?>
<p><?php _e(\'Sorry, no articles written under this category.\'); ?></p>
<?php endif; ?>
</ol>
</div>
但此代码返回在WordPress网站上找到的所有帖子。哪里出了问题?
最合适的回答,由SO网友:Stephen Harris 整理而成
我没有对此进行测试,但以下是您应该使用的方法。Don\'t use query_posts
.
$cats_of_post= get_the_category();
if($cats_of_post){
$cat_id = (int) $cats_of_post[\'0\']->term_id;
$related = get_posts(array(
\'numberposts\' => 5,
\'category\' => $cat_id,
\'orderby\' => \'post_date\',
\'order\' => \'DESC\',
\'exclude\' =>
));
global $post;
$temp_post = $post;?>
<div class="related-posts">
<?php if( $related ): ?>
<ol>
<?php foreach ($related as $post): ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endforeach; ?>
<?php else: //No posts ?>
<p><?php _e(\'Sorry, no articles written under this category.\'); ?></p>
<?php endif; ?>
<?php $post = $temp_post; ?>
</div>
<?php }//Endif no $cats_of_post