questions

Show or hide admin custom setting fields, based on WooCommerce product type

Rate this post

I made custom field backend, which i want to be showed for simple product types and hided for other types. I think little is not enought to me to achieve it. I will appreciate any help. Thanks! Code I added is:

add_action('admin_head', 'show_this_for_simple_products_and_hide_for_others');
function show_this_for_simple_products_and_hide_for_others() {  
?> 
<script>
    jQuery( function($){

    $( 'body' ).on( 'woocommerce-product-type-change', function( event, select_val, select ) {

        if ( select_val === 'simple' ) {
             // modify to an actual CSS class selector
            $( '.p.form-field.final_product_sku_field' ).show();
        }

    } );

    $( 'select#product-type' ).change();

} );
</script>
<?php
}

 

✔️Solution:

You don’t need that as there is already some CSS class selector that allows that.

To show a field for “simple” product type, you need to add in between your custom setting fields (inside your function):

echo '<div class="show_if_simple hidden">';

// Your fields here (for "simple" products type only)

echo '</div >';

You can use the show_if_{$product_type} or hide_if_{$product_type} composite class selectors, to show or hide custom settings product fields based on the product type (where {$product_type} need to be replaced by the targeted product type).

It works for all custom product types.

The class selector hidden specify that the content is hidden for non specified product types to be shown.

You can also use those other class selectors like show_if_virtual, hide_if_virtual, show_if_downloadable and hide_if_downloadable.

The class selector options_group adds a separator horizontal line.

Here is an example (field is shown only for simple products):

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

    echo '<div class="show_if_simple hidden">';

    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' ),
    ) );

    echo '</div>';
}

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

Leave a Reply

Your email address will not be published.

Back to top button