Duggy G
Duggy G

Reputation: 477

Advanced Custom Fields category link

I'm struggling with this even after looking at the documentation but all I'm wanting to do is link to a category. I have created a taxonomy field to select categories. Everything is working apart from when I add

<a href="<?php echo the_sub_field('category_link','option' ); ?>"></a>

I just get the ID of the category but I want the name. This is all within a repeater as I'm creating a menu but I need help getting the name and not the ID.

any help please?

Upvotes: 2

Views: 4777

Answers (3)

Prateek Verma
Prateek Verma

Reputation: 889

If there is an option of selecting only one taxonomy.

Then write the query:

    <?php $term_id = get_sub_field('category_link');
    if( $term_id):
        $term_name = get_cat_name( $term_id ) ;
        $term_url = get_category_link( $term_id ); ?>
        <a href="<?php echo term_url; ?>"><?php echo $term_name; ?></a>
   <?php endif; ?>

OR

If there are multiple category terms, then place this query:

     <?php 
    $terms = get_sub_field('category_link');
    if( $terms ):
        foreach( $terms as $term_id ): 
            $term_name = get_cat_name( $term_id ) ;
            $term_url = get_category_link( $term_id ); ?>
            <a href="<?php echo term_url; ?>"><?php echo $term_name; ?></a>
   <?php endforeach;  endif;    ?>

Now place your category term url & name in the anchor tag.

Upvotes: 2

Prateek Verma
Prateek Verma

Reputation: 889

First of all, let me know have you selected Term_id in the custom field which you have created & also let me know you can select one or more taxonomy through that custom field.

Upvotes: 0

Anjana Shyamlal
Anjana Shyamlal

Reputation: 408

Try this. It can give all your terms under the preferred taxonomy. Just give your taxonomy name in the below code

<?php $terms= get_terms( array(
    'taxonomy' => 'taxonomy name',
) );
    foreach ( $terms as $term ) {
    echo $term->name;
    }

?>

Upvotes: 0

Related Questions