【问题标题】:Programatically update an ACF field for all posts when an ACF options page is updated更新 ACF 选项页面时,以编程方式更新所有帖子的 ACF 字段
【发布时间】:2021-07-10 14:12:47
【问题描述】:

我有一个自定义帖子类型,其中包含一些 ACF 字段。我还设置了一个 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');

理想情况下,如果全局字段值已更改,我也只想更新帖子字段。

【问题讨论】:

  • 只是为了翻转一些逻辑,您真的需要更新每个 CPT 吗?您可以直接从渲染选项中提取吗?根据您拥有的 CPT 数量,每个 CPT 的更新最终都会随着时间的推移而开始变慢,并且可能会超时。

标签: php database wordpress advanced-custom-fields


【解决方案1】:

您可能正在寻找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)

【讨论】:

  • 你能关闭赏金还是需要更多帮助?
猜你喜欢
  • 1970-01-01
  • 2021-08-11
  • 2021-12-08
  • 1970-01-01
  • 2019-11-17
  • 1970-01-01
  • 2022-01-02
  • 2019-09-28
  • 2016-03-07
相关资源
最近更新 更多