While assigning multiple categories to a post, I need to restrict the category choices on a post depending on what other categories have already been assigned to the particular post.
For example, lets say we have categories A, B and C.
For any post, we want to restrict having both categories B and C. So posts may have the following assignments:
- A, B, C
- A, B
- A, C
No post should have B and C.
How can I achieve this?
Okay, I’ve had a couple minutes free time, so I wrote up a small plugin. 😉
The following goes into a new plugin file
tf-restrict-categories/tf-restrict-categories.php
:The introduction
The basics
This is where the action is
The end
The following goes into a new plugin file
tf-restrict-categories/js/tf-restrict-categories.js
:The JavaScript
Copy&Paste the code into the two files, upload to your
plugins
folder, activate the plugin and find the new settings page.Happy restricting. 🙂
Okay, okay, some words of explaining…
The plugin works as follows. On the settings page, we define some category combination. Let’s say, we want to have the rule If ‘Cat A’ is present, do NOT allow ‘Cat C’. This can be achieved by checking the checkbox in the row Cat A and column Cat C. This means: the row category is the master category, and the column category will be restricted.
Of course, you can have multiple combinations with Cat A (and multiple other categories).
When saving/updating a post (or, to be more precise: when having saved/updated a post), the categories are checked against the stored plugin settings – and adapted.
Anything else?
There doesn’t appear to be any hook that you can leverage to alter the categories going in when
wp_create_post
orwp_update_post
are called.However, you can always hook on the
wp_insert_post
action to update categories after a post is saved or updated:What this snippet above does is fetch the categories that would be assigned to a post, leaves only the ones that should be assigned in
$new_categories
, and then over-writes the categories for that post.As you can see, I left out the logic to figure out which categories are valid, since you didn’t describe what that logic is.