0

I have a taxonomy called "country" and I need to visualize it as a list of categories can someone help me?

<li><a href="<?php echo esc_url( home_url() ); ?>/country/argentina/">Argentina</a></li>
<li><a href="<?php echo esc_url( home_url() ); ?>/country/australia/">Australia </a></li>
<li><a href="<?php echo esc_url( home_url() ); ?>/country/canada/">Canada</a></li>
<li><a href="<?php echo esc_url( home_url() ); ?>/country/china/">China</a></li>
<li><a href="<?php echo esc_url( home_url() ); ?>/country/france/">France</a></li>
<li><a href="<?php echo esc_url( home_url() ); ?>/country/germany/">Germany</a></li>
<li><a href="<?php echo esc_url( home_url() ); ?>/country/india/">India</a></li>
<li><a href="<?php echo esc_url( home_url() ); ?>/country/italy/">Italy</a></li>
<li><a href="<?php echo esc_url( home_url() ); ?>/country/spain/">Spain</a></li>
<li><a href="<?php echo esc_url( home_url() ); ?>/country/south-korea/">Korea</a></li>
<li><a href="<?php echo esc_url( home_url() ); ?>/country/uk/">United Kingdom</a></li>
<li><a href="<?php echo esc_url( home_url() ); ?>/country/usa/">USA</a></li>
1
  • Hi Vincenzo! So you want to create output like this from your taxonomy? Do you want to write code to do this and add it to your theme? What have you tried so far?
    – mozboz
    Jul 1, 2020 at 10:02

1 Answer 1

1

You can achieve the result using following code:

$terms = get_terms( array(
    'taxonomy' => 'country',
    'hide_empty' => false,
    'orderby' => 'name',
    'order' => 'ASC',
) );

if ( !empty($terms) ) :
    $output = '<ul>';
    foreach( $terms as $country ) {
        $output.= '<li><a href="'.get_term_link( $country->term_id ).'">'. esc_attr( $country->name ) .'</a></li>';
    }
    $output.='</ul>';
    echo $output;
endif;

Here I'm using get_terms() to get all item of country taxonomy. The checking if there is any item in the list. If yes then I'm looping through them and returning as desired link. get_term_link() is being used to get the term url by using term id.

3
  • is there a way to convert the code into function so i can paste it into the functions.php file and use only the function? Jul 1, 2020 at 12:15
  • just wrap the code as a function. like function list_country(){ here the code above } Jul 1, 2020 at 14:08
  • thanks! works fine! Jul 1, 2020 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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