1

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!

8
  • What is var_dump($term);?
    – s_ha_dum
    Jan 21, 2014 at 15:26
  • @s_ha_dum that gives: ARRAY(1) { [0]=> INT(3) } Jan 21, 2014 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, 2014 at 16:08
  • @Milo even with term object selected, the above code still isn't returning anything? Jan 21, 2014 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" } } Jan 21, 2014 at 16:37

1 Answer 1

1

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 and acknowledge that you have read and understand our privacy policy and code of conduct.

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