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.