1
votes

I found this function here. I'm using ACF pro.

Update: I added variable according to comment below, this got rid of the error, however the function is still not working.

functions.php:

add_action( 'save_post', 'set_featured_image_from_gallery' );

function set_featured_image_from_gallery() {
  $post = get_post(); //Edit according to comment below      
  $has_thumbnail = get_the_post_thumbnail($post->ID);

  if ( !$has_thumbnail ) {

    $images = get_field('gallery', false, false);
    $image_id = $images[0];

    if ( $image_id ) {
      set_post_thumbnail( $post->ID, $image_id );
    }
  }
}

Error message when saving post (pressing "Update"-button):

Notice: Undefined variable: post in /Applications/MAMP/htdocs/pf-blank/wp/wp-content/themes/PF-Blank-theme/functions.php on line 600

Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/pf-blank/wp/wp-content/themes/PF-Blank-theme/functions.php on line 600

Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/pf-blank/wp/wp-content/themes/PF-Blank-theme/functions.php:600) in /Applications/MAMP/htdocs/pf-blank/wp/wp-admin/post.php on line 197

Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/pf-blank/wp/wp-content/themes/PF-Blank-theme/functions.php:600) in /Applications/MAMP/htdocs/pf-blank/wp/wp-includes/pluggable.php on line 1174

1
firstly you need to get your posts data in $post varriable then and then you can use $post->ID , which you have passed in function, so using get_posts data get all the post data in to $post varriable and then try - Manthan Dave
adding a $post = get_posts(); doesn't work, tried with a foreach-loop round the $has_thumbnail, didn't work either. Could I get a code example please? - Carl Papworth

1 Answers

1
votes

You need to pass parameters in get_posts function by giving arguments.

Try below code:

function set_featured_image_from_gallery() {

    $args = array( 'posts_per_page' => 10, 'order'=> 'ASC');
    $postslist = get_posts( $args );
    foreach ( $postslist as $post ) :
      $has_thumbnail = get_the_post_thumbnail($post->ID);

      if ( !$has_thumbnail ) {

        $images = get_field('gallery', false, false);
        $image_id = $images[0];

        if ( $image_id ) {
          set_post_thumbnail( $post->ID, $image_id );
        }
      }
      endforeach; 
    }

    add_action( 'save_post', 'set_featured_image_from_gallery' );