2

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
  • In the loop allow first iteration to update, and all other to delete_post_meta() Commented May 28, 2022 at 7:04
  • @Mulli Thanks for commenting. Do you have any example for me? Commented May 28, 2022 at 7:07

2 Answers 2

1
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!

Sign up to request clarification or add additional context in comments.

Comments

0

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);
    }

2 Comments

I am getting syntax error with if else.
I tried this and it didn't work. I meant the duplicates are still there. pastecode.io/s/xedpwmuv

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.