Last active
May 6, 2016 12:59
-
-
Save PatelUtkarsh/136cc0f9a60924e8f35b to your computer and use it in GitHub Desktop.
Add all post meta using single Insert SQL for migration.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* $arr all meta in associative array. | |
* $post_id where to insert post. | |
**/ | |
function add_post_meta_all( $arr, $post_id ) { | |
global $wpdb; | |
$inserts = array(); | |
foreach ( $arr as $key => $val ) { | |
if ( is_array( $val ) ) { | |
foreach ( $val as $item ) { | |
// insert multiple post meta if it is array | |
$meta_value = wp_unslash($item); | |
$meta_value = sanitize_meta( $key, $meta_value, 'post' ); | |
$inserts[] = $wpdb->prepare( "(%d,%s,%s)",$post_id,$key,$meta_value); | |
} | |
} else { | |
$meta_value = wp_unslash($val); | |
$meta_value = sanitize_meta( $key, $meta_value, 'post' ); | |
$inserts[] = $wpdb->prepare( "(%d,%s,%s)",$post_id,$key,$meta_value); | |
} | |
} | |
if ( ! empty( $inserts ) ) { | |
$sql = "INSERT INTO {$wpdb->postmeta} (`post_id`,`meta_key`,`meta_value`) VALUES " . implode( ', ', $inserts ); | |
$maybe_inserted = $wpdb->query( $sql ); | |
if ( ! $maybe_inserted ){ | |
error_log( $sql . " error: " . $maybe_inserted ); | |
//\WP_CLI::error( $sql . " error: " . $maybe_inserted, false ); | |
return false; | |
} | |
return true; | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment