WordPress.org

Support

Support » How-To and Troubleshooting » How to check if a word is in the category slug?

How to check if a word is in the category slug?

  • parthatel
    Member

    @parthatel

    I want to make categories have different templates if the have a certain word in their slug. For example, all categories with the word “computers” will have one template. All categories with the word “videos” will have another template. So, the structure will go something like this:

    if (category slug has word videos)
    // use this template

    elseif (category slug has word computers)
    // use this template

    I found this code to get the category slug (haven’t tested it)

    <?php if(is_category()) {
    $cat = get_query_var('cat');
    $yourcat = get_category($cat);
    $cat_slug = $yourcat->slug;
    ?>

    but then I don’t have enough php knowledge to see if a word is in that category slug. Please help. Thank You.

Viewing 4 replies - 1 through 4 (of 4 total)
  • One method, purely for example.

    <?php
    if( is_category() ) {
    	$cat = get_query_var('cat');
    	$yourcat = get_category($cat);
    	switch( true ) {
    		// Catch invalid cat ID
    		case( intval( $cat ) == 0 ):break;
    
    		// Match slugs with computers in the name
    		case( strpos( $yourcat , 'computers' ) ):
    
    			// Do something here if computers is in the slug
    
    		break;
    		// Match slugs with books in the name
    		case( strpos( $yourcat , 'books' ) ):
    
    			// Do something here if books is in the slug
    
    		break;
    	}
    }
    ?>

    I find switches to be cleaner then if/else/if/else/if/else and so on….. pretty much the same thing though. I can give you an IF / ELSE equivalent if you prefer…

    You could try something like (add it to your functions.php:

    <?php
    add_filter( 'category_template', 'my_category_template' );
    
    function my_category_template( $template ) {
    	$cat = get_query_var('cat');
    	$yourcat = get_category($cat);
    	$cat_slug = $yourcat->slug;
    
    	if( strpos( $cat_slug, 'computers' ) )
    		$template = locate_template( array( 'computers.php', 'category.php' ) );
    	elseif( strpos( $cat_slug, 'videos' ) )
    		$template = locate_template( array( 'videos.php', 'category.php' ) );
    	// add more else ifs for any other templates
    
    	return $template;
    }
    ?>

    This will load computers.php for any slugs with ‘computers’ in it and videos.php for any slugs with ‘videos’ in it. It falls back to the default template (usually category.php) for any other categories.

    Lots of options… can’t hurt to have some to choose from … 🙂

    Lots of options… can’t hurt to have some to choose from … 🙂

    One of the best things about WordPress 🙂

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to check if a word is in the category slug?’ is closed to new replies.