Zach Smith
Zach Smith

Reputation: 5704

Display Link to Category in Wordpress?

I am trying to figure out how to display the category of an article, and a link to the category. Any help would be greatly appreciated.

Upvotes: 2

Views: 14902

Answers (4)

shakhawat hossain
shakhawat hossain

Reputation: 21

You can use get_the_category()

<?php
$categories = get_the_category();
$separator = ' ';
$output = '';
if($categories){
foreach($categories as $category) {
    $output .= '<a href="'.get_category_link( $category ).'" title="'.esc_attr(sprintf( __( "View all posts in %s" ), $category->name ) ) .'">'.$category->cat_name.'</a>'.$separator;
}
echo trim($output, $separator);
}
?>

Upvotes: 0

Tamara
Tamara

Reputation: 427

Note that: <?php the_category(', ') ?>will display the category as a link. which is good.... but if you want only the category URL (that is, the category link only), then you will have to use the <?php get_category_link($category_ID); ?> the $category_ID is required. once you fix that in, the category URL will be returned.

Consider the example:

<?php
    // Get the ID of a given category
    $category_id = get_cat_ID( 'Category Name' );

    // Get the URL of this category
    $category_link = get_category_link( $category_id );
?>

<!-- Print a link to this category -->
<a href="<?php echo esc_url( $category_link ); ?>" title="Category Name">Category Name</a>

Now you can see how we got the category ID and then using it to get the category Link.
Hope this answers your question well enough?

Upvotes: 2

gbennett
gbennett

Reputation: 120

If you want to do this on post page you can add something like the following to your single.php file of your theme.

<div class="meta">Posted in: <span><?php the_category(', ') ?> </span></div>

Upvotes: 6

Jamie Dixon
Jamie Dixon

Reputation: 54021

Here's some info that will be of use:

http://codex.wordpress.org/Template_Tags/wp_list_categories

Basically you can call: <?php wp_list_categories( $args ); ?> and this will output what you're looking for.

Thr $args parameter is an array of settings strings that lets you change the order, style, depth etc, on links returned.

Upvotes: 2

Related Questions