Tag all Wordpress posts

2019-08-31 07:03发布

问题:

I've been searching for hours, either for a plugin or some safe looking SQL to do this, but nothing seems to be exactly what I need...

I have a Wordpress site of approximately 32,000 posts, and we use various tags to help with administration on the back end (i.e. they're not visible on the front end or used for SEO, before anybody comments on too much usage of the same tag). About 30,000 of these posts include the tag 'new', but we need to now tag the remaining ~2,000 to match.

The WP administration panel isn't really up for the task - it would take somebody days to go through and apply a tag to 2,000 posts. Various plugins seem to exist but they don't really do what they claim in the descriptions. And the only SQL I could find that seemed helpful assumes that the tag is new and that I want to apply it to all posts in a single category. I suppose I could delete the existing tag (again, not a fun task with Wordpress' admin panel - it generally crashes after about 30 posts meaning somebody has to sit clicking the button over and over) and then run the SQL to apply a new.

Can somebody point me in the right direction please?

回答1:

You could run a loop over all of your posts and use wp_set_object_terms() to add the desired tag:

http://codex.wordpress.org/Function_Reference/wp_set_object_terms



回答2:

I had this problem today too. I tagged all of my posts with the following SQL. (Replace <prefix> with your DB prefix and "GlobalTag" with whatever you want your tag name to be.)

# create a term which will be your new tag
INSERT INTO <prefix>_terms (name, slug) VALUES ("GlobalTag", "global-tag")

# this is what defines the term as a Tag vs Category vs Video Category, etc
# only do this if you are creating the category through SQL, not the GUI
INSERT INTO <prefix>_term_taxonomy (term_id, taxonomy, count)
SELECT
  (SELECT term_id from <prefix>_terms AS term WHERE term.name="GlobalTag") as "term_id",
  "tag" as "taxonomy",
  (SELECT COUNT(*) FROM <prefix>_posts AS posts WHERE (posts.post_status IN ("publish", "draft")) AND LENGTH(post_content) > 25) as "count"

# now tag every post with GlobalTag
INSERT INTO <prefix>_term_relationships
SELECT
  id as "object_id",
  (
    SELECT term_taxonomy_id
    FROM <prefix>_term_taxonomy AS term_tax
    INNER JOIN <prefix>_terms ON <prefix>_terms.term_id = term_tax.term_id
    WHERE <prefix>_terms.name="GlobalTag"
  ) as "term_taxonomy_id",
  0 as "term_order"
FROM <prefix>_posts AS posts
WHERE (posts.post_status IN ("publish", "draft")) AND LENGTH(post_content) > 25

NOTE: you may want to tweak the posts query in here. This tags all posts that are published and/or drafts and that have content that is longer than 15 words.