Group Admins

WordPress Troubleshooting and Support

Public Group active 2 years, 7 months ago ago

WordPress support from our community

create function to call category name and slug

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #1174
    Daniel Wiener
    Participant

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

    #1921
    Steve
    Keymaster

    I don’t really know what you are asking, but you don’t need:
    add_action(‘wp_head’, ‘dw_get_category’);

    You can remove that, and then just write: `dw_get_category()` in your theme template.

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.