Rodrigo Zuluaga
Rodrigo Zuluaga

Reputation: 497

Wordpress Post Category Names Link

After going several google searches i've accomplish this code (Not too good on PHP)

     <div>

    <?php

    $args = array(
        'post_type' => 'post'
    );

    $categories = get_categories( $args );

    $catlinks = get_category_link( $categories);


    foreach ( $categories as $category ) {

        echo '<a href=" '.$catlink->link . '"> <h2>' . $category->name .'</h2></a>';


        $args['category'] = $category->term_id;
   } ?>

</div>

This code displays a loop of Wordpress Post Categories, im trying to get each category link, but i'm still not getting the right link.

Any help in advance would be great.

Thanks Rodrigo

Upvotes: 2

Views: 104

Answers (2)

Leland
Leland

Reputation: 2119

You had it pretty close.

You'll want to run get_category_link() against the ID of the $category in your foreach loop.

That looks like this:

<?php
foreach ( $categories as $category ) {
    echo '<a href="' . get_category_link( $category->term_id ) . '"> <h2>' . $category->name . '</h2></a>';
}
?>

So, all together, your whole code should read:

<div>
    <?php
    $args = array(
        'post_type' => 'post'
    );

    $categories = get_categories( $args );
    foreach ( $categories as $category ) {
        echo '<a href="' . get_category_link( $category->term_id ) . '"> <h2>' . $category->name . '</h2></a>';
   }
   ?>
</div>

Upvotes: 1

Mattonit
Mattonit

Reputation: 601

Use get_permalink function. See the reference on Wordpress site

Upvotes: 0

Related Questions