Using get_terms for custom taxonomy in functions.php

I`m trying to retrieve the names of taxonomy items and include them into a theme admin panel.

function retrieve_my_terms() {

    global $terms;

    $terms = get_terms('taxonomy');

    foreach ($terms as $term) {
        $option = $term->name;
        return $option;
    }
}

The function is added after the functions which created the custom post type and taxonomy.

From what I’ve found out, it seems that the init action occurs after the theme’s functions.php file has been included, so if I’m looking for terms directly in the functions file, I`m doing so before they’ve actually been registered.

In other words, init action doesn’t fire until after the theme functions file is included, therefore any term retrieval must occur after init.

My problem is that I don`t know how to retrieve the terms after the init.

Any answer will be much appreciated!

Thank you!
Madalin

3 Answers
3

You can add the action on the init itself, just increase the priority of the add_action call. The higher the priority the later the function is called.

add_action('init', 'retrieve_my_terms', 9999);

But my suggestion is that you should do these kind of things as late as possible, preferably just before the first time they are used. There’s an action 'wp_loaded' which gets called after full wordpress has been loaded & ready to start working on the output. That action might work for you.

Leave a Comment