简体   繁体   English

从 Wordpress 媒体库中查询随机图像

[英]query random image from Wordpress Media Library

If i am using the the plugin "Enhanced Media Library" and i want to display a random image, can i somehow use a WP_query to do this?如果我使用插件“增强媒体库”并且我想显示随机图像,我可以以某种方式使用 WP_query 来执行此操作吗?

With the plugin activated this is how my media library looks like:激活插件后,这就是我的媒体库的样子: 在此处输入图片说明

I have created a category called: "imgfront", and i then want to display a random image from this category on a specific page.我创建了一个名为“imgfront”的类别,然后我想在特定页面上显示来自该类别的随机图像。 I tried the following query:我尝试了以下查询:

           $image = new WP_Query( 
            array(
                'post_type' => 'attachment', 
                'media_category' => 'imgfront',
                'posts_per_page' => '1', 
                'orderby' => 'rand',   
                )
            );  

        if( $image->have_posts() ){
            $image_attributes = wp_get_attachment_image_src( $image->posts[0], 'full' );
            ?><img src="<?php echo $image_attributes[0]; ?>"> <?php
        }

The query does noot seem to return any images though.查询似乎没有返回任何图像。

Fortunately, I am an author of the Enhanced Media Library (thanks for using it!).幸运的是,我是 Enhanced Media Library 的作者(感谢使用它!)。 Media taxonomies created by the plugin, including Media Categories, are just ordinary WordPress custom taxonomies.插件创建的媒体分类法,包括媒体类别,只是普通的 WordPress 自定义分类法。 So, everything related to WordPress taxonomies works for them equally well.因此,与 WordPress 分类法相关的一切都同样适用于它们。

Taxonomy request should be as described in WP_Query Taxonomy Params :分类请求应如WP_Query 分类参数中所述

$args = array(
    'post_type'      => 'attachment',
    'orderby'        => 'rand',
    'posts_per_page' => '1',

    'tax_query' => array(
        array(
            'taxonomy' => 'media_category',
            'field'    => 'slug',
            'terms'    => 'imgfront',
        ),
    ),
);
$image = new WP_Query( $args );

But I would've better used term_id instead of slug in this case.但在这种情况下,我最好使用term_id而不是slug

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

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