WordPress Snippets

How to add a custom tab to product information of WooCommerce

<?php
//Show only if is administrator and 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 post-type 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; // This will returns an array
	} else {
		return [0];
	}
}

Leave a Reply