Importing CSV files (or something similar) is something that’s nothing new to web development.

If you’re writing a server-side code that’s responsible for importing a file in the context of WordPress, then you can be doing anything from programmatically creating posts to creating more complex relationships among post types, taxonomies, and so on.

In this case, it’s nice to have an abstract function that can help to do a lot of the repetitive work for you. After all, aren’t functions specifically for that?

Programmatically Add Post Terms

Before looking at the code to do this, it’s worth noting a couple of assumptions that are being made for the sake of this example. It’s simple enough to prove a point, but it may need additional arguments if you’re working on something more complex.

In general, what we’re doing is programmatically creating a post and then associated a term for a taxonomy with the post. We’re given the following information:

  1. `$post` references to a post array that has all of the properties that you’d expect. This could just as easily be an object.
  2. `$value` is the name of the term to be associated with the post.
  3. `$taxonomy` is the name of the taxonomy for which the term will be created.

In an object-oriented context, the function call will look like this:

$this->set_post_term( $post, $value, $taxonomy );

First, the code:

Now before showing an actual example, note that the code works as follows:

  1. We check to see if the term exists.
  2. If the term does not exist, then we insert the term. In doing so, we take the `$value` and replace the spaces with hyphens while also lowercasing the contents for the sake for following the conventions of a WordPress slug.
  3. Once the term is created, we can then associate the with the post using `wp_set_post_terms`. Note that this will what work whatever post type (despite the function name) and I’ve opted to use `true` as the final parameter so that it will append the term to the list of terms that already exist. I’m not a fan of blindly overwriting data.

So given the following data:

  • `$term_name` being ‘acme’
  • `$taxonomy` being ‘acme_taxonomy`

Then we’d made a function call like this:

$this->set_post_term( $post, 'acme', 'acme_taxonomy' );

It’s simple, but if you’re working with a mass import and multiple taxonomies, having this function really saves a lot of time and repetitive code.