2

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.

4 Answers 4

6

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>
2

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.

2

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?

0

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);
}
?>

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.