Skip to content

Instantly share code, notes, and snippets.

@anubhavbhatt
Created January 16, 2020 18:24
Show Gist options
  • Save anubhavbhatt/8f2155bdfbdacfb7624893ee87d920ff to your computer and use it in GitHub Desktop.
Save anubhavbhatt/8f2155bdfbdacfb7624893ee87d920ff to your computer and use it in GitHub Desktop.
Copy the attachment of one WP to another WP
<?php
$servername = "YOUR_SERVER_NAME";
$username = "YOUR_USERNAME";
$password = "YOUR_PASSWORD";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$fromDatabase = 'DATABASE_ONE';
$fromTablePost = $fromDatabase . '.wp_posts';
$fromTablePostMeta = $fromDatabase.'.wp_postmeta';
$toDatabase = 'DATABASE_TWO';
$toTablePost = $toDatabase .'.wp_posts';
$toTablePostMeta = $toDatabase .'.wp_postmeta';
$sql = "SELECT * FROM $fromTablePost WHERE post_type = 'attachment'";
$result = $conn->query($sql);
if($result->num_rows > 0 ){
// output data of each row
while($row = $result->fetch_assoc()) {
$postID = $row['ID'];
$newRow = make_data($row,'ID',$conn);
// Insert Data into Post Table
$inserted_id = insert($conn, $toTablePost, $newRow);
// Collect data from PostMeta
$sql2 = "SELECT * FROM $fromTablePostMeta WHERE post_id = $postID";
$result2 = $conn->query($sql2);
if($result->num_rows > 0 ){
// output data of each row
while($row2 = $result2->fetch_assoc()) {
$newRow2 = make_data($row2,'meta_id', $conn);
$newRow2['post_id'] = $inserted_id;
// Insert Data into Post Meta
insert($conn, $toTablePostMeta, $newRow2);
}
}
}
}
$conn->close();
function insert($db, $table = 'posts', $data = array())
{
$columns = implode(", ", array_keys($data));
$escaped_values = array_values($data);
$values = implode(", ", $escaped_values);
$sql = "INSERT INTO $table ($columns) VALUES ($values)";
if ($db->query($sql) === true) {
return mysqli_insert_id($db);
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
}
function make_data($row=array(), $key_to_exclude='ID', $conn){
$newRow = array();
foreach($row as $key => $value){
if($key == $key_to_exclude) continue;
if(!ctype_digit($value)){
$newRow[$key] = "'" . mysqli_real_escape_string($conn,$value) . "'";
}else{
$newRow[$key] = $value;
}
}
return $newRow;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment