in MySQL, WordPress

Add term to all posts with one MySQL query in WordPress

Today in #wordpress <Mariaa> asking about some interesting

How to add term to all posts with one MySQL query in WordPress?

in some cases in development stage we do this manually, but when we have a large amount of posts it will be overkilling to do this in hand.

So here is the mine solution.

INSERT INTO wp_term_relationships
(
  SELECT
    id object_id,
    (SELECT term_id FROM wp_terms WHERE name = '<term name>') term_taxonomy_id,
    0 term_order
  FROM wp_posts
  WHERE post_type='<custom post type>'
)
ON DUPLICATE KEY UPDATE term_order=term_order;


If your DB prefix is different than wp_ then you should use your prefix in table names (if it is x_ then x_posts instead of wp_posts).

Write a Comment

Comment