【问题标题】:How to make Wordpress save_post_($post-type) hook works with multiple Custom Post Types如何使 Wordpress save_post_($post-type) 钩子适用于多种自定义帖子类型
【发布时间】:2022-01-21 07:33:14
【问题描述】:

我有一个与 save_post_($post-type) 挂钩和 ACF 库字段相关的问题。

我从某个地方得到了这个代码 sn-p。让我解释一下:我创建了一个 ACF 画廊字段(acf-gallery 是字段名称)显示在自定义帖子类型(cpt1 是 slug)然后使用这个 sn-p 将此画廊的第一张图片设置为特色图片当像 Woocommerce 一样保存时。

但是如果我希望它与另一种自定义帖子类型一起使用(假设 slug 是 cpt2)怎么办?我可以用array( 'cpt1', 'cpt2' ) 代替cpt1 吗?有没有办法包含多个自定义帖子类型?


/* Set the first image generated by ACF gallery field as featured image */

add_action( 'save_post_cpt1', 'set_featured_image_from_gallery' );

function set_featured_image_from_gallery() {

    global $post;
    $post_id = $post->ID;

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

    if ( $image_id ) {
        set_post_thumbnail( $post_id, $image_id );
    }
}

我根据下面的 cmets 使用 save-post 挂钩编辑了这个 sn-p。但我不知道它是否有效。有人可以帮忙吗?

/* Set the first image generated by ACF gallery field as featured image */

add_action( 'save_post', 'set_featured_image_from_gallery' );

function set_featured_image_from_gallery($post_id) {

    if (get_post_type($post_id) != array( 'cpt1', 'cpt2')) {
        return;
    }

    $has_thumbnail = get_the_post_thumbnail($post_id);

      if ( !$has_thumbnail ) {

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

        if ( $image_id ) {
          set_post_thumbnail( $post_id, $image_id );
        }
      }
}

【问题讨论】:

  • 一般的save_post钩子应该为所有帖子类型(包括页面)触发,所以你可以使用它,你只需要检查实际的帖子类型然后首先在你的回调函数中,这样你就不会意外地将更新应用于其他类型而不是你想要的。
  • 而且确实没有必要在这个地方使用全局帖子 ID(我不太确定,如果它总是指向正确的帖子 - 如果这个钩子在批量更新期间触发或某些东西,可能会出错) - 挂钩可以将帖子 ID 和帖子内容直接传递给回调函数。
  • 您可以使用普通的save_post,然后检查$post中的类型
  • @CBroe 我刚刚修改了代码并删除了全局 $post,您可以检查一下吗?我只是一个 WordPress 菜鸟。
  • @Stender 嗨,你能检查一下修改后的版本吗?我不知道它是否有效或有意义。

标签: php wordpress advanced-custom-fields wordpress-hook


【解决方案1】:

我通常使用save_post钩子、$post_id变量、get_post_typein_array函数。

function set_featured_image_from_gallery($post_id)
{
    $included_cpts = array('cpt1', 'cpt2', 'cpt3');

    if (in_array(get_post_type($post_id), $included_cpts)) {

        $has_thumbnail = get_the_post_thumbnail($post_id);

        if (!$has_thumbnail) {

            $images = get_field('acf_gallery', $post_id, false);

            $image_id = $images[0];

            if ($image_id) {

                set_post_thumbnail($post_id, $image_id);
                
            }
        }
    }
}

add_action('save_post', 'set_featured_image_from_gallery');

【讨论】:

  • 这似乎是一个更好的解决方案。但我必须删除 $has_thumbnail 否则如果我重新排列画廊图像,特色图像将不会更新。我不知道是否有办法将现有的 CPT 缩略图与第一个画廊图像进行比较。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-27
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多