Wordpress + Timber + ACF Pro。在functions.php中,每当发布一个帖子(周类型)时,我都会触发一个动作。
我想从这篇文章中获取数据,并使用它为每个用户创建一个新帖子。
我让它在时尚之后工作。发布帖子时,我会获取标题和用户名,并将其用作新创建帖子的标题。
但是,我在尝试提取ACF数据时遇到了问题 - 例如:一个星期开始日期字段。所有ACF数据都返回NULL(我知道填充了字段)。
我已经阅读了文档 - 要访问数据的状态,你需要调用get_field('field_name','post_id') - 我已经完成了。
我已经写出了$ ID - 所以知道这是正确的。
这可能是由于我运行的顺序?
这是我的代码:
function weekly_published_post_setup($ID, $post) {
$customers = get_users();
$theDate = get_field("week_commencing", $ID);
// Array of WP_User objects.
foreach ( $customers as $user ) {
$new_post = array(
'post_type' => 'weekly_tasks',
'post_title' => $post->post_title . ' - ' . $theDate . ' - ' . $user->display_name,
'post_content' => $theDate,
'post_status' => 'publish',
'post_author' => $user->ID
);
wp_insert_post($new_post);
}
}
add_action( 'publish_week', 'weekly_published_post_setup', 10, 2 );
**编辑**
事实证明,在创建ACF字段之前,wordpress帖子已被保存?因此,朋友重构了我的代码以使用不同的事件。但是,发布帖子时不会触发...
function week_published_delivery_setup($ID) {
$post = get_post($ID);
if ($post->post_type != 'week') {
return;
}
if( $post->post_modified_gmt != $post->post_date_gmt ){
return;
}
$customers = get_users();
$field = get_field('week_commencing', $ID);
$fields = post.get_field_objects($ID);
if( $fields )
{
foreach( $fields as $field_name => $field )
{
$tmp .= $field['label'] . $field['value'];
}
}*/
// Array of WP_User objects.
foreach ( $customers as $user ) {
$new_delivery_post = array(
'post_type' => 'delivery',
'post_title' => $post->post_title . ' - ' . $field . ' - ' . $user->display_name,
'post_content' => $post->post_title,
'post_status' => 'publish',
'post_author' => $user->ID
);
wp_insert_post($new_delivery_post);
}
}
add_action( 'acf/save_post', 'week_published_delivery_setup', 20);
答案 0 :(得分:0)
所以现在测试发布时的帖子状态 - 然后执行所需的操作。触发操作如果old_status == future,new_status == publish似乎可以解决问题。
function on_all_status_transitions( $new_status, $old_status, $post ) {
$ID = $post->ID;
if ($post->post_type != 'week') {
return;
}
if ( $new_status != $old_status && $old_status == 'future' && $new_status == 'publish' ) {
$customers = get_users();
$field = get_field('week_commencing', $ID);
// Array of WP_User objects.
foreach ( $customers as $user ) {
$new_delivery_post = array(
'post_type' => 'delivery',
'post_title' => $post->post_title . ' - ' . $field . ' - ' . $user->display_name,
'post_content' => $post->post_title,
'post_status' => 'publish',
'post_author' => $user->ID
);
wp_insert_post($new_delivery_post);
}
}
}
add_action( 'transition_post_status', 'on_all_status_transitions', 20, 3 );