0

I'm trying to echo the taxonomy name inside a for each loop, instead of the category slug at this line :

<div class="title"><?php echo $taxonomy; ?></div>

I tried :

<div class="title"><?php echo $taxonomy->name; ?></div>

but I get an error : " Trying to get property 'name' of non-object"

Here is my code :

<?php
$custom_post_type = get_queried_object();
$custom_post_type_name = $custom_post_type->name;
$taxonomies = get_object_taxonomies($custom_post_type_name);
?>

<?php foreach ($taxonomies as $taxonomy) : ?>

    <?php $categories = get_terms(array(
        'orderby' => 'name',
        'taxonomy' => $taxonomy,
        'order'   => 'ASC',
        'hide_empty' => 1,

    )); ?>

    <div id="filters-<?php echo $taxonomy; ?>" class="filter-group">

        <div class="title"><?php echo $taxonomy; ?></div>

        <ul class="filters-select" data-filter-group>

            <?php foreach ($categories as $category) : ?>
                
                <li>
                    <label><?php echo $category->name; ?></label>
                    <input type="checkbox" value=".<?php echo $category->slug; ?>" />
                </li>
            <?php endforeach; ?>

        </ul>

    </div>

<?php endforeach; ?>

Am I missing something?

1 Answer 1

1

get_object_taxonomies() by default returns a list of taxonomy names like category and post_tag. If you want the function to return taxonomy objects instead, then set the second parameter to objects:

$taxonomies = get_object_taxonomies($custom_post_type_name, 'objects');

And then change your foreach () code to foreach ($taxonomies as $taxonomy => $tax_object), then use $tax_object->labels->singular_name to access the singular label of the specific taxonomy.

2
  • 1
    awesome @Sally CJ, works like a charm thanks May 18, 2021 at 14:31
  • Glad it helped, and you can mark my answer as "correct" if it answered the question. 🙂
    – Sally CJ
    May 18, 2021 at 15:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.