Is it possible to update post meta from array in o

2020-06-23 08:36发布

问题:

Code snippet:

$save_dbarray = array(
    'email'         => 'email@email.se',
    'adress'        => 'adress'
);

//Save values from created array into db
foreach($save_dbarray as $meta_key=>$meta_value) {
   update_post_meta($post_id, $meta_key, $meta_value);
}

Is there any way to optimize above code? In this simple scenario, it wouldn't matter, but If I have a large array then I guess it might be performance issues when updating?

I would like to do something like:

update_post_meta($post_id, $save_dbarray);

Is this possible?

回答1:

While the other answers are creative solutions to your problem, they don't seem to address the actual issue or answer your question.

The Answer

No. WordPress's update_post_meta only works on one field at a time. Your best bet is to stick with the method you're using above, with the foreach loop. The other answers provide ways of storing that meta in a single field, which is probably fine for some but (as in my case) some need to query against those values, and having a serialized or JSON-encoded array doesn't cut it.

Unfortunately, WP provides no "bulk meta update" method, and if it did, it would likely be a foreach loop. You can always write a function to help make your code cleaner, at least:

<?php
function update_post_meta_array( $post_id, $meta ) {
    if ( ! get_post( $post_id ) || ! is_array( $meta ) || empty( $meta ) ) {
        return false;
    }

    foreach ( $meta as $meta_key => $meta_value ) {
        update_post_meta( $post_id, $meta_key, $meta_value );
    }

    return true;
}


回答2:

phatskat is correct in that there's no built-in way to do this and a foreach loop is required.

This is the most efficient I've found - wrote about it in a blog post as well:

add_action('init', 'bulk_update_post_meta_data');

function bulk_update_post_meta_data() {
    $args = array(
        'posts_per_page' => -1,
        'post_type' => 'POSTTYPEHERE',
        'suppress_filters' => true 
    );

    $posts_array = get_posts( $args );

    foreach($posts_array as $post_array) {
        update_post_meta($post_array->ID, 'POSTMETAKEY', 'NEWVALUE');
    }
}


回答3:

Why not try with serialize() like this:

According to update_post_meta() documentation you can pass the $meta_value as array, that will be serialized into a string.

$save_dbarray = array(
  'email'         => 'email@email.se',
  'adress'        => 'adress'
);


update_post_meta($post_id, 'my_custom_fields', $save_dbarray);


回答4:

Possible multiple value at a time you can your value genearte escaped_json

$escaped_json = '{"key":"value with \\"escaped quotes\\""}';

update_post_meta( $id, 'double_escaped_json', wp_slash($escaped_json) );