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
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.It’s true that
functions.php
is loaded beforeinit
– and that most post types will be registered using that hook. But there are later hooks that you can use – and which will be more appropriate.You say you need access the terms inside
functions.php
. But when do you need them?init
fires on every page load – front and back – and I don’t think you mean to retrieve the terms on every page load. There are lots of hooks available to you and they’re all triggered in various contexts. If you tell us precisely what you want to do with the terms that will determine which hook you should use.(I’m a bit confused by include them into a theme admin panel). It sounds like you might be trying to output a list in an admin metabox. Regardless, can you include some code?
You can define your function in the global scope of functions.php with no issues.
It’s using the function prior to registration that’s the problem. Instead of doing things in functions.php in the global scope, do them in hooks. The only thing in functions.php that should be allowed to not be in a hook is the calls to
add_action
.So put everything in hooks, and make your calls in a hook/action after the registration of your post types, not before in loose code in the global