Home Wordpress Adding a woocommerce custom filed drop down
Wordpress - October 21, 2015

Adding a woocommerce custom filed drop down

Here is the simple way to achieve a simple Woo-commerce custom drop-down to show custom attribute. For example in my shop i have a product color.

// Product Custom Files for Color //

add_action( 'woocommerce_product_options_sku', 'wc_color_product_field' );
function wc_color_product_field() {
   woocommerce_wp_select( 
    array( 
    'id'      => 'wc_color', 
    'label'   => __( 'Product Color', 'woocommerce' ), 
    'options' => array(
        'one'   => __( 'Blue', 'woocommerce' ),
        'two'   => __( 'Black', 'woocommerce' ),
        'three' => __( 'Pink', 'woocommerce' ),
        'four' => __( 'Purple ', 'woocommerce' ),
        'five' => __( 'Yellow ', 'woocommerce' )
        )
    )
);
}

add_action( 'save_post', 'wc_color_save_product' );
function wc_color_save_product( $product_id ) {
    // 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['wc_color'] ) ) {
        if ( is_numeric( $_POST['wc_color'] ) )
            update_post_meta( $product_id, 'wc_color', $_POST['wc_color'] );
    } else delete_post_meta( $product_id, 'wc_color' );
}

add_action( 'woocommerce_single_product_summary', 'wc_rrp_show', 5 );
function wc_rrp_show() {
    global $product;
    // Do not show this on variable products
    if ( $product->product_type <> 'variable' ) {
        $rrp = get_post_meta( $product->id, 'wc_color', true );
        echo '<div class="woocommerce_msrp">';
        _e( 'RRP: ', 'woocommerce' );
        echo '<span class="woocommerce-wc-color">' . woocommerce_price( $rrp ) . '</span>';
        echo '</div>';
    }
}

// Optional: To show on archive pages
add_action( 'woocommerce_after_shop_loop_item_title', 'wc_color_show' );

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also

The Speed of Nine Planet

Sun : Astronomically the Sun is fixed and it is the planets which are moving round Sun. Bu…