简体   繁体   中英

Add a field only on admin products from a custom type in WooCommerce

I made custom field in product backend, that I want to be only for Product type pw-gift-card :

function creating_final_sku_field(){
    global $product;
        
    if ($product->is_type('pw-gift-card')) {    
        $args = array(
            'label' => __( 'Final SKU', 'woocommerce' ),
            'placeholder' => __( 'Enter final SKU here', 'woocommerce' ),
            'id' => 'final_sku',
            'desc_tip' => true,
            'description' => __( 'This SKU is for final use only.', 'woocommerce' ),
        );
        woocommerce_wp_text_input( $args );
    }
}
add_action( 'woocommerce_product_options_sku', 'creating_final_sku_field' );

This is code throws a critical error.
Any help is appreciated.

The main error comes from undefined $product variable. Try the following instead:

add_action( 'woocommerce_product_options_sku', 'add_product_final_sku_custom_field' );
function add_product_final_sku_custom_field(){
    global $post, $product_object;

    if ( ! is_a( $product_object, 'WC_Product' ) ) {
        $product_object = wc_get_product( $post->ID );
    }
        
    if ( $product_object->is_type('pw-gift-card') ) {    
        woocommerce_wp_text_input( array(
            'label' => __( 'Final SKU', 'woocommerce' ),
            'placeholder' => __( 'Enter final SKU here', 'woocommerce' ),
            'id' => 'final_sku',
            'desc_tip' => true,
            'description' => __( 'This SKU is for final use only.', 'woocommerce' ),
        ) );
    }
}

Code goes in functions.php file of the active child theme (or active theme).

Important Note: Specifying a product type as condition will not work when adding a new product , as the product type is not yet saved. This need to be done some CSS...

在此处输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM