Search code examples
phpwordpresswoocommerceproductadvanced-custom-fields

Hide custom product tab if content is empty in WooCommerce single products


I created a field in ACF plugin. I added the code below to show the data as a custom tab but the tab is always visible even if the field is empty. What am I missing?


// 1.Displays the tab on every product page
add_filter( 'woocommerce_product_tabs', 'woo_new_tab' );
    function woo_new_tab( $tabs ) { 
    // Adds the new tab 
        if (!empty(get_the_content())) {
            $tabs['application'] = array(
                'title'     => __( 'Application', 'woocommerce' ),
                'priority'  => 20,
                'callback'  => 'woo_new_tab_content'
            );
        return $tabs;
        }
    }

// the callback (refer to https://www.advancedcustomfields.com/resources/code-examples/) for more info
function woo_new_tab_content() {
// The new tab content
//Working with Array values (checkbox, select, relationship, repeater) use below

    $values = get_field('application'); //field name
    if($values){
        echo '<ul>';
        foreach($values as $value){
            echo '<li>' . $value . '</li>';
        }
        echo '</ul>';
    }
}

Solution

  • To hide a custom product tab when it's content is empty, use instead:

    // Add a custom product tab on single product pages
    add_filter( 'woocommerce_product_tabs', 'woo_new_tab' );
    function woo_new_tab( $tabs ) { 
        $values = get_field('application');
    
        // Adds the new tab 
        if ( ! empty($values) ) {
            $tabs['application'] = array(
                'title'     => __( 'Application', 'woocommerce' ),
                'priority'  => 20,
                'callback'  => 'woo_new_tab_content'
            );
        }
        return $tabs;
    }
    
    // Displays the tab content 
    function woo_new_tab_content() {
        $values = (array) get_field('application');
    
        echo '<ul>';
    
        foreach ( $values as $value ) {
            echo '<li>' . $value . '</li>';
        }
        echo '</ul>';
    }