Add Custom Cost Price Field To Product

add custom cost price field to product

Add Custom Cost Price Field To Product

 |   |  0
WooCommerce WordPress

Here, I explain how to Add custom cost price field to product in WordPress – WooCommerce.

Add a field to the interface:-

add_action( 'woocommerce_product_options_pricing', 'wc_cost_product_field' );
function wc_cost_product_field() {
  woocommerce_wp_text_input( 
    array( 
      'id' => 'cost_price', 
      'class' => 'wc_input_price short', 
      'label' => __( 'Cost Price', 'woocommerce' ) . ' (' . get_woocommerce_currency_symbol() . ')'
    ) 
  );
}

To save the new custom cost price field:-

add_action( 'save_post', 'wc_cost_save_product' );
function wc_cost_save_product( $product_id ) {
 
  // stop the quick edit interferring as this will stop it saving properly
  // when a user uses quick edit feature
  if(isset($_POST['_inline_edit'])) {
    if (wp_verify_nonce($_POST['_inline_edit'], 'inlineeditnonce'))
    return;
  }
 
  // If this is a auto save do nothing, we only save when update button is clicked
  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
    return;
  if ( isset( $_POST['cost_price'] ) ) {
    if ( is_numeric( $_POST['cost_price'] ) )
      update_post_meta( $product_id, 'cost_price', $_POST['cost_price'] );
    } else delete_post_meta( $product_id, 'cost_price' );
}

Enjoy…


1 Claps

Show your love in the form of Claps and Comments...

Comments...

No comments found. Leave your reply here.