显示带有缩略图的随机帖子,而不仅仅是帖子的标题

时间:2019-02-15 作者:gafm

这段代码运行得非常好。它用permalink随机显示文章的标题,但我的目标是显示缩略图和/或特色图像。

任何帮助都将不胜感激。enter image description here

<?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>\';
        while ( $the_query->have_posts() ) {
        $the_query->the_post();

        $string .= \'<li><a href="\'. get_permalink() .\'">\'. get_the_title() .\' </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\');  ?>

2 个回复
SO网友:Jacob Peattie

您可以使用函数获取文章缩略图HTMLget_the_post_thumbnail(), 所以你只需要更换get_the_title() 使用该功能:

$string .= \'<li><a href="\'. get_permalink() .\'">\'. get_the_post_thumbnail() .\' </a></li>\';
默认情况下,图像大小为defined by your theme, 但你可以使用other available sizes 通过将大小名称作为函数的第二个参数传递:

$string .= \'<li><a href="\'. get_permalink() .\'">\'. get_the_post_thumbnail( null, \'large\' ) .\' </a></li>\';

SO网友:Chinmoy Kumar Paul

更换此线路

$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;
}

相关推荐