Menu Close

Add field for showing retail price for WooCommerce Products

Codeamend

Use the following steps to add product custom field for retail price.

Step 1: Add Custom field input at product add / edit page

<?php add_action( 'woocommerce_product_options_pricing', 'code_add_retail_to_products' );      
function code_add_retail_to_products() {          
    woocommerce_wp_text_input( array( 
        'id' => 'retailprice', 
        'class' => 'short wc_input_price', 
        'label' => __( 'Retail price', 'woocommerce' ) . ' (' . get_woocommerce_currency_symbol() . ')',
        'data_type' => 'price', 
    ));      
} ?> 

Step 2: Save Retail field via custom field

<?php add_action( 'save_post_product', 'code_save_retail' );
function code_save_retail( $product_id ) {
    global $pagenow, $typenow;
    if ( 'post.php' !== $pagenow || 'product' !== $typenow ) return;
    if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) return;
    if ( isset( $_POST['retailprice'] ) ) {
    if ( $_POST['retailprice'] )
        update_post_meta( $product_id, 'retailprice', $_POST['retailprice'] );
    } else delete_post_meta( $product_id, 'retailprice' );
} ?> 

Step 3: Display Retail field at single product page

<?php
add_action( 'woocommerce_single_product_summary', 'code_display_retail', 9 );
function code_display_retail() {
    global $product;
    if ( $retailprice = get_post_meta( $product->get_id(), 'retailprice', true ) ) {
        echo '<div class="woocommerce_retail">';
        _e( 'Retail price: ', 'woocommerce' );
        echo '<span>' . wc_price( $retailprice ) . '</span>';
        echo '</div>';
    }
}
?> 
Posted in PHP, WooCommerce, WordPress

You can also read...