【问题标题】:How to update a field while creating a new post with ACF form如何在使用 ACF 表单创建新帖子时更新字段
【发布时间】:2022-01-02 18:27:00
【问题描述】:

我在 WordPress 网站的前端使用 ACF 表单。 “Post A”中的 ACF 表单创建了一个新帖子“Post B”。我正在尝试创建一个函数来更新 Post A 中的 ACF 字段(然后我将使用它从 Post A 中删除表单,以便它只能提交一次)。我一直在尝试使用 acf/save_post 操作来更新字段,但这似乎只影响 Post B 而不是 Post A。这是我的代码:

<?php 
add_action('acf/save_post', 'update_post_status', 20);

function update_post_status( $post_id ) {

    if( get_post_type($post_id) !== 'mypost' ) {
        return;
    }
  
    update_field('form_submitted', 'yes');
  
}
?>

【问题讨论】:

    标签: php wordpress advanced-custom-fields acfpro


    【解决方案1】:

    我认为您为此任务使用了不正确的钩子

    acf-save_post

    
    Fires when saving the submitted $_POST data.
    
    

    你可以使用'save_post'

    Save_post is an action triggered whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. The data for the post is stored in $_POST, $_GET or the global $post_data, depending on how the post was edited. For example, quick edits use $_POST.
    

    例如

    add_action( 'save_post', 'my_save_post_function', 10, 3 );
    
    function my_save_post_function( $post_ID, $post, $update ) {
        if( get_post_type($post_ID) !== 'mypost' ) {
            return;
        }
      
        update_field('form_submitted', 'yes', $post_ID);
    }
    

    【讨论】:

    • 这似乎执行了更新 Post B 而不是 Post A 的相同功能。它还运行在后端保存以及表单提交上,这可能会导致一些问题。
    【解决方案2】:

    我成功地使用了acf/validate_save_post 而不是acf/save_post,因为它在创建新帖子之前触发,因此该函数仍然引用原始帖子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 2021-08-11
      • 2021-01-05
      • 2021-07-10
      • 2014-01-29
      • 2021-07-06
      • 2021-05-18
      相关资源
      最近更新 更多