php - 自定义价格字段未保存在 WooCommerce 中的管理产品中

标签 php wordpress woocommerce product hook-woocommerce

我向 WooCommerce 添加了自定义价格字段。该字段按预期显示,但它不保存输入的值。

我的 functions.php 文件中的代码是:

/* Add custom price field to general page */
function wc_cost_product_field() {
    woocommerce_wp_text_input( array( 'id' => 'wholesaler_price', 'class' => 'wc_input_price short', 'label' => __( 'Wholesaler price', 'woocommerce' ) . ' (' . get_woocommerce_currency_symbol() . ')' ) );
}

add_action( 'woocommerce_product_options_pricing', 'wc_cost_product_field' );

function pcc_save_custom_price( $post_id ) {
    // Grab the custom price from $_POST
    $custom_price = isset( $_POST[ 'wholesale_price' ] ) ? sanitize_text_field( $_POST[ 'wholesale_price' ] ) : '';

    // grab the product
    $product = wc_get_product( $post_id );

    // Save the custom price using WooCommerce built-in functions
    $product->update_meta_data( 'wholesale_price', $custom_price );
    $product->save();
}

add_action( 'woocommerce_process_product_meta', 'pcc_save_custom_price' );

最佳答案

你有一些小错误,这应该足够了

还要注意使用 woocommerce_admin_process_product_object 来保存而不是过时的 woocommerce_process_product_meta Hook

/* Add custom price field to general page */
function action_woocommerce_product_options_pricing() { 
    woocommerce_wp_text_input( array(
        'id' => 'wholesaler_price', 
        'class' => 'wc_input_price short', 
        'label' => __( 'Wholesaler price', 'woocommerce' ) . ' (' . get_woocommerce_currency_symbol() . ')',
    ) );
}

add_action( 'woocommerce_product_options_pricing', 'action_woocommerce_product_options_pricing', 10, 0 );

// Save Fields
function action_woocommerce_admin_process_product_object( $product ) {
    if( isset($_POST['wholesaler_price']) ) {
        $product->update_meta_data( 'wholesaler_price', sanitize_text_field( $_POST[ 'wholesaler_price'] ) );
    }
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 ); 

关于php - 自定义价格字段未保存在 WooCommerce 中的管理产品中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62437702/

相关文章:

php - 从多维数组到 MySQL

php - 获取 youtube 订阅者列表给我 400 错误

javascript - WordPress 的 video.js : JavaScript error in IE 8

css - Wordpress 子菜单在悬停时消失

php - 禁用特定运输方式的支付网关

javascript - 提交而不重新加载页面

php - 使用 PHP 在 Mongo DB 中的文档中添加数据

WordPress 标签 - 从预先确定的列表中选择?

php - 从 Woocommerce 中的产品页面库存显示中删除 "can be backordered"

javascript - WooCommerce:如何将监听器添加到 "found_variation"事件