• Resolved tlw22

    (@tlw22)


    Hi,

    I’m currently using the following code to display the first category of every post on the page:

    <?php $category = get_the_category(); echo $category[0]->cat_name; ?>

    This works great, however does anyone know how to then link to the category chosen.

    e.g The selected category is ‘gaming’ so on the actual page (single.php) it shows like so:
    Gaming

    Thanks to anyone who can help me out!

Viewing 4 replies - 1 through 4 (of 4 total)
  • Haven’t tested but what about something like this:

    <?php $category = get_the_category(); 
    
    echo "<a href=\"/yourcategorybasehere/";
    echo $category[0]->cat_slug;
    echo "\">";
    echo $category[0]->cat_name;
    echo "</a>"; ?>
    Thread Starter tlw22

    (@tlw22)

    The code works great, however, I would like a more automated process, so that the category changes with whatever I change it to on the post page.

    Actually, change of plan, do you know how to find the link of a category page (couldn’t seem to find it anywhere)?

    I’m gathering it would look something like sitename.com/category=gaming (with name at the end?)

    This way I can then add the url slug of the category to the end of the link url when inputted in.

    Hope this makes sense, haha, cheers!

    Thread Starter tlw22

    (@tlw22)

    Ah, found a solution:

    <?php
    $category = get_the_category();
    if ($category) {
      echo '<a href="' . get_category_link( $category[0]->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category[0]->name ) . '" ' . '>' . $category[0]->name.'</a> ';
    }
    ?>

    ^Posted by another person on the forums

    Thanks for your help

    ahhh… yup that looks like the answer, yeah, my answer would assume you had permalinks set to /%postname%/ …

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Links to categories’ is closed to new replies.