How can I show child categories under there parent category in the wordpress admin? On a post the format of the category box would look like this:
Category 1
- Sub-Category 1.1
- Sub-Category 1.2
Category 2
EDIT:
On a post page, the categories are already seen in hierarchical manner but with checkboxes. So, I have assumed that you have to show list of all the categories/subcategories somewhere in the admin panel in following format.
So, presentation is upto you, I have just given logic to pull the necessary data i.e. list of all the categories along with subcategories.
$arg1 = array(
'parent' => 0,
'orderby' => 'name',
'hide_empty' => 0,
'pad_counts' => false
);
$categories = get_terms('category', $arg1); //or use your custom taxonomy name
if( !empty($categories) && is_array($categories) ){
echo '<ul>';
foreach($categories as $cat){
echo '<li>'.$cat->name;
$arg2 = array(
'child_of' => $cat->term_id,
'orderby' => 'name',
'hide_empty' => 0,
'pad_counts' => false
);
$sub_categories = get_terms('category', $arg2); //or use your custom taxonomy name
if(!empty($sub_categories) && is_array($sub_categories)){
echo '<ul>';
foreach($sub_categories as $scat){
echo '<li>'.$scat->name.'</li>';
}
echo '</ul>';
}
echo '</li>';
}
echo '</ul>';
}
use this code for solving your problem.
<?php
$args = array( 'orderby' =>'name',
'texonomy' =>'category',
'child_of' =>0,
'parent' =>0 );
$cats = get_categories($args);
foreach ($cats as $cat) {
echo $cat->name;
$arg = array('orderby' => 'name',
'child_of' =>0,
'parent' =>$cat->term_id);
$sub_cats =get_categories($arg);
foreach ($sub_cats as $sub) {
echo '<hr><br>';
echo '<h3>'.$sub->name.'</h3>';
echo '<hr><br>';
$args = array(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'category',
'terms' => $sub->term_id,
),
),
);
$query = new WP_query( $args);
//echo "<pre>"; print_r($query); echo "</pre>";
while($query->have_posts()) : $query->the_post();
echo "<br>";
the_title();
echo "<br>";
the_content();
endwhile;
echo "<hr>";
}
}
?>
texonomy
parameter. Do not make up your own parameters and expect it to work out of the box.
Commented
Jul 29, 2015 at 12:00