WooCommerce 产品页面默认有3个选项卡:描述,其它信息和评论,对于很多 WordPress 主题或许不太适合,需要修改或者添加选项卡。WooCommerce 官方文档已经给出了详细的文档:
需要将代码添加到主题functions.php文件。
1、删除选项卡
/**
* 删除产品数据选项卡
*/
add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );
function woo_remove_product_tabs( $tabs ) {
unset( $tabs['description'] ); // 删除描述
unset( $tabs['reviews'] ); // 删除评论
unset( $tabs['additional_information'] ); // 删除其它信息
return $tabs;
}
2、重命名选项卡
/**
* 重命名选项卡
*/
add_filter( 'woocommerce_product_tabs', 'woo_rename_tabs', 98 );
function woo_rename_tabs( $tabs ) {
$tabs['description']['title'] = __( '产品详情' ); // 重命名描述
$tabs['reviews']['title'] = __( '产品评论' ); // 签名评论
$tabs['additional_information']['title'] = __( '产品参数' ); // 签名其它信息
return $tabs;
}
3、更改选项卡顺序
/**
* 更改选项卡顺序
*/
add_filter( 'woocommerce_product_tabs', 'woo_reorder_tabs', 98 );
function woo_reorder_tabs( $tabs ) {
$tabs['reviews']['priority'] = 5; // 评论第一
$tabs['description']['priority'] = 10; // 描述第二
$tabs['additional_information']['priority'] = 15; // 其它信息第三
return $tabs;
}
4、自定义选项卡内容
/**
* 自定义选项卡内容
*/
add_filter( 'woocommerce_product_tabs', 'woo_custom_description_tab', 98 );
function woo_custom_description_tab( $tabs ) {
$tabs['description']['callback'] = 'woo_custom_description_tab_content'; // 自定义描述回调
return $tabs;
}
/**
* 选项卡内容
*/
function woo_custom_description_tab_content() {
echo '<h2>Custom Description</h2>';
echo '<p>Here\'s a custom description</p>';
}
5、添加自定义选项卡
/**
* 添加一个自定义选项卡
*/
add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {
// 添加一个新选项卡
$tabs['test_tab'] = array(
'title' => __( '名称', 'woocommerce' ),
'priority' => 50,
'callback' => 'woo_new_product_tab_content'
);
return $tabs;
}
/**
* 选项卡内容
*/
function woo_new_product_tab_content() {
// The new tab content
echo '<h2>New Product Tab</h2>';
echo '<p>Here\'s your new product tab.</p>';
}
6、附加信息选项卡
“附加信息”选项卡仅在产品设置了重量、尺寸或属性,并选中“在产品页面上可见”时才会显示。如果在产品没有重量、尺寸或属性时,尝试对该选项卡更改,将出现类似于以下的错误消息:
Warning: call_user_func() expects parameter 1 to be a valid callback, no array or string given in /mysite/wp-content/plugins/woocommerce/templates/single-product/tabs/tabs.php on line 35
在这种情况下,必须使用 WooCommerce 条件判断:
has_attributes()
has_dimensions()
has_weight()
比如此段代码:
/**
* 检查产品是否有属性、尺寸或重量
*/
add_filter( 'woocommerce_product_tabs', 'woo_rename_tabs', 98 );
function woo_rename_tabs( $tabs ) {
global $product;
if( $product->has_attributes() || $product->has_dimensions() || $product->has_weight() ) {
$tabs['additional_information']['title'] = __( '产品参数' ); // 重命名附加信息选项卡
}
return $tabs;
}
有了这些代码,稍作修改,定制选项卡易如反掌。