WordPress.org

Ready to get started?Download WordPress

Forums

Category Slug Instead of ID Help (6 posts)

  1. Tommy White
    Member
    Posted 2 years ago #

    I use the following code on one of my sites that is a City site that lists items such as Restaurants. Under restaurants I have about 20 sub categories. The Following code works well if I use cat-ID but how can I make it use cat-SLUG instead.

    I find that I'm having to stop and look up ID numbers to make sure I'm editing the right files or which files I need to edit. So Instead of say cat-5.php I want cat-restaurants.php and then have all the child categories default to cat-restaurants.php

    [Code moderated as per the Forum Rules. Please use the pastebin]

  2. alchymyth
    The Sweeper & Moderator
    Posted 2 years ago #

    have you considered working with category templates:

    http://codex.wordpress.org/Category_Templates

  3. Tommy White
    Member
    Posted 2 years ago #

    Yes. Nothing on that page is a solution to my problem unless I want to manually add every category name to a IF statement. Unless I am missing something?

    Paste Bin Code *sigh

  4. alchymyth
    The Sweeper & Moderator
    Posted 2 years ago #

    http://codex.wordpress.org/Function_Reference/get_category

    to get the category slug from the category ID, you could use

    $cat_slug = get_category($catid)->slug;

  5. Tommy White
    Member
    Posted 2 years ago #

    I will play around with that and see what I can make of it. Thank you.

  6. Digital Raindrops
    Member
    Posted 2 years ago #

    Hi have a look at locate_template() this will look in both the parent and child themes folder for the files.

    Also get_template_part() this will also look in both folders and load a file with just the name, no path or extention.

    <?php locate_template( $template_names, $load, $require_once ); ?>
    <?php get_template_part( $slug, $name ); ?>

    Locate Template
    $template_names is an array.

    <?php
    $template_names = array();
    $template_names[] = 'category-' .get_category($catid)->slug .'.php';
    if locate_template( $template_names,true,true) exit;
    ?>

    We could load files conditional.

    <?php
    $template_names = array();
    $template_names[] = 'category-' .get_category($catid)->slug .'.php';
    if locate_template($template_names,false):
    ?>
       <?php get_template_part('category',get_category($catid)->slug); ?>
       <?php exit; ?>
    <?php endif; ?>

    We could have a custom menu and a loop file, un-tested code.

    <?php
    $template_names = array();
    $template_names[] = 'category-menu.php';
    $template_names[] = 'category-' .get_category($catid)->slug .'.php';
    if locate_template($template_names,true,true) exit;
    ?>

    HTH

    David

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.