Posted By

chrs on 02/25/11


Tagged

wordpress publishpost haspostthumbnail


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

hkamci


Wordpress - Set featured image if nothing is selected


 / Published in: PHP
 

If a post is published without setting a featured image and there is an image attachment, this will select an image from the media library and set it as the featured image.

  1. function set_featured_image($post_ID){
  2.  
  3. if(!has_post_thumbnail($post_ID)){
  4.  
  5. $args = array(
  6. 'post_parent' => $post_ID,
  7. 'post_type' => 'attachment',
  8. 'numberposts' => 1,
  9. 'post_status' => null,
  10. 'post_mime_type' => 'image',
  11. );
  12.  
  13. if($image = get_children($args)) {
  14. $image = current($image);
  15. add_post_meta($post_ID, '_thumbnail_id', $image->ID);
  16. }
  17. }
  18. }
  19.  
  20. add_action("publish_post", "set_featured_image");

Report this snippet  

You need to login to post a comment.