WordPress:保存 post 时将 'Featured image' 设置为第一个 ACF-gallery

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

我找到了这个函数 here。 我正在使用 ACF 专业版。

更新:我根据下面的评论添加了变量,这消除了错误,但是功能仍然无法使用。

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 );
    }
  }
}

保存 post 时的错误消息(按 "Update" 按钮):

注意:未定义变量:post in /Applications/MAMP/htdocs/pf-blank/wp/wp-content/themes/PF-Blank-theme/functions.php on line 600

注意:试图在第 600

行 /Applications/MAMP/htdocs/pf-blank/wp/wp-content/themes/PF-Blank-theme/functions.php 中获取 non-object 的 属性

警告:无法修改 header 信息 - headers 已经在 /Applications/MAMP/htdocs/pf-blank/wp/wp-admin/post 中发送(输出开始于 /Applications/MAMP/htdocs/pf-blank/wp/wp-content/themes/PF-Blank-theme/functions.php:600)。 php 第 197 行

警告:无法修改 header 信息 - headers 已经由 /Applications/MAMP/htdocs/pf-blank/wp/wp-includes/pluggable 发送(输出开始于 /Applications/MAMP/htdocs/pf-blank/wp/wp-content/themes/PF-Blank-theme/functions.php:600)。 php 第 1174 行

您需要在get_posts函数中通过参数传递参数。

试试下面的代码:

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' );