Return category slug / title from category ID

I have a custom field set up that returns the category ID of a chosen category, I’m looking to use this category ID to show, in one instance: category slug, and another instance: category title.

The field get’s called quite simply like so: <?php the_field('category_test'); ?> and returns the ID, in this case 4.

Read More

Is it at all possible to use this field to return the category slug, and also use it to return the category title? I’m not really sure how or if this can be done. Any suggestions would be greatly appreciated!

Related posts

1 comment

  1. get_category will return all the information you need for both cases.

    $catinfo = get_category(get_field('category_test'));
    

    From the Codex, that will give you (sample data obviously):

    stdClass Object
    (
        [term_id] => 85
        [name] => Category Name
        [slug] => category-name
        [term_group] => 0
        [term_taxonomy_id] => 85
        [taxonomy] => category
        [description] => 
        [parent] => 70
        [count] => 0
        [cat_ID] => 85
        [category_count] => 0
        [category_description] => 
        [cat_name] => Category Name
        [category_nicename] => category-name
        [category_parent] => 70
    )
    
    

    I am pretty sure that get_field is correct.

    get_category works correctly for every category ID that I’ve tried, and NULL for bad category IDs but per the discussion below, get_field can return an array. When this happens get_category appears to return the first category in the database by ID which is the uncategorized category by default. That can be demonstrated with the following.

    var_dump(get_category(array(8,9,10)));
    

    Therefore, to compensate you will need:

    $cat_field = get_field('category_test');
    if (is_array($cat_field)) {
      $cat_field = $cat_field[0];
    }
    $catinfo = get_category($cat_field);
    

    To get any particular field just use standard object syntax. Fpr example:

    echo $catinfo->slug;
    

    Or

    $cname = $catinfo->name;
    

Comments are closed.