I made a child function.php with this code. All new posts will automatically use the attachment id for the image I have uploaded to my Media Library.

function wpsites_auto_set_featured_image() {
  global $post;
  $featured_image_exists = has_post_thumbnail($post->ID);
  if (!$featured_image_exists)  {
    $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);
add_action('save_post', 'wpsites_auto_set_featured_image');

The only problem is that I have to open all posts and update them before the feature image appears.

How can I bulk update all the images to the feature image? How do I create a function that simulates the click on Update button for all posts?

Is this posible with: wp_update_post( $my_post );

Where to put it?

  • It will help to format your code properly to make it easier for others to read. Click the help link under the Add Comment button to see a summary of the available formatting options. Generally, code is formatting using the backtick: `
    – davemac
    Commented Nov 24, 2017 at 2:27
  • Why not adding image directly into your post loop something like this ? wp_get_attachment_image_src( get_post_thumbnail_id($post->ID) , $image_size );
    – Ronald
    Commented Nov 24, 2017 at 11:46
  • thanks for your answer. I am a real beginner. Where do I place this code? Commented Nov 24, 2017 at 15:25
  • Problem solved, answer found on this site: if you want to use the '$update' argument (that is the 3rd) of the 'save_post' hook you need to add 3 as $accepted_args param on add_action (see docs). add_action('save_post', 'wpsites_auto_set_featured_image', 10, 3); For which it is 10 I do not know yet. Commented Nov 25, 2017 at 6:41


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.