Carl Papworth Carl Papworth - 28 days ago 8
PHP Question

WordPress: Set 'Featured image' as first ACF-gallery when saving post

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

Answer

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');
    $postlist = 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' );
Comments