Advertisement
simkoG

auto-featured-image.php

Oct 17th, 2022
968
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.95 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * @soure https://www.gavick.com/blog/wordpress-automatically-set-post-featured-image
  5.  */
  6.  
  7. function auto_featured_image() {
  8.     global $post;
  9.  
  10.     if (!has_post_thumbnail($post->ID)) {
  11.         $attached_image = get_children( "post_parent=$post->ID&amp;post_type=attachment&amp;post_mime_type=image&amp;numberposts=1" );
  12.          
  13.       if ($attached_image) {
  14.               foreach ($attached_image as $attachment_id => $attachment) {
  15.                    set_post_thumbnail($post->ID, $attachment_id);
  16.               }
  17.          }
  18.     }
  19. }
  20.  
  21. // Use it temporary to generate all featured images
  22. add_action('the_post', 'auto_featured_image');
  23.  
  24. // Used for new posts
  25. add_action('save_post', 'auto_featured_image');
  26. add_action('draft_to_publish', 'auto_featured_image');
  27. add_action('new_to_publish', 'auto_featured_image');
  28. add_action('pending_to_publish', 'auto_featured_image');
  29. add_action('future_to_publish', 'auto_featured_image');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement