post_status ) { return; } $the_terms = get_the_terms( $post_ID, self::POST_TAXONOMY ); if ( empty( $the_terms ) ) { return; } /* * Optional - filter out the default category */ if ( 'category' == self::POST_TAXONOMY ) { $default_category_id= get_option('default_category'); foreach( $the_terms as $index => $term ) { if ( $term->term_id == $default_category_id ) { unset( $the_terms[ $index ] ); break; } } } /* * Remove this if you want to assign a new random image each time the post is updated. */ if ( '' != get_the_post_thumbnail( $post_ID ) ) { return; } /* * Pick the term, e.g. the first value or perhaps a random value */ $chosen_name = $the_terms[0]->name; /* * Find the right [mla_gallery] parameter name for the taxonomy */ switch ( self::ITEM_TAXONOMY ) { case 'category': $taxonomy = 'category_name'; break; case 'post_tag': $taxonomy = 'tag'; break; default: $taxonomy = self::ITEM_TAXONOMY; } /* * Use a shortcode to finish the job, or parse the image ID our of gallery output */ if ( self::USE_SHORTCODE ) { add_shortcode( 'random_featured_image', 'RandomFeaturedImage::random_featured_image_shortcode' ); do_shortcode( sprintf( '[mla_gallery %1$s="%2$s" orderby=rand posts_per_page=1 mla_alt_shortcode=random_featured_image rfi_post_id="%3$d"]', $taxonomy, $chosen_name, $post_ID ) ); remove_shortcode( 'random_featured_image' ); } else { /* * Compose a simple gallery and capture the output */ $gallery = do_shortcode( sprintf( '[mla_gallery %1$s="%2$s" orderby=rand posts_per_page=1 size=none link=none mla_style=none mla_caption="rfi_image_id={+attachment_ID+}"]', $taxonomy, $chosen_name, $post_ID ) ); /* * Find the ID of the random image, if there is one, * then set the featured image. */ if ( preg_match( '/rfi_image_id=(\d+)/', $gallery, $matches ) ) { $success = set_post_thumbnail( $post_ID, absint( $matches[1] ) ); } } } /** * WordPress Shortcode; assigns the Featured Image * * @since 1.00 * * @param array shortcode parameters; defaults ( 'rfi_post_id' => 0, 'ids' => '' ) * * @return void echoes error messages, if any */ public static function random_featured_image_shortcode( $attr ) { $default_arguments = array( 'rfi_post_id' => 0, 'ids' => '', ); /* * Accept only the attributes we need and supply defaults */ $arguments = shortcode_atts( $default_arguments, $attr ); /* * Make sure we have a post ID */ if ( empty( $arguments['rfi_post_id'] ) ) { return ''; } /* * Make sure we have exactly one image ID */ $ids = ! empty ( $arguments['ids'] ) ? explode( ',', $arguments['ids'] ) : array(); if ( empty( $ids ) ) { return ''; } else { $ids = $ids[0]; } /* * At last! Set the new featured image */ $success = set_post_thumbnail( absint( $arguments['rfi_post_id'] ), absint( $ids ) ); return ''; } //random_featured_image_shortcode } //RandomFeaturedImage /* * Install the shortcode and/or filters at an early opportunity */ add_action('init', 'RandomFeaturedImage::initialize'); ?>