【问题标题】:Show featured images of recent posts in Wordpress?在 Wordpress 中显示最近帖子的特色图片?
【发布时间】:2016-02-07 00:31:15
【问题描述】:

我为我的 Wordpress 网站创建了一个非常简单的插件,以使用简码 ([recentposts]) 显示指向我最近发布的帖子的链接。该插件到目前为止有效,但我正在努力寻找一种方法来显示在每个帖子链接的<div> 标签中调用的每个帖子的特色图像。

您能否告诉我如何做到这一点。我的插件代码如下:

<?php
/*
Plugin Name: Blog Display Blocks
Description: Plugin to display blog posts in block with shortcode
Author: Chris Brosnan
*/

function RecentPosts() {
    $recent_posts = wp_get_recent_posts(6);
    echo '<div class="blog-contain">';
    foreach( $recent_posts as $recent ){
        echo '<div class="third-box"><a href="' . get_permalink($recent["ID"]) . '">' .   $recent["post_title"].'</a> </div> ';
    } 
};

echo '</div>';
add_shortcode('recentposts', 'RecentPosts');

register_activation_hook( __FILE__, array( 'Blogdisplay', 'plugin_activation' ) );
register_deactivation_hook( __FILE__, array( 'Blogdisplay', 'plugin_deactivation' ) );

?>

我需要做什么才能在每个被调用的帖子的相应链接旁边显示特色图片?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    通过反复试验和一些进一步的搜索,我现在找到了我的问题的解决方案。

    <?php
    /*
    Plugin Name: Blog Display Blocks
    Description: Plugin to display blog posts in block with shortcode
    Author: Chris Brosnan
    */
    
    add_image_size( 'featured-thumb', 300, 200, true ); // (cropped)
    function RecentPosts() {
        $rPosts = new WP_Query();
        $rPosts->query('showposts=6');
            while ($rPosts->have_posts()) : $rPosts->the_post(); ?>
            <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'featured-thumb' ); ?>
            <?php $image_url = $image[0]; ?>
                <a href="<?php the_permalink(); ?>">
                <div class="third-box" style="background-image: url(<?php echo $image_url; ?>);">
                    <p><?php the_title();?></p>
                </div>
                </a>
            <?php endwhile;
        wp_reset_query();
    };
    add_shortcode('recentposts', 'RecentPosts');
    
    register_activation_hook( __FILE__, array( 'Blogdisplay', 'plugin_activation' ) );
    register_deactivation_hook( __FILE__, array( 'Blogdisplay', 'plugin_deactivation' ) );
    
    ?>
    

    【讨论】:

      【解决方案2】:

      在您的代码中使用 wp_get_recent_posts() 您将获得帖子 id($recent["ID"]),然后您可以使用以下任何一种, 只需将其添加到您要显示特色图片的代码中即可。

      $image = wp_get_attachment_image_src( get_post_thumbnail_id( $recent["ID"] ), 'single-post-thumbnail' );
      or can use
      echo get_the_post_thumbnail($recent["ID"], 'featured-image');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-27
        • 1970-01-01
        相关资源
        最近更新 更多