Programmatically Add Multiple Post Terms in WordPress

A couple of weeks ago, I shared a simple gist for how to programmatically add post terms in WordPress. If you’ve read the series on importing CSV files into WordPress, then you’re likely to encounter something like the following scenario:

Given a CSV, apply multiple terms to a single post when the terms are delimited by another character.

So, for example, let’s say that you have a CSV and each value is, naturally, separated by a comma. Within one of the columns, words – or terms, in our case – are delimited by semicolons. Each value that precedes a semicolon represents a term (related to any given taxonomy in the system – this is irrelevant for this particular post).

Adding multiple terms to a post, or post type, is relatively simple and can be based off the functionality already shared.

Programmatically Add Multiple Post Terms

The process for doing this is straightforward:

  1. Check to see if there are multiple terms
  2. If there are, loop through them and apply each to the given post
  3. Otherwise, continue with the original routine

Here’s the process that I’ve used in order to do exactly that.

1. Check for Multiple Terms

This assumes that the delimiter that you’re using it a semicolon, though you would obviously change that to be whatever is relevant to your case:

Easy enough, isn’t it? The code simply checks to see if at least a single semicolon exists. Note that this does mean your term cannot have a semicolon in it. That is, it must be treated as a sort of “reserved word” when creating the CSV files.

2. Apply Multiple Terms

This is the easy part: Since we already have a function for assigning a single value, we can take advantage of that function and use it to apply each of the terms:

Notice that this function reads each of the values into an array and loops through the array calling our original function.

3. Use The Original Code

From here, we can take the original function and then enhance it just a little bit so that it checks for multiple terms and then applies them using the same logic that already exists.

Obviously, it’s hard to capture every variation of a use case for something like this, but the above code should provide some general direction on how to apply multiple terms to a post (at least, when importing from a CSV).

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.