$my_post_id = 644;
$areas = wp_get_post_terms( $my_post_id, 'area-trabajo' );
var_dump($areas);
This code, in functions.php, returns:
object(WP_Error)#3178 (2) { ["errors"]=> array(1) { ["invalid_taxonomy"]=> array(1) { [0]=> string(20) "Taxonomia no válida" } } ["error_data"]=> array(0) { } }
But in a template, returns the expected result:
array(1) { [0]=> object(WP_Term)#7194 (11) { ["term_id"]=> int(150) ["name"]=> string(13) "Restauración" ["slug"]=> string(12) "restauracion" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(150) ["taxonomy"]=> string(12) "area-trabajo" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(1) ["filter"]=> string(3) "raw" ["term_order"]=> string(1) "0" } }
What could be the reason that in the functions.php returns invalid_taxonomy?
1 Answer
If you dump the code into functions.php
, then the custom taxonomy hasn’t been registered, because it isn’t recommend to register custom taxonomies earlier than the init
hook.
Running the code within the template hierarchy files should work, because it’s later than init
.
If you want to run it within the functions.php
file, make sure to hook it accordingly.