【问题标题】:WordPress: Set 'Featured image' as first ACF-gallery when saving postWordPress:保存帖子时将“特色图片”设置为第一个 ACF 库
【发布时间】:2017-03-20 13:11:27
【问题描述】:

我找到了这个函数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)在/Applications/MAMP/htdocs/pf-blank/wp/wp-admin/post.php 在第 197 行

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

【问题讨论】:

  • 首先您需要在 $post 变量中获取您的帖子数据,然后您可以使用您已传入函数的 $post->ID ,因此使用 get_posts 数据将所有帖子数据放入$post 变量然后尝试
  • 添加$post = get_posts(); 不起作用,尝试在$has_thumbnail 周围使用foreach 循环,也不起作用。请问可以给我一个代码示例吗?

标签: php wordpress advanced-custom-fields


【解决方案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' );

【讨论】:

  • 为此工作:$postlist = get_posts( $args ); == $postslist = get_posts( $args ); & if ( $has_thumbnail ) { == if ( !$has_thumbnail ) {
  • @Carl Papworth 抱歉没有明白你详细说明?我的解决方案不适合你?
  • 这个函数可以工作,除了有一些拼写错误:$postlist 变量名不一样,$has_thumbnail 应该是!$has_thumbnail,这样它就不会改变之前设置的缩略图。这仅用于复制/粘贴目的。干杯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多