我有一个自定义代码片段,用于在产品页面上显示自定义选项卡。内容是带有中继器字段的 ACF 文件字段。 它工作正常,当我设置产品的文件时,它们都按照我希望的方式显示在产品页面上。 我希望如果没有指定文件,该选项卡也不应该出现。
这是我使用的代码:
add_filter( 'woocommerce_product_tabs', 'woostify_custom_tab' );
function woostify_custom_tab( $tabs ) {
if( get_field('letoltheto_katalogusok') ) {
$tabs['tab-catalogues'] = array(
'title' => 'Letölthető katalógus',
'callback' => 'woostify_custom_tab_content',
'priority' => 25,
);
}
return $tabs;
}
function woostify_custom_tab_content( $slug, $tab ) {
if (have_rows('letoltheto_katalogusok')) {
while (have_rows('letoltheto_katalogusok')) {
the_row();
$file = get_sub_field('letoltheto_katalogus');
$file2 = get_sub_field('letoltheto_katalogusa');
$file3 = get_sub_field('letoltheto_katalogusb');
?>
<br>
<div class="katalogusok">
<a href="<?php echo $file['url']; ?>" target="_blank" ><?php echo $file['filename']; ?></a>
<a href="<?php echo $file2['url']; ?>" target="_blank" ><?php echo $file2['filename']; ?></a>
<a href="<?php echo $file3['url']; ?>" target="_blank" ><?php echo $file3['filename']; ?></a>
</div>
<?php
}
}
}
大家有什么想法吗?
对添加选项卡的部分执行相同的操作,就像在实际填充选项卡的代码中所做的那样 - 使用
have_rows('letoltheto_katalogusok')
检查中继器是否实际上包含要循环的内容。
function woostify_custom_tab( $tabs ) {
if( have_rows('letoltheto_katalogusok') ) {
$tabs['tab-catalogues'] = array(
'title' => 'Letölthető katalógus',
'callback' => 'woostify_custom_tab_content',
'priority' => 25,
);
}
return $tabs;
}
注意
have_rows
是“动态的”,一旦所有行都被迭代,它将返回 false (这就是为什么它可以在所有行都输出后终止 while
循环。)但是因为此时你是 不是迭代行,当它进入 woostify_custom_tab_content
函数中的循环时,它仍然会保留相同的初始 true 或 false 值。