2

If a custom post does not have a featured image, I would like to grab an image from the media library to use in place of the featured image. These particular images wouldn't be attached to any particular post, and would only be used in place of a featured image in posts where there is none. I don't want to get any image from the media library, only ones that I've somehow tagged.

I have it working now with a set of hardcoded images (that I just ftp'd to the uploads directory). However, I would like the ability to just add images to the media library and somehow "tag" them that they are for use as a default image. Since there doesn't appear to be categories/tags/taxonomies for uploaded images, what would be the best solution to get this functionality?

The only thing I could think of is create a page, and upload all my "default images" to that page. Then just query for all the images attached to that page and use a random one. There has to be a better way though than creating a useless page to categorize images.

0

1 Answer 1

5

You can use taxonomies with the media library, you just need to either add a built-in taxonomy, or register a new one.

For example, adding the built-in post tag taxonomy to attachments:

function wpd_attachment_taxonomy() {
    register_taxonomy_for_object_type( 'post_tag', 'attachment' );
}
add_action( 'init', 'wpd_attachment_taxonomy' );

You can then query for images with a specific tag:

$args = array(
    'post_type' => 'attachment',
    'post_status' => 'inherit',
    'tag' => 'tagged',
    'posts_per_page' => 1,
    'fields' => 'ids',
    'orderby' => 'rand'
);

$image = new WP_Query( $args );

if( $image->have_posts() ){
    $image_attributes = wp_get_attachment_image_src( $image->posts[0], 'full' );
    echo $image_attributes[0];
}

Change tagged to whatever the slug of your chosen tag is. This will get the attachment ID of one random image with your tag. We can then use that ID to get the attachment image attributes.

2
  • Sweet, I knew there was a much simpler way. I certainly have a lot to learn about WP. Works perfect. Thanks Milo!
    – bassfan
    Dec 19, 2015 at 21:32
  • For anyone wanting multiple random images rather than a single image, update the code to 'post_per_page' => X where X is the number of images AND remove the [0] from this line: $image_attributes = wp_get_attachment_image_src( $image->posts, 'full' );
    – Pixelsmith
    May 4, 2021 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.