Reputation: 266
I have a custom post type set up with some ACF fields. I also have an ACF options page set up.
I'm trying to update a text field on all custom posts with a value from a text field within the options page, when the options page is updated.
Here's what I've tried:
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');
Ideally I also want to only update the posts field if the global field value has changed.
Upvotes: 4
Views: 3517
Reputation: 2906
You are probably looking for the acf/save_post
hook. This is triggered whenever your ACF options page is getting saved. Just make sure that the current screen has the id of your options page.
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');
Does that get you anywhere?
EDIT: Since you asked to only update data if the global value has changed, you should do the following:
1 Give your acf/save_post
action a priority higher than 10:
add_action('acf/save_post', 'my_function', 5);
2 Get the old and new value:
$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 Compare them if($old_value != $new_value)
Upvotes: 5