functions - Return category name with & Ampersand doesnt work

admin2025-06-04  2

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;
  }
}

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;
  }
}
Share Improve this question asked Jan 6, 2019 at 19:43 JoaMikaJoaMika 6986 gold badges27 silver badges58 bronze badges 5
  • And why don’t you check by term slug? It would be much safer... – Krzysiek Dróżdż Commented Jan 6, 2019 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.. – JoaMika Commented Jan 6, 2019 at 20:23
  • ok sorry, everything seems to work fine now when I test for slug. thanks for pointing it out – JoaMika Commented Jan 6, 2019 at 20:29
  • Take a look at my answer. There are few problems with your code, that I’ve fixed already. – Krzysiek Dróżdż Commented Jan 6, 2019 at 20:33
  • Shortcodes are supposed to return their content, not display it – Tom J Nowell Commented Jan 6, 2019 at 21:20
Add a comment  | 

1 Answer 1

Reset to default 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;
  }
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749038345a315831.html

最新回复(0)