skip to Main Content

I am converting wordpress custom fields into one single array in the wp database. I am able to do it but I have duplicated entries. I just need one. Please guide me. Thanks!

Before running my code:
enter image description here

After running my code:
enter image description here

What I actually want:
enter image description here

My code:

add_action( 'init', function() {
    if ( 'migrate' !== filter_input( INPUT_GET, 'action' ) ) {
        return;
    }
 
    $query = new WP_Query( [
        'posts_per_page' => -1,
        'post_type'      => 'post',
        'post_status'    => 'any',
    ] );
    if ( ! $query->have_posts() ) {
        return;
    }
 
    while ( $query->have_posts() ) {
        $query->the_post();
        
        $field_id_1 = 'gallery';
        $field_value_1 = get_post_meta( get_the_ID(), $field_id_1, false );
        
        update_post_meta( get_the_ID(), $field_id_1, $field_value_1);
    }
} );

2

Answers


  1. Chosen as BEST ANSWER
    add_action( 'init', function() {
        if ( 'migrate' !== filter_input( INPUT_GET, 'action' ) ) {
            return;
        }
     
        $query = new WP_Query( [
            'posts_per_page' => -1,
            'post_type'      => 'post',
            'post_status'    => 'any',
        ] );
        if ( ! $query->have_posts() ) {
            return;
        }
     
        while ( $query->have_posts() ) {
            $query->the_post();
            
            $field_id_1 = 'gallery';
            $field_value_1 = get_post_meta( get_the_ID(), $field_id_1, false );
            
            delete_post_meta( get_the_ID(), $field_id_1 );
    
            add_post_meta( get_the_ID(), $field_id_1, $field_value_1);
    
        }
    } );
    

    @Mulli I got it working this way. Instead of updating the post_meta, I decide to delete the post_meta first and then add_post_meta. Thank you for your help!


  2. See the relevant part:

        $first=true;
        $field_id_1 = 'gallery';
        while ( $query->have_posts() ) {
            $query->the_post();
            
            $field_value_1 = get_post_meta( get_the_ID(), $field_id_1, false );
    
            if ($first){
                update_post_meta( get_the_ID(), $field_id_1, $field_value_1);
                $first = false;
            else delete_post_meta( get_the_ID(), $field_id_1, $field_value_1);
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search