2
$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

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.

  • I se.. actually I have the code inside: add_action('init', 'save_job_candidate_still'); , Could I use a different hook that is executed before the template? ( as i'm validating a $_post request in there ) – Toni Michel Caubet Sep 20 '16 at 10:00
  • You can also try a different priority, like add_action('init', 'save_job_candidate_still', 999 ); Better yet check the code where you registered the custom taxonomy. @ToniMichelCaubet – birgire Sep 20 '16 at 10:01
  • hm... that's going to be complicated, because I defined using the toolset plugin ( used to be named wp custom fields.. ), i'll try with the 999. Thanks! – Toni Michel Caubet Sep 20 '16 at 10:02
  • You can e.g. check the hook sequence here in the Codex. There are also plugins out there that should be able to show you this in detail @ToniMichelCaubet – birgire Sep 20 '16 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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