我想只显示父类别名称而不是儿童 未在任何产品或帖子中使用的我只需要列出父自定义类别。
我已尝试 get_terms , wp_list_categories 功能,但其显示 孩子也
这是我的代码。
<?php
require_once('connection.php');
$taxonomy = 'product_cat';
$orderby = 'parent';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 0; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'childless' => false,
'child_of' => 0,
'title_li' => $title,
'hide_empty' => $empty,
'hierarchical'=>1
//'hierarchical=0&depth=1'
);
$rrr=wp_list_categories( $args );
print_r($rrr);
?>
它也显示了孩子,但我只需要父类别名称。
我使用的Product_cat是一个 woocommerce类别,当我用它时 get_terms 它的 null 数组。
我也这样使用但是product_cat不能与get_terms一起使用
<?php
$parent_cat_arg = array('hide_empty' => false, 'parent' => 0 );
$parent_cat = get_terms('product_cat',$parent_cat_arg);
foreach ($parent_cat as $catVal) {
/*some code*/
}
?>
参见附图,我也解释了我的需要。
答案 0 :(得分:2)
试试此套parent
为0
$taxonomy = 'product_cat';
$orderby = 'parent';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 0; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'childless' => 0,
'child_of' => 0,
'title_li' => $title,
'hide_empty' => $empty,
'parent'=>0,
);
$rrr=wp_list_categories( $args );
print_r($rrr);
答案 1 :(得分:1)
使用此代码显示父类别名称
<?php
$terms = get_terms('category', array('hide_empty' => false, 'parent' => 0));
$terms2 = $terms;
for ($i = 0; $i < count($terms); $i++) {
$child = get_terms('category', array('hide_empty' => false, 'parent' => $terms[$i]->term_id));
$terms2[$i]->child = $child;
}
for ($s = (count($terms2) - 1); $s >= 0; $s--) {
if (isset($terms2[$s]->child)) {
echo "<select name='parent_cat' class='dropdown' id='cat_" . $terms2[$s]->name . "'>";
echo "<option selected='selected' value=''>" . $terms2[$s]->name . "</option>";
for ($ch = 0; $ch < count($terms2[$s]->child); $ch++) {
echo "<option value='" . $terms2[$s]->child[$ch]->term_id . "'>" . $terms2[$s]->child[$ch]->name . "</option>";
}
echo "</select>";
}
}
?>
您可以更改自定义帖子类型分类名称的术语。
答案 2 :(得分:0)
如果 get_terms
由于某种奇怪的原因不起作用,自定义分类法未显示已注册,请尝试使用 WP_Term_Query
:
$term_query = new WP_Term_Query( array(
'taxonomy' => 'regions', // <-- Custom Taxonomy name..
'orderby' => 'name',
'order' => 'ASC',
'child_of' => 0,
'parent' => 0,
'fields' => 'all',
'hide_empty' => false,
) );
// Show Array info
echo "<pre>";
print_r($term_query->terms);
echo "</pre>";
//Render html
if ( ! empty( $term_query->terms ) ) {
foreach ( $term_query ->terms as $term ) {
echo $term->name .", ";
echo $term->term_id .", ";
echo $term->slug .", ";
echo "<br>";
}
} else {
echo '‘No term found.’';
}