我试图在创建该帖子后设置custom post type
中字段的值。下面是我的代码:
add_action('acf/save_post', 'set_coach_email');
function set_coach_email( $post_id ){
$posttype = get_post_type($post_id);
if ('team' !== $posttype){
return;
}
$email = 'test@test.com';
update_field('coach_email', $email, $post_id);
}
我用ACF fields
来创建这个自定义的帖子类型,但是我似乎不能让它工作。
我会检查相反的条件检查。此外,我首先检查字段是否为空,然后我只运行更新,如果字段为空。
add_action('acf/save_post', 'set_coach_email');
function set_coach_email($post_id)
{
$posttype = get_post_type($post_id);
$email_field = get_field('coach_email', $post_id);
if ('team' == $posttype && empty($email_field)) {
$email = 'coachtest@test.com';
update_field('coach_email', $email, $post_id);
}
}
刚刚测试了我自己的自定义帖子类型,它工作得很好。如果你也能让它工作,请告诉我!
我发现有时使用acf/save_post
,提高优先级可以确保在运行动作函数之前运行其他所有内容。
当在get_field()
函数中传递$post_id
时,这可能会起作用,当使用acf/save_post
时,我倾向于不传递$post_id
,以确保使用当前最新的字段数据。但这一理论可能并非如此。
<?php
// save post action with priority 20 (default 10)
add_action('acf/save_post', 'set_coach_email', 20);
/**
* @param $post_id int|string
*/
function set_coach_email($post_id) {
// get our current post object
$post = get_post($post_id);
// if post is object
if(is_object($post)) {
// check we are on the team custom type and post status is either publish or draft
if($post->post_type === 'team' && ($post->post_status === 'publish' || $post->post_status === 'draft')) {
// get coach email field
$coach_email = get_field('coach_email');
// if coach email field returns false
if(!$coach_email) {
// coach email default
$email = 'coachtest@test.com';
// update coach email field
update_field('coach_email', $email, $post->ID);
}
}
}
// finally return
return;
}