SQL / wp_update_post: change post custom field to CPT post taxonomy

Question

the setup is as follow:
I have posts with a custom field: actor = 'tom hanks'
for advanced management I created a custom post type (actors) and added “tom hanks” as a post within that actors taxonomy.

Via plugin ‘Advanced custom fields’ I connected the custom taxonomy (actors) to the default posts so I can select ‘tom hanks’ on the regular post page.

This can be done manually (check the custom field value and click the according actors category) but there are way more than 1500 posts and many other similar custom field values.

Do you have any idea how that can be solved via SQL query or function?

in one line:
get value from customfield ‘actors’ and move to taxonomy(‘actors’) for that post.
the custom field value could be used as the taxonomy slug.

I think it’s also possible with the wp_update_post function but I have no idea how to call all posts, the custom fields and taxonomy.

If somebody can please help me out with the query for a mysql or similar you would definitely make my day 🙂

EDIT:
I think wp_update_post is a good way to accomplish this task.

// get all post IDs
$post_ids = get_posts(array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'numberposts'   => -1, // get all posts.
    'fields'     => 'ids', // Only get post IDs
));

// info: custom field 'actor' = 'Tom Hanks'

// Update all posts
foreach ($post_ids as $id) {

  $excerpt =  get_post_meta($id, 'excerpt', true);  // for testing purpose I added a customfield 'excerpt'
    // info: custom field 'actor' = 'Tom Hanks'
  $customfield_value = get_post_meta($id, 'actor', true);
  // change the custom field values to slug format:  'Tom Hanks' > 'tom-hanks'
  $customfield_value = sanitize_title_with_dashes($customfield_value);


  $post = array(
    'ID' => $id,      // select all posts
    'post_excerpt' => $excerpt, // update the excerpt field with the customfield 'excerpt'
    'tax_input'      => array(
      'actor' => array(
        $customfield_value
      )
    )
  );

  wp_update_post( $post );

  // delete the old post meta after we moved it to the taxononmy
  //delete_post_meta($id, 'actor');

}
0
, , Gerald 2 years 2020-04-30T23:10:39-05:00 0 Answers 96 views 0

Leave an answer

Browse
Browse