【发布时间】: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