更换此线路
$string .= \'<li><a href="\'. get_permalink() .\'">\'. get_the_title() .\' </a></li>\';
使用
$string .= \'<li><a href="\'. get_permalink() .\'">\'. get_the_post_thumbnail( get_the_ID(), \'thumbnail\' ) .\' </a></li>\';
get_the_post_thumbnail 函数在前端显示特征图像。
以下是完整代码:
<?php
function wpb_rand_posts() {
$args = array(
\'post_type\' => \'post\',
\'orderby\' => \'rand\',
\'posts_per_page\' => 5
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
$string = \'<ul class="wpb-rand-posts">\';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$string .= \'<li><a href="\'. get_permalink() .\'">\'. get_the_post_thumbnail( get_the_ID(), \'thumbnail\' ) .\' </a></li>\';
}
$string .= \'</ul>\';
/* Restore original Post Data */
wp_reset_postdata();
} else {
$string .= \'no posts found\';
}
return $string;
}
add_shortcode(\'random-posts\',\'wpb_rand_posts\');
add_filter(\'widget_text\', \'do_shortcode\');
?>
我将CSS类名添加到UL标记中。
您将此CSS添加到style.css 文件
ul.wpb-rand-posts {
list-style-type: none;
margin: 20px 0;
padding: 0;
}
.wpb-rand-posts li {
display: inline-block;
float: left;
margin-left: 10px;
width: calc( ( 100% - 40px ) / 5 );
}
.wpb-rand-posts li:first-child {
margin-left: 0;
}