我已使用code sample from Woocommerce's site为Woocommerce中的单个产品页面添加了自定义产品标签。
我希望自定义标签仅在有内容时有条件地显示。为此,我使用以下代码:
// Set a global variable for the custom tab content to pass it to the callback function that displays the tab content.
$features_tab_content = '';
function woo_new_product_tab($tabs) {
global $post, $features_tab_content;
$custom_fields = array(
'field_one'=>'Field One',
'field_two'=>'Field Two'
);
$fields_to_display = array();
foreach ($custom_fields as $fieldname=>$fieldtitle) {
$$val = get_post_meta( $post->ID, $fieldname, true );
if ($$val != '') {
$fields_to_display[$fieldtitle] = $$val;
}
}
if (count($fields_to_display) > 0) {
$features_tab_content = '<h2>Product Features</h2><table class="shop_attributes"><tbody>';
foreach ($fields_to_display as $fieldtitle=>$val) {
$features_tab_content .= '<tr><th>' . $fieldtitle . '</th><td>' . $val . '</td></tr>';
}
$features_tab_content .= '</tbody></table>';
$tabs['features'] = array(
'title' => __( 'Features', 'woocommerce' ),
'priority' => 20,
'callback' => 'woo_new_product_tab_content'
);
}
return $tabs;
}
function woo_new_product_tab_content() {
global $features_tab_content;
echo $features_tab_content;
}
add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
代码测试woo_new_product_tab
函数中自定义选项卡内容是否存在,并使用名为$features_tab_content
的变量来保存实际内容。
问题在于我无法弄清楚如何将内容传递给实际显示内容的回调函数,因此我在函数中使$features_tab_content
变量全局化并在回调中使用它函数woo_new_product_tab_content
。
这似乎有点笨拙,但它比测试两种功能中的内容要好。我不想使用插件来执行此操作,但我想知道是否有更简洁的方法来编写它。
答案 0 :(得分:0)
您可以在过滤$ tabs时检查是否存在要显示的元数据:
add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {
global $post;
if( get_post_meta( $post->ID, 'field_one', true ) || get_post_meta( $post->ID, 'field_two', true ) ){
// Adds the new tab
$tabs['features'] = array(
'title' => __( 'Features', 'stackoverflow' ),
'priority' => 20,
'callback' => 'woo_new_product_tab_content'
);
}
return $tabs;
}
没有全局变量的回调:
function woo_new_product_tab_content() {
global $post;
$custom_fields = array(
'field_one'=>'Field One',
'field_two'=>'Field Two'
);
$fields_to_display = array();
foreach ($custom_fields as $fieldname=>$fieldtitle) {
$$val = get_post_meta( $post->ID, $fieldname, true );
if ($$val != '') {
$fields_to_display[$fieldtitle] = $$val;
}
}
// The new tab content
if (count($fields_to_display) > 0) {
echo '<h2>Product Features</h2><table class="shop_attributes"><tbody>';
foreach ( $fields_to_display as $fieldtitle => $val ) {
echo '<tr><th>' . $fieldtitle . '</th><td>' . $val . '</td></tr>';
}
echo '</tbody></table>';
}
}