I am looking to extend the below code to select a random featured image based on a specific category. The below works but uses an overall list of images to pull from vs a list of images based on specific categories. In the below, any image starting wtih "UF-" is selected at random to be used as the featured image.
Can someone help point me in the right direction? Ideally, looking to have several images for each category that are used at random.
function autoset_featured() {
global $post;
$already_has_thumb = has_post_thumbnail($post->ID);
if (!$already_has_thumb) {
$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_id);
}
} else {
set_post_thumbnail($post->ID, get_image());
}
}
}
function get_image(){
$list = array();
$data = array();
$media_query = new WP_Query(
array( 'post_status' => 'inherit',
'post_parent' => 0,
'post_type' => 'attachment',
'post_mime_type' => 'image/jpeg'
));
foreach ($media_query->posts as $post) {
$fullpath = wp_get_attachment_url($post->ID);
$list = (explode("/", $fullpath));
$string = $post->ID.'|'.$list[sizeof($list)-1];
if (substr($list[sizeof($list)-1],0,3) == 'UF-') {
array_push($data,(explode("|", $string)));
$idx = mt_rand(0, count($data)-1);
$img_id = $data[$idx][0];
}
}
return $img_id;
}
add_action('the_post', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');