WordPress:保存帖子时将“特色图片”设置为第一个ACF图库

时间:2016-11-07 08:46:21

标签: php wordpress advanced-custom-fields

我找到了这个函数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 );
    }
  }
}

保存帖子时出现错误消息(按“更新”按钮):

注意:未定义的变量:在第600行的/Applications/MAMP/htdocs/pf-blank/wp/wp-content/themes/PF-Blank-theme/functions.php中发布

注意:尝试在第600行的/Applications/MAMP/htdocs/pf-blank/wp/wp-content/themes/PF-Blank-theme/functions.php中获取非对象的属性

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

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

1 个答案:

答案 0 :(得分:1)

您需要通过提供参数在 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' );