最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to update custom field in WooCommerce

programmeradmin1浏览0评论

I have added 2 custom fields in a WooCommerce installation using the instructions on this link. It works to save the values but I'm having some problem changing/updating values.

Here is my code that handles the saving:

// Hook save action to database
add_action('woocommerce_process_product_meta', 'woocommerce_save_fields');  

// Save field to database
function woocommerce_save_fields($post_id)
    {
        $myField = $_POST['field_name'];
        if (!empty($myField))
          update_post_meta($post_id, 'field_name', esc_attr($myField), esc_attr($myField));
        else update_post_meta( $post_id, 'field_name', '' );

    }

The if (!empty(...)) saves the field value when first adding it. The else ... allows to empty the field and delete it's value. But I still can't just change the value. And after deleting, I can't save a new value to the fields.

I know my problem is inside this function. But I can't figure it out. Any tips on this?

Thanks

I have added 2 custom fields in a WooCommerce installation using the instructions on this link. It works to save the values but I'm having some problem changing/updating values.

Here is my code that handles the saving:

// Hook save action to database
add_action('woocommerce_process_product_meta', 'woocommerce_save_fields');  

// Save field to database
function woocommerce_save_fields($post_id)
    {
        $myField = $_POST['field_name'];
        if (!empty($myField))
          update_post_meta($post_id, 'field_name', esc_attr($myField), esc_attr($myField));
        else update_post_meta( $post_id, 'field_name', '' );

    }

The if (!empty(...)) saves the field value when first adding it. The else ... allows to empty the field and delete it's value. But I still can't just change the value. And after deleting, I can't save a new value to the fields.

I know my problem is inside this function. But I can't figure it out. Any tips on this?

Thanks

Share Improve this question edited May 20, 2020 at 19:06 TVBZ asked May 20, 2020 at 16:11 TVBZTVBZ 1298 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Okay found it. It was a silly mistake I overlooked. I had 1 attribute (esc_attr($myField)) double inside the update_post_meta() method.

So this function works perfectly:

function woocommerce_save_fields($post_id)
    {
        $myField = $_POST['field_name'];
        if (!empty($myField))
          update_post_meta($post_id, 'field_name', esc_attr($myField));
        else update_post_meta( $post_id, 'field_name', '' );

    }
发布评论

评论列表(0)

  1. 暂无评论