0

In several theme templates I have code to retrieve the category name and slug for the present post or category page. It is outside the loop. Here is the repeated code:

global $post;
$categories = get_the_category($post->ID);
if ( $categories ) {
foreach ($categories as $category) {
    $dw_category_slug = $category->slug;
    $dw_category_name = $category->name;
}  
}else {
    $dw_category_slug = 'utopia';
} 

I would like to be able to include this in the functions file instead of writing it in several places. This is what I have tried in my functions file:

  add_action('wp_head', 'dw_get_category');
  function dw_get_category() {
    global $post;
    $categories = get_the_category($post->ID);
           if ( $categories ) {
               foreach ($categories as $category) {
               $dw_category_slug = $category->slug;
               $dw_category_name = $category->name;
        }
        } else {
            $dw_category_slug = 'utopia';
        }         
    $dw_category[] = array('name' => $dw_category_name, 'slug' =>    $dw_category_slug);
    return $dw_category;     
    }                                                   

I would like to be able to write something like $dw_category['name'] in the template files to call the category name. I know this is the wrong way to do it. Do I need to divide this into 2 functions so there is only one value returned for the function? Or is there some other way to do this? Writing it as a class?

If interested the url is http://lenoremalenblog.com

Thanks for your time.

1 Answer 1

1

You don't need to hook the dw_get_category() function. Simply do it like this:

  function dw_get_category() {
    global $post;
    $categories = get_the_category($post->ID);
        if ( $categories ) {
           foreach ($categories as $category) {
               $dw_category_slug = $category->slug;
               $dw_category_name = $category->name;
           }
        } else {
            $dw_category_slug = 'utopia';
        }         
    $dw_category = array('name' => $dw_category_name, 'slug' =>    $dw_category_slug);
    return $dw_category;     
    } 

Then call it like this:

$the_post_cats = dw_get_category();
echo 'Category: '.$the_post_cats['name'];
echo 'Slug: '.$the_post_cats['slug'];
2
  • thanks, that worked. I also had to get rid of the '[]' in $dw_category[], which was a careless mistake. Thanks Commented Jul 8, 2011 at 13:17
  • @danielwiener Yes, the [] was not necessary (see code - it's copy/paste ready). So: Glad it worked. :)
    – kaiser
    Commented Jul 8, 2011 at 17:08

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.