The template I was using ran several, different, custom categories through the archive.php template. I needed to hook in some code to just one type of category, but not the others. I needed some way to test the current archive category type, but all the hooks were too generic.
After much messing about, I figured out how to get the current archive category type in WordPress. Use the get_body_class() WordPress function, then test for your category using in_array().
Here's how that looks:
$body_classes = get_body_class();
if (in_array('tax-job_listing_category', $body_classes)) {
// code to run
}
How does it work?
When you view the source code of a WordPress page, it usually has a number of classes in the body tag. In my example, it looked like this:
<body class="archive tax-job_listing_category term-short-term-rentals term-18 logged-in admin-bar no-customize-support wp-custom-logo post-image-below-header post-image-aligned-center sticky-menu-fade right-sidebar nav-float-right fluid-header separate-containers active-footer-widgets-0 header-aligned-left dropdown-hover">
The function get_body_class() basically turns that into an array, which looks like this:
Array
(
[0] => archive
[1] => tax-job_listing_category
[2] => term-short-term-rentals
[3] => term-18
[4] => logged-in
[5] => admin-bar
[6] => no-customize-support
[7] => wp-custom-logo
[8] => post-image-below-header
[9] => post-image-aligned-center
[10] => sticky-menu-fade
[11] => right-sidebar
[12] => nav-float-right
[13] => fluid-header
[14] => separate-containers
[15] => active-footer-widgets-0
[16] => header-aligned-left
[17] => dropdown-hover
)
You can't always count on the classes being in that order, so don't use the array keys to test. It's much better to use in_array().
The code I wanted to run applied only to tax-job_listing_category, rather than tax-job_listing_region, which ran on the same template and used the same WordPress do_action hooks.
Can you use is_category() or is_tax()?
You often can use is_category() or is_tax(), if you know which you want to connect with.
In fact, while researching for this tutorial, I realised is_tax() was even better suited to what I was trying to do.
I've needed to connect in with the body classes before, so I'm leaving this tutorial with the example I started with.
The code l ended up rolling out was:
if (is_tax('job_listing_category')) {
// code to run
}
Notice that to run the query, you have to drop the "tax-" from the start.
The same would apply if you were running it on a category archive. You would use is_category('jquery') if it was on a page that had category-jquery in the body class.
If you had to test for several categories, you would put them in array like this:
if (is_category(array('jquery', 'php')) {
// code to run
}
Using get_body_class() is particularly useful when you need to combine different queries.
There are many ways to arrive at your desired result. Hopefully this helps you get there.