I'm trying to display all post-categories except those who have an specific parent-categorie.
Can someone help me?
This is my current code:
<?php
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 0,
) );
echo '<ul>';
foreach( $categories as $category ) {
echo '<li><a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a></li>';
}
echo '</ul>';
?>
I'm trying to display all post-categories except those who have an specific parent-categorie.
Can someone help me?
This is my current code:
<?php
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 0,
) );
echo '<ul>';
foreach( $categories as $category ) {
echo '<li><a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a></li>';
}
echo '</ul>';
?>
Share
Improve this question
asked Feb 22, 2022 at 16:30
HenThaiHenThai
32 bronze badges
1
- Hello, There's nothing in your code which can say to WordPress to not display a category. You should give a try to generatewp.com/wp_tax_query which help you to write your correct Query. – Sébastien Serre Commented Feb 22, 2022 at 18:01
1 Answer
Reset to default 0get_categories()
gives you an array of WP_Term
objects, which has the parent
property. This contains the ID of the parent category. Inside your loop you can do a simple comparison to see, if the current iteration category has the specific parent category's ID or not, and if it does, skip it.
$parent_id = 123; // change to actual term id
foreach( $categories as $category ) {
if ( $parent_id === $category->parent ) {
continue;
}
// rest of the code...
}