Search code examples
phpwordpresscustom-post-typecustom-taxonomytaxonomy-terms

Get Permalink for Taxonomy


I have a custom post type of hardware with a custom taxonomy called hardware_categories attached to it.

I have a piece of code that outputs each taxonomy as a H3 and under each one it outputs the hardware items inside that taxonomy.

I'm having trouble adding a permalink link around the taxonomy name.

The code I'm trying is here:

<div class="container  hardware-archive-container">

<?php // Output all Taxonomies names with their respective items
$terms = get_terms('hardware_categories');
foreach( 
    $terms as $term ):
    $term_link = get_term_link( $term );
?>                         

    <h2><a href="<?php esc_url( $term_link ) ?>"><?php echo $term->name; ?></a></h2>

    <div class="row justify-content-center hardware-archive-row">

    <?php                         
      $posts = get_posts(array(
        'post_type' => 'hardware',
        'taxonomy' => $term->taxonomy,
        'term' => $term->slug,                                  
        'nopaging' => true, // to show all posts in this taxonomy, could also use 'numberposts' => -1 instead
      ));
      foreach($posts as $post): // begin cycle through posts of this taxonmy
        setup_postdata($post); //set up post data for use in the loop (enables the_title(), etc without specifying a post ID)
    ?>        

        <div class="col-md-3">
        
        <?php 
        $image = get_field( 'hardware_main_image');
        if( !empty( $image ) ): ?>
            <img src="<?php echo esc_url($image['url']); ?>" alt="<?php echo esc_attr($image['alt']); ?>" />
        <?php endif; ?>

        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        
        </div>

    <?php endforeach; ?>

    </div>                                                  

    <a href="#"><p>See all products from: <?php echo $term->name;?></p></a>

<?php endforeach; ?>

</div>

The parts I added to try and generate a link are these two lines:

$term_link = get_term_link( $term );

and

<h2><a href="<?php esc_url( $term_link ) ?>"><?php echo $term->name; ?></a></h2>

Ive tried a lot of other things, but I can't seem to get category link...

Can anyone tell me where I'm going wrong? Thanks for looking.


Solution

  • Could you try this:

    $term_link = get_term_link( $term->term_id, "hardware_categories" );
    

    Also try to modify your terms:

    $terms = get_terms( array(
        'taxonomy' => 'taxonomy_name',
        'hide_empty' => false
    ) );
    

    The way you're using get_terms is deprecated see the documentation

    Your code should look like this

    $terms = get_terms( array(
        'taxonomy' => 'hardware_categories',
        'hide_empty' => false
    ) );
    foreach( $terms as $term ):?>
        <h2><a href="<?php echo get_term_link( $term->term_id, 'hardware_categories');?>"><?php echo $term->name; ?></a></h2>
    <?php endforeach;?>