我显示类别列表作为选择字段的选项。问题在于,每个类别看起来都相同。即使它们是子类别。
例如,我的类别树看起来像这样:
但是在选择字段中显示为:
这是我的代码,用于在表单中填充选择字段:
function populate_dropdown_with_product_categories( $form ) {
//product_cat is the taxonomy for WooCommerce's products
//get the terms for the product_cat taxonomy
$product_categories = get_terms( 'product_cat', array('hide_empty' => false,) );
//Creating drop down item array.
$items = array();
//Adding product category terms to the items array
foreach ( $product_categories as $product_category ) {
$items[] = array( 'value' => $product_category->name, 'text' => $product_category->name );
}
//Adding items to field id 6. Replace 6 with your actual field id. You can get the field id by looking at the input name in the markup.
foreach ( $form['fields'] as &$field ) {
if ( $field->id == 64 ) {
$field->choices = $items;
}
}
return $form;
}
我想我需要在此行中添加类别的级别:
$items[] = array( 'value' => $product_category->name, 'text' => $product_category->name );
但是我该怎么做?对我来说,如果每个级别在名称之前都获得一个-
(对于第三级别,则为两个-
...)就足够了。
类似这样的东西:
- Main category
-- Sub category
--- Third level category
我找到了解决方案。我已经更改了foreach
代码,如下所示:
foreach ( $product_categories as $product_category ) {
$product_category_level = count( get_ancestors($product_category->term_id, 'product_cat'));
if ($product_category_level == 1 ) :
$product_category_level_indicator = '- ';
elseif ($product_category_level == 2 ) :
$product_category_level_indicator = '-- ';
else:
$product_category_level_indicator = '';
endif;
$items[] = array( 'value' => $product_category->name, 'text' => $product_category_level_indicator.$product_category->name );
}
它对我有用。反馈表示赞赏。