0

I have a custom field in post_meta table of wordpress database. It's called 'combined'. I want to seperate the values based on key and save them as multiple rows if there are multiple values for the key.

My meta_key:

enter image description here

Result after I run my code:

enter image description here

What I want:

enter image description here

My code:

add_action( 'init', function() {
    if ( 'migrate' !== filter_input( INPUT_GET, 'action' ) ) {
        return;
    }
 
    $query = new WP_Query( [
        'no_found_rows' => true,
        'update_post_term_cache' => false,
        'fields' => 'ids',
        'posts_per_page' => -1,
        'post_type'      => 'post',
        'post_status'    => 'any',
    ] );
    if ( ! $query->have_posts() ) {
        return;
    }
 
    while ( $query->have_posts() ) {
        $query->the_post();
        
        $data = get_post_meta( get_the_ID(), 'combined', true );
        
foreach($data as $singleData => $value ){
    
    update_post_meta( get_the_ID(), $singleData, $value );


}

    }
} );
3
  • That code appears to me as though it should be functional (though I'd probably modify the query to only select posts containing the combined meta). What's the problem?
    – bosco
    May 30, 2022 at 17:05
  • @bosco Thank you for your reply. All posts have the combined meta field. I avoided querying by meta as the query is not very performance optimized. I have modified the query to only fetch ids as other data is not required.
    – Ryan Tan
    May 31, 2022 at 4:09
  • @bosco Coming to the issue. Please check screenshot 2 and 3. I want it like screenshot 3. Multiple meta_key with the values. Not serialized array.
    – Ryan Tan
    May 31, 2022 at 4:10

1 Answer 1

0

I have found the way to get the values as I want them to be in the database. Changing the loop part in the above code with code did the trick.

$data = get_post_meta( get_the_ID(), 'combined', true );
        
foreach($data as $singleData => $value ){
    $thisArray = $data[$singleData];    
        foreach ($thisArray as $key2 => $value){
            add_post_meta( get_the_ID(), $singleData, $thisArray[$key2], $unique = false);
        }   
}

Your Answer

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

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