Random image from tag/custom type on sidebar

How would I pull a single random image from custom post type “athletes” and the custom image field “athletethumbnail” to be displayed in my sidebar? (I have PHP enabled for my text widget on sidebar.)

Related posts

Leave a Reply

1 comment

  1. If I get your question right, as you mention Tag in the title, but not in the Content – and also mention a random image but then it’s not a library image but a custom field value…

    So, the following code will grab 1 random custom post type that has a custom field value that’s not empty. And it’s a mix of get_posts, get_post_meta and Custom_Field_Parameters:

    $args = array(
       'numberposts' => 1,
       'orderby' => 'rand',
       'post_type' => 'athletes',
       'post_status' => 'publish',
        'meta_query' => array(
            array(
                'key' => 'athletethumbnail',
                'value' => '',
                'compare' => '!=' /* will not grab posts with empty Custom Field */
            )
        )
    
    );
    $show_albums = get_posts ( $args );
    echo get_post_meta($show_albums[0]->ID,'athletethumbnail',true);