This weekend, I shared how to setup a query to find all untagged posts in WordPress that aren’t tagged with a specific tag. In my example, I opted to use IDs (for no particular reason), but Ross also showed how you can use slugs, as well.
Anyway, there are a number of things that you can do with untagged posts – perhaps you want to remove them, perhaps you want to categorize them, or perhaps you want to apply a tag to them so that they’re stamped with a tag (like one that was not
Tagging Untagged Posts and CPTs
This is a relatively straightforward process, but there are a couple things to note if you find yourself doing this.
First, note that the Codex states the following:
For hierarchical terms (such as categories), you must always pass the id rather than the term name to avoid confusion where there may be another child with the same name.
Secondly, note that the function that’s being used depends on the post type. That is, there is a way to tag the standard post type, then there’s a way to tag a custom post type.
Tagging a Post
The Codex also has a small note about this function as it relates to custom post types:
This function will only work on the native post type. For a taxonomy on a custom post type use wp_set_object_terms().
The way to use that function is easy enough (and the accompanying Codex article covers it well). Here’s a simple example:
Make sure to read the code comment: this assumes that that the function in the previous post hasn’t changed.
Tagging a Custom Post Type
If you want to do the same thing for a custom post type, there’s very little that needs to be changed. Note that the query that’s defined in the previous post must have a different post_type
parameter than post
.
In this case, it would correspond to the name of a custom post type.
Secondly (and as mentioned above), in this case, the function that needs to be used is wp_set_object_terms
. This works much in the same way that wp_set_post_terms
works.
Note that in this function there is an optional $append
argument that can be passed. In the case below, I’ve set it up such that it will append a tag – after all, the ID is that we’re finding untagged posts – but if you end up query for information that already has a tag, but perhaps not a specific tag, then you may want to add this tag to those that already exists.
That’s what this code does:
For the most part, there’s very little difference save for the name of the function, the optional final argument, and how the query is constructed.
Improving the Initial Function
Perhaps the best thing to do would be to generalize the initial function so that the post type that’s being queried is passed as an argument to the function. That way, it’s flexible enough to query for whatever custom post type is defined.
Regardless, that’s straightforward enough, and the function calls that are demonstrated above still stand as-is.
Leave a Reply
You must be logged in to post a comment.