0

I have a category named: This & That

However, for some strange reason my switch code doesn't pick it up. When I output $firstcat it does return This & That which makes it even more cumbersome.

The code works fine for other categories not containing the ampersand &.

function posend_text_shortcode() {
  $mycategory = get_the_category();
  $firstcat = $mycategory[0]->name;
     switch($firstcat){
      case "This & That":
       include(get_stylesheet_directory() . '/inc/style/check.php');
      break;
   default:
       include(get_stylesheet_directory() . '/inc/style/default.php'); 
    break;
  }
}
  • And why don’t you check by term slug? It would be much safer... – Krzysiek Dróżdż Jan 6 at 19:50
  • how could I do this please? I am writing mycategory[0]->slug - but I still get the same problem with this category. It works for single words just fine.. – Joanna Mikalai Jan 6 at 20:23
  • ok sorry, everything seems to work fine now when I test for slug. thanks for pointing it out – Joanna Mikalai Jan 6 at 20:29
  • Take a look at my answer. There are few problems with your code, that I’ve fixed already. – Krzysiek Dróżdż Jan 6 at 20:33
  • Shortcodes are supposed to return their content, not display it – Tom J Nowell Jan 6 at 21:20
2

Using titles in such comparisons is always a little bit risky - you have to deal with encodings and so on.

Much safer way is using of slugs in code, because they are url-safe.

So your code could look like this:

function posend_text_shortcode() {
  $mycategory = get_the_category();

  $slug = '';
  if ( ! empty($mycategory) ) {  // you have to check, if any category is assigned
      $slug = $mycategory[0]->slug;
  }

  switch($slug){
      case 'this-that': // change to real slug
          get_template_part('/inc/style/check.php'); // you should use get_template_part instead of including template parts
          break;

      default:
          get_template_part('/inc/style/default.php'); 
          break;
  }
}

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.