简体   繁体   中英

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?

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. 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!). Media taxonomies created by the plugin, including Media Categories, are just ordinary WordPress custom taxonomies. So, everything related to WordPress taxonomies works for them equally well.

Taxonomy request should be as described in WP_Query Taxonomy Params :

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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