DEV Community

loading...

Using the WordPress in_category() function

andystitt829 profile image Andy Stitt ・2 min read

My biggest project at work is the Delaware COVID-19 information website. It is built in WordPress.

I recently had a problem to solve where I wanted alert boxes to automatically display in the language that the page was translated into. We have pages in the three most spoken languages in Delaware: English, Spanish, and Haitian Creole.

I decided to approach it by assigning specific categories to the Spanish and Haitian Creole pages. I was then able to use the WordPress in_category() function to identify which categories that page belonged to.

This applied to single pages, so in page.php, my code looked something like this:

<?php
   if(in_category('spanish')) {
      include 'includes/spanish-file.php';
   } elseif(in_category('haitian-creole')) {
      include 'includes/haitian-creole-file.php';
   } else {
      include 'english-file.php';
   }
?>
Enter fullscreen mode Exit fullscreen mode

This if statement first looks to see if the category assigned to the page is "spanish", and if it is, then the PHP include function displays the content within spanish-file.php.

If the category is not "spanish", then it looks to see if it is "haitian-creole", and if it is, then it displays the contents of haitian-creole-file.php.

If the category doesn't match either of those, then it displays english-file.php.

The majority of pages on the website are in English, so I didn't feel the need to assign an English category and simply included it in the "else" condition for all pages that had neither "spanish" or "haitian-creole" assigned to it.

I wrote this function in the page.php file. I'm sure there are arguments against doing that. If you wanted to, you could also define it as a function in the functions.php file and then call the function in page.php. If you did it that way, it would look something like this:

In functions.php:

<?php
   function multi_language_page_files() {
      if(in_category('spanish')) {
         include 'includes/spanish-file.php';
      } elseif(in_category('haitian-creole')) {
         include 'includes/haitian-creole-file.php';
      } else {
         include 'english-file.php';
      }
   }
Enter fullscreen mode Exit fullscreen mode

No closing PHP ?> tag needed in the functions.php file.

Then, you would call the function in page.php:

<?php multi_language_page_files() ?>

I hope this helps. I was not previously aware of the in_category() function before I found it yesterday. It is extremely helpful in this case!

Discussion (0)

pic
Editor guide