WordPress.org

Ready to get started?Download WordPress

Forums

category slug as template name (5 posts)

  1. jonathantopf
    Member
    Posted 5 years ago #

    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?

  2. stvwlf
    Member
    Posted 5 years ago #

    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

  3. chaoskaizer
    Member
    Posted 5 years ago #

    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;
    }
    ?>
  4. Driftless
    Member
    Posted 5 years ago #

    Brilliant chaoskaizer. Thanks for that...

  5. benz001
    Member
    Posted 5 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic