Get posts with no tags?

I’m not in the position to code right now, but here is an idea

A thousand posts is quite a lot, but it is even more if you are retrieving all posts from the db in one go. What if you have ten thousand posts, of which only ten or twenty is not tagged after the whole retagging operation. This can become such a huge query that you run the danger of timing out

I would suggest the following:

  • If this operation is just going to be used for the purpose of retagging only without paging, use get_posts. WP_Query returns a lot of information that won’t be necessary.

  • Retrieve a manageable amount of tags at any given time, say 100 tags at a time till it is all done. This will not only load faster, but your list will also not be that overwhelming. You can also paginate your list if you wish, but again, as not to overwhelm the user, I would not do this. Stick to one page.

To properly manage and retrieve only the posts without tags, you will first need to get a list of all your tags. This can simply be done by the function get_tags(). You most probably will need to get only the ids from the returned array of tag objects. For this you can make use of wp_list_pluck

This can then be used in your query to exclude all posts which have tags attached to them. You can make use of the tag__not_in parameter. This will only retrieve posts now which does not any tags

Here is a concept query (Caveat: Untested and as stated, only a concept)

$tags = get_tags();
$tag_ids = wp_list_pluck( $tags, 'term_id' );

$args = array(
   'posts_per_page' => 100,
   'tag__not_in' => $tag_ids
);

$query = get_posts( $args ); // Use which suits your best, get_posts or WP_Query
// $query = new WP_Query( $args );

// YOUR POST LOOP