0

I'm currently using the taxonomy field in ACF, with the aim of printing the category name in the front end. Using it like so:

<?php $term = get_sub_field('category_selector'); if( $term ): ?>
<span><?php echo $term->name; ?></span>
<?php endif; ?>

Which is currently displaying nothing, I've debugged the $term which doesn't display the category ID of 3, but for some reason I can't get hold of the category name from this? Any suggestions would be greatly appreciated!

  • What is var_dump($term);? – s_ha_dum Jan 21 '14 at 15:26
  • @s_ha_dum that gives: ARRAY(1) { [0]=> INT(3) } – user1374796 Jan 21 '14 at 15:35
  • 1
    When you add the taxonomy field to your field group, one of the options is to return the Term ID or Term object. You currently have ID selected. Every ACF field that associates some sort of object has this option. – Milo Jan 21 '14 at 16:08
  • @Milo even with term object selected, the above code still isn't returning anything? – user1374796 Jan 21 '14 at 16:30
  • @Milo ah actually, nearly there, I var dumped it with 'term object' selected and got this like so: array(1) { [0]=> object(stdClass)#2150 (11) { ["term_id"]=> int(2) ["name"]=> string(16) "Product Category" ["slug"]=> string(16) "product-category" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(2) ["taxonomy"]=> string(21) "wpsc_product_category" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(2) ["object_id"]=> int(59) ["filter"]=> string(3) "raw" } } – user1374796 Jan 21 '14 at 16:37
0

Assuming that 3 is a category ID...

$term = get_sub_field('category_selector'); 
if( $term ) {
  foreach($term as $t) {
    $t = get_category($t);
    echo $t->name;
  }
}

In other words, it looks like ACF is just storing the ID, not the whole object, so you need to use that ID to grab the category object before you have access to the name, slug, etc.

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.