我用一些ACF字段设置了一个自定义的post类型。我还设置了一个ACF选项页面。
当选项页面更新时,我正试图用选项页面中文本字段的值更新所有自定义帖子的文本字段。
以下是我尝试过的:
function update_global_flash_text(){
$current_page = get_current_screen()->base;
if($current_page == 'toplevel_page_options') {
function update_global_servicing_text() {
$args = array(
'post_type' => 'custom',
'nopaging' => true,
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
update_field('servicing_flash_text', $_POST['global_servicing_offer_text']);
}
}
wp_reset_postdata();
}
if(array_key_exists('post',$_POST)){
update_global_servicing_text();
}
}
}
add_action('admin_head','update_global_flash_text');
理想情况下,我只想在全局字段值发生更改时更新posts字段。
您可能正在寻找acf/save_post
挂钩。每当保存ACF选项页面时,就会触发此操作。只需确保当前屏幕具有选项页面的id即可。
function my_function() {
$screen = get_current_screen();
/* You can get the screen id when looking at the url or var_dump($screen) */
if ($screen->id === "{YOUR_ID}") {
$new_value = get_field('global_servicing_offer_text', 'options');
$args = array(
'post_type' => 'custom',
'nopaging' => true,
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
update_field('servicing_flash_text', $new_value);
}
}
wp_reset_postdata();
}
}
add_action('acf/save_post', 'my_function');
这能让你有所收获吗?
编辑:由于您要求只在全局值发生更改时更新数据,因此您应该执行以下操作:
1将acf/save_post
操作的优先级设置为高于10:
add_action('acf/save_post', 'my_function', 5);
2获取新旧价值:
$old_value = get_field('global_servicing_offer_text', 'options');
// Check the $_POST array to find the actual key
$new_value = $_POST['acf']['field_5fd213f4c6e02'];
3比较它们if($old_value != $new_value)