Get ID and slug from taxonomy object

I have a custom field to select a category (custom taxonomy) and then I will display a list of all of its child-categories. This works fine when I return the custom field as “term_id.”

HOWEVER. I would like to also get the slug from this selected category (the parent) so I can link to its category page (I don’t think I can link to it with the ID). So I thought maybe I should return the custom field as an object instead. This is what it dumps:

Read More
 stdClass Object ( [term_id] => 122 [name] => Quick Release Watch Bands [slug] => fits-all [term_group] => 0 [avhec_term_order] => 0 [term_taxonomy_id] => 122 [taxonomy] => product_cat [description] => Watch bands in many colors [parent] => 0 [count] => 293 [meta_id] => 1 [woocommerce_term_id] => 122 [meta_key] => order [meta_value] => 22 ) 

Do you know how I can pull out both the ID (122) and the slug (fits-all) from this? Here is my code so far. The custom field is called “selected_category”.

<?php $catid = get_sub_field('selected_category');  

            $args = array(
              'taxonomy'     => 'product_cat',
              'orderby'      => 'name',
              'show_count'   => 0,
              'pad_counts'   => 0,
              'hierarchical' => 1,
              'title_li'     => '',
              'depth'        => 1,
              'child_of'     => $catid
            );

            ?> 

<h4><a href="URL.COM/NEED-CATEGORY SLUG"><?php the_sub_field('title'); ?></a></h4>

<ul class="subcats">
<?php wp_list_categories( $args ); ?>
</ul>

Can anyone help me, please? Thank you so much!

Related posts

Leave a Reply

1 comment

  1. It sounds like you’re looking for the get_term_link() function.

    Your code will look something like this:

    <?php
    $catid = get_sub_field('selected_category');
    
    $term_link = get_term_link( intval( $catid ), 'product_cat' );
    ?>
    
    <h4><a href="<?php echo esc_url( $term_link ); ?>"><?php the_sub_field('title'); ?></a></h4>
    

    As you can see, get_term_link() takes two argument, the term and taxonomy. If you’re saving the term object in the field and passing it as the first argument, then the second argument is optional. If you pass the ID, as done above, then you have to pass the taxonomy name.