Wordpress - Set featured image if nothing is selected


/ Published in: PHP
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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


Comments


You need to login to view comments.