把这个放在你的功能上。然后在任何需要的页面中调用该函数。这段代码准备使用css。
if (! function_exists(\'menu_categories\')) {
function menu_categories(){
$cat_args = array( \'orderby\' => \'name\', \'order\' => \'asc\', \'hide_empty\' => true);
$cats = get_terms( \'product_cat\', $cat_args ); ?>
<h1>Categories</h1><?php
foreach ($cats as $key => $cat):
if ($cat->parent == 0): ?>
<div class="tc-menuint-1">
<a href="<?php echo get_term_link($cat) ?>"><?php echo $cat->name; ?></a></li>
<div class="tc-menuint-2"><?php
foreach ($cats as $key => $cat2):
if ($cat2->parent == $cat->term_id): ?>
<div class="tc-menuint-3">
<li><a href="<?php echo get_term_link($cat2) ?>"><?php echo $cat2->name; ?></a></li>
<div class="tc-menuint-4"> <?php
foreach ($cats as $key => $cat3):
if ($cat3->parent == $cat2->term_id): ?>
<li><a href="<?php echo get_term_link($cat3) ?>"><?php echo $cat3->name; ?></a></li><?php
endif;
endforeach; ?>
</div>
</div> <?php
endif;
endforeach; ?>
</div>
</div><?php
endif;
endforeach;
}
}
然后从任何地方调用该函数。
<?php menu_categories(); ?>
嗯,就是这样!!
为了理解php代码,我们得到了如下所有类别:
$cat_args = array( \'orderby\' => \'name\', \'order\' => \'asc\', \'hide_empty\' => true);
$cats = get_terms( \'product_cat\', $cat_args );
foreach ($cats as $key => $cat):
echo \'<a href=\'.get_term_link($cat).\'>\'.$cat->name.\'</a><br>\';
endforeach;
显示所有类别和子类别后:我们可以过滤它以仅显示类别(顶层):
$cat_args = array( \'orderby\' => \'name\', \'order\' => \'asc\', \'hide_empty\' => true);
$cats = get_terms( \'product_cat\', $cat_args );
foreach ($cats as $key => $cat):
if ($cat->parent == 0):
echo \'<a href=\'.get_term_link($cat).\'>\'.$cat->name.\'</a><br>\';
endif;
endforeach;
如果需要子类别,我们可以再次过滤它们:
$cat_args = array( \'orderby\' => \'name\', \'order\' => \'asc\', \'hide_empty\' => true);
$cats = get_terms( \'product_cat\', $cat_args );
foreach ($cats as $key => $cat):
if ($cat->parent == 0):
echo \'<a href=\'.get_term_link($cat).\'>\'.$cat->name.\'</a><br>\';
foreach ($cats as $key => $cat2):
if ($cat2->parent == $cat->term_id):
echo \'<a href=\'.get_term_link($cat2).\' style="color:red;">\'.$cat2->name.\'</a><br>\';
endif;
endforeach;
endif;
endforeach;
然后,如果我们想要一个子类别,我们可以添加另一个代码块,就像在本例中将$cat2更改为例如$cat3之前添加的代码块一样,并将其与父$cat2的term\\u id进行比较。现在,如果出于某种原因,我们需要更多的子类别,我们可以继续下去。。。
$cat_args = array( \'orderby\' => \'name\', \'order\' => \'asc\', \'hide_empty\' => true);
$cats = get_terms( \'product_cat\', $cat_args );
foreach ($cats as $key => $cat):
if ($cat->parent == 0):
echo \'<a href=\'.get_term_link($cat).\'>\'.$cat->name.\'</a><br>\';
foreach ($cats as $key => $cat2):
if ($cat2->parent == $cat->term_id):
echo \'<a href=\'.get_term_link($cat2).\' style="color:red;">\'.$cat2->name.\'</a><br>\';
foreach ($cats as $key => $cat3):
if ($cat3->parent == $cat2->term_id):
echo \'<a href=\'.get_term_link($cat3).\' style="color:green;">\'.$cat3->name.\'</a><br>\';
endif;
endforeach;
endif;
endforeach;
endif;
endforeach;