Kermode

/ˈkɜːrmoʊd/
The Spirit Bear

Written by Gray Gilmore

I make websites for a living. I love CSS and building simple and modular stylesheets. Somewhere along the way I also turned into a Ruby developer. Life comes at you fast I guess. You can read my resume to learn about my journey so far.

You can find me as @graygilmore on several platforms:

Good ol' fashion email works, too: hello@kermode.co

You can subscribe to this blog via RSS: XML, JSON

WordPress: Limit Custom Taxonomies to Specific Pages

Custom taxonomies are super powerful when put to good use. The problem with a large website, however, is that the taxonomies probably aren’t that applicable to every single page. After a necessity to fix this for an upcoming project, I had to get my hands dirty!

I had to really put on my thinking cap for this one. Out of the box, WordPress provides the function remove_meta_box but only allows you to specify whether you want to remove it from posts or pages.

remove_meta_box('yourmetabox','page','normal');

We’ll eventually need to include that in our function, but first we’ll need to find out where we are.

Where Are We?

A question more accustomed to road trips but very applicable here. When we’re editing a page, we need to first find out what page we’re editing. We can do this by using the following:

$post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'];

Now that we’ve stored our pages ID in $post_id, we can use that to find out our page’s parent and other ancestors:

$parent = get_post_ancestors($post_id);

Who’s Your Daddy?

Now we have our page’s ID, its parent’s ID and any of its other ancestors’ IDs! That’s a whole lot of information – time to use it.

We’re going to check to see if the ancestor that we’re looking for comes up in our array:

if(in_array('4',$parent)) {
  // do something
}

In my case, the ancestor that I was looking for has an ID of ’4′ – so that’s the number that I’m looking for. But because we want to remove the custom taxonomy from pages that aren’t under our ancestor, we’ll need to change the ‘if’ to ‘if not’:

if(!in_array('4',$parent)) {
  // do something
}

Putting It All Together

Here is our code in all of its glory. Add this to your functions.php file:

// Remove taxonomy boxes from certain pages
function gg_no_more_tax() {
  $post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'];
  $parent = get_post_ancestors($post_id);
  if(!in_array('4',$parent)) {
    remove_meta_box('yourmetaboxdiv','page','normal');
  }
}

add_action('admin_init','gg_no_more_tax');

To find the value that you need to enter for yourmetaboxdiv, you can right click on the custom taxonomy box and inspect the element to find the #id of the div.