admin管理员组

文章数量:1287612

I have 20 subcategories from a parent category, and they are like that
Parent

  • September
  • November
  • … up to 20

Here is the code that try it to display, but I get only 1 category instead

<?php
$categories = get_categories('child_of=505');
foreach($categories as $category): ?>

    <div class="qitem">
        <a href="<?php get_category_link( $category->term_id ); ?>" title="<?php echo $category->name; ?>">
            <?php echo $category->name; ?>
        </a>
        <h4>
            <span class="caption">
                <?php echo $category->name; ?>
            </span>
        </h4>
        <p>
            <span class="caption">
                <?php echo $category->description; ?>
            </span>
        </p>
    </div>

<?php endforeach; ?>

I have 20 subcategories from a parent category, and they are like that
Parent

  • September
  • November
  • … up to 20

Here is the code that try it to display, but I get only 1 category instead

<?php
$categories = get_categories('child_of=505');
foreach($categories as $category): ?>

    <div class="qitem">
        <a href="<?php get_category_link( $category->term_id ); ?>" title="<?php echo $category->name; ?>">
            <?php echo $category->name; ?>
        </a>
        <h4>
            <span class="caption">
                <?php echo $category->name; ?>
            </span>
        </h4>
        <p>
            <span class="caption">
                <?php echo $category->description; ?>
            </span>
        </p>
    </div>

<?php endforeach; ?>
Share Improve this question edited Oct 5, 2021 at 6:01 bueltge 17.1k7 gold badges62 silver badges97 bronze badges asked Oct 5, 2021 at 5:41 Digital PointDigital Point 153 bronze badges 2
  • 1 Is this the complete code? You're missing an endforeach. – Jacob Peattie Commented Oct 5, 2021 at 5:57
  • I missed to put the endforeach in the post. – Digital Point Commented Oct 5, 2021 at 5:58
Add a comment  | 

1 Answer 1

Reset to default 0

get_categories() uses get_terms() so the array argument you can pass it will be the same.
From the documentation the array can have a property hide_empty, by default its true.
I'm guessing that those categories have no posts attached to it, if that is the case you will need to set it to false.
The code would be like this.

get_categories([
    'child_of'   => 505,
    'hide_empty' => false
]);

Update

If you want to order the results you can add order to the array, the default value is ASC so you will need to set it to DESC.

get_categories([
    'child_of'   => 505,
    'hide_empty' => false,
    'order'      => 'DESC'
]);

You can check WP_Term_Query::__construct( string|array $query = '' ) for all the available arguments you can use.

本文标签: categoriesDisplay all subcategories from parent category