简体   繁体   English

WordPress媒体库访问PHP

[英]Wordpress Media Library Access PHP

Im trying to find a way to pull random images from either a post or wordpress's built in image library. 我试图找到一种从帖子或wordpress的内置图像库中提取随机图像的方法。 Im not sure how to query image uris from a post or the media library - is there a tag or method that I can adopt? 我不确定如何从帖子或媒体库中查询图像uri-是否可以使用标签或方法? Should I just write something in PHP to manually query the wordpress database? 我是否应该使用PHP编写一些内容以手动查询wordpress数据库? If so what is the most efficient way to return image urls? 如果是这样,返回图片网址的最有效方法是什么?

PS I would have posted this on Wordpress Stack but it seemed more like a technical question than a wordpress-specific question so I brought here instead. PS:我本可以在Wordpress Stack上发布此内容,但它似乎更像是一个技术性问题,而不是特定于Wordpress的问题,因此我将其带到这里。 Wordpress stack questions have a bad habit of not getting answered. WordPress堆栈问题有一个不被回答的坏习惯。

Wordpress has built-in functions to access the array on images attached to a post. Wordpress具有内置功能,可以访问帖子上附加的图像上的数组。 I found this function on the web, and it might be just what you're looking for. 我在网上找到了此功能,它可能正是您要的功能。 It fetches the images attached to a post, sorts them randomly, and returns the URL of the first one: 它获取帖子中附加的图像,对它们进行随机排序,然后返回第一个的URL:

function random_image_url($size=large) {

    global $post;
    if ( $images = get_posts(array(
        'post_parent' => get_the_ID(),
        'post_type' => 'attachment',
        'numberposts' => 1,
        'orderby' => 'rand',
        'post_mime_type' => 'image',))) {

        foreach( $images as $image ) {
            $attachmenturl=wp_get_attachment_image_src($image->ID, $size);
            $attachmenturl=$attachmenturl[0];
            echo ''.$attachmenturl.'';
        }

    }  else {
        echo '' . get_bloginfo ( 'stylesheet_directory' ) . '/img/no-attachment.gif';
    }
}

source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM