WordPress.org

Forums

How to check if a word is in the category slug? (5 posts)

  1. parthatel
    Member
    Posted 5 years ago #

    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.

  2. Mark / t31os
    Moderator
    Posted 5 years ago #

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

  3. Mohammad Jangda
    Member
    Posted 5 years ago #

    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.

  4. Mark / t31os
    Moderator
    Posted 5 years ago #

    Lots of options... can't hurt to have some to choose from ... :)

  5. Mohammad Jangda
    Member
    Posted 5 years ago #

    Lots of options... can't hurt to have some to choose from ... :)

    One of the best things about WordPress :)

Topic Closed

This topic has been closed to new replies.

About this Topic