我已将帖子分配给每个类别。然而,有些帖子需要分配给多个类别,这就是代码崩溃的时候。没有任何错误消息。每当我将帖子分配给多个类别时,Wordpress 网站仅加载来自 Cat1 的帖子。
我的作业后方法:
Post1 - Cat1
Post2 - Cat2
Post3 - Cat1,Cat3,Cat4
Post4 - Cat3
Post5 - Cat4
这是我的代码,如果每个帖子都分配给一个类别,则该代码有效。一旦一个帖子被分配到多个类别,它就会失败。这是我的代码
category.php
<?php
global $post;
$category = get_the_category($post->ID);
$category = $category[0]->cat_ID;
$myposts = get_posts(
array(
'numberposts' => -1,
'offset' => 0,
'category__in' => array($category),
'post_status'=>'publish',
'order'=>'ASC'
)
);
foreach($myposts as $post) : setup_postdata($post);
?>
<a href="<?php the_permalink() ?>"><?php echo substr(get_the_title(),0,55); ?></a>
<?php endforeach; ?>
<?php wp_reset_query(); ?>
问题是,在类别页面上,您想要获取查询的对象(类别),而不是全局 $post 对象,我认为这将是最后添加到类别中的帖子。尝试这个代码,看看它是如何工作的。
$category = get_queried_object();
$cat_id = $category->term_id;
$myposts = get_posts(
array(
'numberposts' => -1,
'offset' => 0,
'category' => $cat_id,
'post_status'=>'publish',
'order'=>'ASC'
)
);