I added a custom price field to WooCommerce. The field appears as expected BUT it does not save the values entered.
My code in my functions.php
file is:
/* 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' );
You have some minor mistakes, this should suffice
Also note the use of woocommerce_admin_process_product_object
to save instead of the outdated 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 );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.