André Amorim

Crafting Web Experiences


//

How to add a custom tab to product information of WooCommerce

<?php 
// Show only if user is administrator or reseller
if (
    my_get_current_user_roles()[0] == 'administrator' ||
    my_get_current_user_roles()[0] == 'wholesale_customer' ||
    my_get_current_user_roles()[0] == 'price_b2b'
) {

    // Add a custom tab called "Tabela Nutricional"
    add_filter('woocommerce_product_tabs', 'woo_product_tab_tabela_nutricional');

    function woo_product_tab_tabela_nutricional($tabs) {
        $tabs['tabela_nutricional'] = array(
            'title'    => 'Tabela Nutricional',
            'priority' => 10,
            'callback' => 'render_woo_product_tab_tabela_nutricional'
        );

        return $tabs;
    }

    // Callback: render the tabela
    function render_woo_product_tab_tabela_nutricional() {
        // Get tabela from ACF field added to product
        $tabela = get_field('produto_tabela_nutricional');

        if (empty($tabela)) {
            echo 'Este produto não tem uma tabela nutricional!';
        } else {
            echo $tabela;
        }
    }
}

// Get the current user roles
function my_get_current_user_roles() {
    if (is_user_logged_in()) {
        $user  = wp_get_current_user();
        $roles = (array) $user->roles;

        return $roles; // Returns an array
    } else {
        return [0];
    }
}

Published date:

Modified date: