0

Basically I want to automatically set an image randomly from a selection of about 3 or 4 images in my Media Library when someone posts a blog from a particular category. I've got this so far but it only sets one image for that category.

function default_category_featured_image() {
global $post;
$featured_image_exists = has_post_thumbnail($post->ID);

if (!$featured_image_exists)  {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );

if ($attached_image) {

foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment);
}}
else if ( in_category('49') ) {
set_post_thumbnail($post->ID, '2200');
    wp_reset_postdata();
}                      
                           }

      }
add_action('the_post', 'default_category_featured_image');

Is it possible to have more than one feature image randomly for each category?

1 Answer 1

0

You should prepare an array of images ids for each category and pick one of them randomly. I say "one of them" since the featured image is always 1 if I understood well your question.. which is somehow ambiguous when you say set an image and later to have more than one feature image So, editing part of your code and assuming that the rest is working:

//...
else if ( in_category('49') ) {
  // array of  ids of images for this category
  $arrImages = array(2200,2201,2202);

  // get random index from array $arrImages
  $randIndex = array_rand($arrImages);

  // output the value for the random index
  set_post_thumbnail($post->ID, $arrImages[$randIndex]);
  //wp_reset_postdata();

}
else if ( in_category('50') ) { // for example.. and so on
  $arrImages = array(2203,2204,2205);
  $randIndex = array_rand($arrImages);
  set_post_thumbnail($post->ID, $arrImages[$randIndex]);
}

wp_reset_postdata(); is not actually needed since you're not altering the main query see wp_reset_postdata()

Your Answer

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

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