首页 文章

在Wordpress的主页上显示随机帖子附件

提问于
浏览
1

我正在尝试将1个随机图像附加到帖子上,并将其显示在首页上(更改哪个图像在刷新时显示) . 我看到的所有代码都展示了如何在帖子页面的循环中显示附件,但这将从一个页面获取附件并将其显示在不同的页面上 .

任何帮助都会很大,因为我没有真正的起点 .

2 回答

  • 0

    您可以使用WP_Query直接查询附件 . 它们实际上是一种仅用于附件的帖子类型 . 这段代码将为随机图像吐出 <img> 标签:

    $query = new WP_Query( array( 'post_status' => 'any', 'post_type' => 'attachment' ) ); 
    $key = array_rand($query->posts, 1);
    
    echo wp_get_attachment_image($query->posts[$key]->ID, 'medium');
    

    字符串 medium 可以替换为您在仪表板的媒体部分中设置的其他大小,或者使用add_image_size()在代码中设置的自定义大小 .

  • 5

    未经测试,但这应该只从数据库中获取一行,并充分利用WP_Query函数 .

    您可以通过将 'full' 替换为数组(例如 array(200, 130) )来更改显示的图像的大小 . 查看codex for wp_get_attachment_image()了解更多信息 .

    $args = array(
        'orderby'           => 'rand',
        'post_type'         => 'attachment'
        'post_status'       => 'inherit',
        'posts_per_page'    => 1
    )
    $query = new WP_Query($args);
    
    if($query->have_posts()) : while($query->have_posts() : $query->the_post();
    
            echo wp_get_attachment_image(get_the_ID(), 'full');
    
        endwhile;
    
        wp_reset_postdata();
    
    endif;
    

相关问题