function wpb_rand_posts() {
$string = ''; // 初始化字符串变量
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 5,
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
$string .= '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$string .= '<li><a href="'. get_permalink() .'">'. get_the_title() .'</a></li>';
}
$string .= '</ul>';
/* 恢复原始文章数据 */
wp_reset_postdata();
} else {
$string .= 'no posts found';
}
return $string;
}
add_shortcode('wpb-random-posts', 'wpb_rand_posts');
add_filter('widget_text', 'do_shortcode');
代码解析:
wpb_rand_posts
函数:
-
使用
WP_Query
查询 5 篇随机的文章(通过'orderby' => 'rand'
实现)。 -
如果找到了文章,使用
while
循环生成一个无序列表 (<ul>
),每篇文章的标题都链接到它的详细页面 (<a>
标签)。 -
如果没有找到文章,则显示
'no posts found'
。add_shortcode
函数:
-
将
wpb_rand_posts
函数注册为一个 WordPress 短代码[wpb-random-posts]
,你可以在页面或文章中插入这个短代码来显示随机文章。add_filter
函数:
-
确保短代码可以在小工具文本区域中使用(通过
do_shortcode
)。
[wpb-random-posts]