Search code examples
wordpressimportadvanced-custom-fieldsbulkupdate

Moving Wordpress Custom Field Value into Default Editor/Excerpt


I am in the process of migrating posts between an old and a new website. ACF was used on the old website and when I import the posts into the new website it creates the custom fields "banner_description" and "main_description".

I would like to do away with these custom fields and have the values from each be put into the default Excerpt and Editor text boxes.

banner_description -> Excerpt

main_descriptoin -> Default WYSIWYG Editor

How would I go about doing this?


Solution

  • Utilize the wp_update_post() function to update the content and excerpt of each post you want. Pull in the ACF data you need with the get_field() ACF function so you can set the content and excerpt accordingly. You can call the update function via the init action.

    Note: Recommended to only add and run this init action once and then remove the function so it won't be called every time a page loads.

    function update_posts_content_excerpt() {
      $args = array(
        'post_type'      => 'post',
        'posts_per_page' => -1,
        'post_status'    => 'publish'
      );
      $posts_array = get_posts( $args );
    
      // Loop through those posts 1 by 1
      foreach ($posts_array as $post) {
        $post_id = $post->ID;
    
        // Get current value of the ACF fields
        $banner_description = get_field("banner_description", $post_id);
        $main_description = get_field("main_description", $post_id);
    
        // Create array of data to update for the post
        $post_update_data = array(
          'ID'           => $post_id,
          'post_excerpt' => $banner_description,
          'post_content' => $main_description
        );
        // Update the post into the database
        wp_update_post( $post_update_data );
      }
    }
    add_action('init', 'update_posts_content_excerpt');