wordpress收费下载资源主题
wordpress付费下载资源插件

wordpress获取指定多个分类ID以及其子分类

wp_dropdown_categories 原生不支持直接传入多个父分类 ID,但可以通过 自定义查询 + 拼接 HTML 完美实现:指定多个顶级分类,自动展示它们的所有子分类(层级缩进)。

直接把这段代码放到你的主题 functions.php 或自定义插件中:

function custom_dropdown_multiple_categories($parent_ids = [], $args = []) {
if (empty($parent_ids)) return '';

$all_items = [];

// 遍历每个指定父分类,把【父分类本身 + 全部子分类】都加入列表
foreach ($parent_ids as $parent_id) {
// 1. 先加入父分类本身
$parent_cat = get_category($parent_id);
if ($parent_cat && !is_wp_error($parent_cat)) {
$all_items[] = $parent_cat;
}

// 2. 再获取该父分类下所有层级子分类
$child_cats = get_categories([
'parent' => $parent_id,//仅显示二级,child_of就是所有子分类
'hide_empty' => false,
'hierarchical' => true,
]);

$all_items = array_merge($all_items, $child_cats);
}

// 去重
$term_ids = array_unique(wp_list_pluck($all_items, 'term_id'));
$unique_items = [];
foreach ($term_ids as $id) {
foreach ($all_items as $item) {
if ($item->term_id == $id) {
$unique_items[] = $item;
break;
}
}
}
$all_items = $unique_items;

// 默认参数
$default_args = [
'show_option_none' => '选择分类',
'option_none_value' => '',
'name' => 'cat',
'id' => 'cat',
'selected' => 0,
];
$args = wp_parse_args($args, $default_args);

// 拼接下拉菜单
$html = '<select name="' . esc_attr($args['name']) . '" id="' . esc_attr($args['id']) . '">';
$html .= '<option value="' . esc_attr($args['option_none_value']) . '">' . esc_html($args['show_option_none']) . '</option>';

foreach ($all_items as $cat) {
$depth = count(get_ancestors($cat->term_id, 'category'));
$indent = str_repeat('&nbsp;&nbsp;', $depth);
//$selected = selected($args['selected'], $cat->term_id, false);

$html .= '<option value="' . esc_attr($cat->term_id) . '">';
$html .= $indent . esc_html($cat->name);
$html .= '</option>';
}

$html .= '</select>';
return $html;
}

// 你要显示的多个父分类ID 

$parent_ids = [2,5,8]; 

// 输出下拉菜单 

echo custom_dropdown_multiple_categories($parent_ids);

0 个评论

定制开发
本站承接WordPress等系统建站仿站、二次开发、主题插件定制等开发服务
在线咨询
  • 请先加Q,临时会话收不到
    QQ:1-247-246-247

  • QQ一群:104228692(满)
  • QQ二群:64786792
在线咨询
本站承接WordPress建站仿站、二次开发、主题插件定制等PHP开发服务!

了解详情