我只想在页面上显示所有类别的最后一篇文章。为了做到这一点,我制作了以下代码:
<?php
$args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$categories = get_categories($args);
foreach($categories as $category) {
$categoryId = $category->cat_ID;
query_posts('posts_per_page=1&cat=$categoryId');
if ( have_posts() ) :
while ( have_posts() ) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<span><?php echo $categoryId; ?></span>
<?php
endwhile;
endif;
}
wp_reset_query();
?>
但显示的帖子都是一样的。我忘了什么?
您的问题在这里:
'posts_per_page=1&cat=$categoryId'
单引号和双引号之间有很大的区别。单引号用于字符串文字。变量插值需要双引号。
将其更改为:
'posts_per_page=1&cat='.$categoryId
或者:
"posts_per_page=1&cat={$categoryId}"
请使用这样的参数:
$args = array(
'orderby' => 'name',
'order' => 'ASC',
'posts_per_page' =>'-1'
);
posts_per_page=-1,用于获取所有帖子。