最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

custom post types - Display all Categories except ones with a specific parent

programmeradmin2浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 0

get_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...   
} 
发布评论

评论列表(0)

  1. 暂无评论