0

To save complication I have imported a custom fields (categories & terms) to the wp_postmeta table, which are linked to respective posts. Shown as listed in wp_postmeta:

meta_id post_id meta_key                meta_value
183     45      job_listing_region      Kingston
208     46      job_listing_region      Fajardo
233     47      job_listing_region      Letchworth
258     48      job_listing_region      Oxford
283     49      job_listing_region      Beaulieu-sur-Mer

Using a SQL query how do you move these to taxonomies & terms to the following tables?

wp_term_relationships
wp_term_taxonomys
wp_terms

I'm finding the table relationship a little confusing, whether to JOIN or UPDATE in this instance. A good reference article below for someone who knows what they're doing. Thanks in advance, Murray

SQL to update custom post taxonomies

1 Answer 1

0

I would recommend using WordPress function calls to set up your terms, instead of SQL. This is assuming you've already registered a custom taxonomy called job_listing_region.

// Add this to your theme's functions.php
function convert_meta_to_term() {
  global $wpdb;
  $meta_query = $wpdb->get_results("
    SELECT *
    FROM $wpdb->postmeta
    WHERE meta_key = 'job_listing_region'
  ");
  foreach ($meta_query as $meta) {
    // Append new terms for each post
    wp_set_object_terms($meta->post_id, $meta->meta_value, 'job_listing_region', true);
  }
}
add_action('wp_ajax_convert_meta_to_term', 'convert_meta_to_term');

Now you can call this function by going to the URL http://your-blog.tld/wp-admin/admin-ajax.php?action=convert_meta_to_term.

6
  • Thanks Dan, can you give me a heads up on how to use function calls, as I have never used them before.
    – Muzza
    Commented Jun 9, 2014 at 5:16
  • Sure, I've changed the example to be callable via an WP AJAX-style request. Commented Jun 9, 2014 at 17:35
  • The error return value is 0, have add in AND post_type = 'job_listing' and have checked the custom taxonomy to be register_taxonomy( 'job_listing_region' still with no change to error value. Thanks again but still not sure.
    – Muzza
    Commented Jun 10, 2014 at 6:31
  • Yeah, the return value 0 is totally normal. The thing you should be checking for is whether these terms are getting created, or if there are errors logged, etc. When you say you added that AND clause, did you also join on the wp_posts table? Because wp_postmeta has no post_type column. And you can call exit if you want to suppress the 0. I normally do that and add some debug text in there. Commented Jun 11, 2014 at 7:32
  • Sorry I have checked for terms and log but am unable to find a solution.
    – Muzza
    Commented Jun 11, 2014 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.