我的简短代码只显示第三个帖子,而不是三个帖子。
我需要调整什么才能显示最近发布的三篇文章的列表?
function recent_posts_shortcode() {
query_posts(array(
'orderby' => 'date',
'order' => 'DESC',
'showposts' => 3
));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string = '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
endif;
wp_reset_query();
return '<ul>' . $return_string . '</ul>';
}
add_shortcode('recent-posts', 'recent_posts_shortcode');```发布于 2020-12-30 01:33:54
您使用的query_posts()不适合在插件或主题中使用,并且不能在“循环”中使用。您可以改为使用WP_Query()类。它的实例化几乎完全相同。
同样,你只得到最后一篇文章的原因是因为你的代码每次都会重新赋值$return_string变量。你需要改用PHP的concatenation assignment operator: .=。(此外,为了避免未定义的变量警告,您需要首先对其进行初始化,这是添加第一个<ul>的好地方
function recent_posts_shortcode(){
$recent_posts_query = new WP_Query( array(
'order' => 'DESC',
'orderby' => 'date',
'posts_per_page' => 3
) );
$return_string = '<ul>';
if( $recent_posts_query->have_posts() ) :
while( $recent_posts_query->have_posts() ) : $recent_posts_query->the_post();
$return_string .= sprintf( '<li><a href="%s">%s</a></li>', esc_attr( get_permalink() ), get_the_title() );
endwhile;
endif;
wp_reset_postdata();
$return_string .= '</ul>';
return $return_string;
}
add_shortcode( 'recent-posts', 'recent_posts_shortcode' );https://stackoverflow.com/questions/65495445
复制相似问题