Create a product meta and verify nonce PHPCS way

/**
 * Adds custom field to General tab in Product data
 */
function woocommerce_new_price() {
	woocommerce_wp_text_input(
		[
			'id' => '_new_product_price',
			'placeholder' => '',
			'label' => __( 'New price', 'two' ),
			'type' => 'number',
		]
	);
}
add_action( 'woocommerce_product_options_general_product_data', 'woocommerce_new_price' );

/**
 * Saves new price when product is saved/updated
 */
function save_woocommerce_new_price( $post_id ) {
	$nonce = wp_create_nonce( '_new_product_price' );
	if ( empty( $nonce ) || ! wp_verify_nonce( wp_unslash( $nonce ), '_new_product_price' ) ) {
			return;
	}
	$product = wc_get_product( $post_id );
	$new_price = ! empty( sanitize_key( wp_unslash( $_POST['_new_product_price'] ) ) ) ? sanitize_key( wp_unslash( $_POST['_new_product_price'] ) ) : '';
	$product->update_meta_data( '_new_product_price', esc_attr( $new_price ) );
	$product->save();
}
add_action( 'woocommerce_process_product_meta', 'save_woocommerce_new_price' );

Leave a Reply

Your email address will not be published.