WordPress.org

Support

Support » Themes and Templates » category slug as template name

category slug as template name

  • Hi there, does anyone know if i can use a category slug in a similar way to its id when naming individual template files for the categorys. i.e.

    i have a category called ‘news’ with an id of 4

    making a template of category-4.php works fine but i would like to use category-news.php

    any ideas?

Viewing 4 replies - 1 through 4 (of 4 total)
  • If you want to custom code your PHP, you can call them anything you want. If you want WP to auto-access them with no coding on your part you have to follow the WP template hierarchy naming rules.

    http://codex.wordpress.org/Template_Hierarchy

    you could; add the below code ↓ inside your theme’s functions.php.

    <?php
    add_filter('category_template','my_category_template_filter');
    function my_category_template_filter($template){
        $cid = absint( get_query_var('cat') );
        $file = TEMPLATEPATH.'/category-'.sanitize_title_with_dashes(get_cat_name($cid)).'.php';
        return (file_exists($file)) ? $file : $template;
    }
    ?>

    Brilliant chaoskaizer. Thanks for that…

    Just the inspiration I needed!
    I’d suggest a small tweak though – this current code works out what the slug should be by sanitising the query variable (which I believe could be anything coming from the URL rewrite) then looks up the category name and turns that into what should be the slug.

    However the actual slug doesn’t always equal the sanitised name as you can edit the slugs in the admin.

    The following tweak will get the actual slug assigned to that category from the database:

    <?php
    add_filter('category_template','my_category_template_filter');
    function my_category_template_filter($template){
        $cid = absint( get_query_var('cat') );
        $cat = get_category($cid);
        $file = TEMPLATEPATH.'/category-'.$cat->slug.'.php';
        return (file_exists($file)) ? $file : $template;
    }
    ?>

    It shouldn’t need sanitising as its already been cleaned before writing to the db.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘category slug as template name’ is closed to new replies.
Skip to toolbar