首页 > 解决方案 > WooCommerce:在保存帖子之前更新字段值

问题描述

我在 WooCommerce 中有一个额外的自定义字段(高级自定义字段)来显示一些产品亮点。这些突出显示在 HTML 中的格式如下:

<li>Supports thousands of apps</li>
<li>1080p maximum display resolution</li>
<li>Supports both 2.4 Ghz and 5 Ghz Wi-Fi networks</li>
<li>Supports iOS</li>

我需要它们的格式如下

<g:product_highlight>Supports thousands of apps</g:product_highlight>
<g:product_highlight>1080p maximum display resolution</g:product_highlight>
<g:product_highlight>Supports both 2.4 Ghz and 5 Ghz Wi-Fi networks</g:product_highlight>
<g:product_highlight>Supports iOS</g:product_highlight>

基本上我只需要更改标签并将内容保存在第二个元字段中。

我找到了一个文档来更新特定字段的值在保存帖子时触发操作

我的片段如下所示:

add_action('acf/save_post', 'my_acf_save_post', 5);
function my_acf_save_post( $post_id ) {

    // Get previous values.
    $prev_values = get_fields( $post_id );

    // Get submitted values.
    $values = $_POST['acf'];

    // Check if a specific value was updated.
    if( isset($_POST['acf']['product_details_usp']) ) {
        
        $field_key = "product_details_usp_google";
        $value = "some new string";
        update_field( $field_key, $value, $post_id );
        
    }
}

我要更改数据的元字段是product_details_usp. 我现在想更改该字段中的数据(下一步)并将其保存在product_details_usp_google.

但它不起作用。没有数据从一个字段传输到另一个字段。我的代码有什么问题吗?

标签: phpwordpresswoocommerceadvanced-custom-fields

解决方案


我找到了一个基于来自 LoicTheAztec 的答案的解决方案

add_action( 'save_post', 'update_usp_google_shopping' );
function update_usp_google_shopping( $post_id ){

    // Only for shop order
    if ( 'product' != $_POST[ 'post_type' ] )
        return $post_id;

    // Checking that is not an autosave
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $post_id;

    // Check the user’s permissions (for 'shop_manager' and 'administrator' user roles)
    if ( ! current_user_can( 'edit_shop_order', $post_id ) && ! current_user_can( 'edit_shop_orders', $post_id ) )
        return $post_id;

    // Updating custom field data
    if( isset( $_POST['acf'] ) ) {
                    
        // The new value
        $value = 'Test';

        // OR Get an Order meta data value ( HERE REPLACE "meta_key" by the correct metakey slug)
        // $value = get_post_meta( $post_id, 'meta_key', true ); // (use "true" for a string or "false" for an array)

        // Replacing and updating the value
        update_post_meta( $post_id, 'product_details_usp_google', $value );
    }
}

代码将 Test 值添加到新的自定义字段。


推荐阅读