0

I have over 10,000 posts on a site which all need to have a tag added to them. WP_Query is either running out of memory or timing out on my server and in the past running large queries with this function, i've had my MySQL query limit reached with similar functions

I know I can't use WP_Query and wp_set_post_tags efficiently, and i'm sure it can be done with wpdb without as many queries to the database. There's only one tag which needs to be added to each post.

How can it be done with a wpdb query?

  • Your best bet - Go with SQL. – krembo99 Feb 7 '14 at 3:53
  • SQL or wpdb whichever makes the fewest queries to the db. Any chance you can show some code? I'm only able to work with WP_Query get_posts etc. – Anagio Feb 7 '14 at 3:55
  • if you want with wp_query this should work : <?php global $wp_query;$tag = 'test';$query_vars= array('post_type' => 'post');$posts = $wp_query->query($query_vars);foreach($posts as $post) wp_add_post_tags($post->ID,$tag); ?> . The SQL method is more reliable, but a bit complicated if you are not familiar with the inner works .. if you are having problems, you should divide the queries to pieces. ( each 1000 for example). this is only a concept .. you should use proper queries ( like prepare() etc ) – krembo99 Feb 7 '14 at 5:19
  • @krembo99 you mean wp_set_post_tags the problem with this is, each instance of wp_set_post_tags within the loop is generating a query to the database. That's over 10,000 queries. Something i'm trying to avoid. – Anagio Feb 7 '14 at 9:19
  • I understand , but if you divide the query for only a one time job - i do not see what the problem is . Anyhow, here is the SQL ( next comment ) you will have to create the tag my_tag first on ONE or more posts. Please also TEST thoroughly and backup DB before you use it on production – krembo99 Feb 7 '14 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.