Skip to content

Instantly share code, notes, and snippets.

@johndigital
Last active March 29, 2016 18:29
Show Gist options
  • Save johndigital/180d7b880b73df75943132e3e8a6d9d4 to your computer and use it in GitHub Desktop.
Save johndigital/180d7b880b73df75943132e3e8a6d9d4 to your computer and use it in GitHub Desktop.
Move metadata from one Wordpress site to another (quick and dirty)
<?php
// Add this to the functions.php file of the SENDING site
function fh_export_page_metadata(){
$post = get_post();
// change this to target site URL
$target_site = 'http://www.example-site.com';
// add 'run' to URL query string to run this
if ( !empty($_REQUEST['run']) ){
// get all pages
$args = array(
'posts_per_page' => -1,
'order' => 'ASC',
'post_type' => 'page',
'post_status' => 'any'
);
$all_posts = get_posts($args);
// init output
$out = array();
// loop pages
foreach ($all_posts as $this_post){
// get all page meta you want to transfer
$page_meta = get_post_meta($this_post->ID, '_custom_page_meta', true);
$media_meta = get_post_meta($this_post->ID, '_custom_media_meta', true);
// add post ID and two meta values to output
$out[] = array(
'page_id' => $this_post->ID,
'page_meta' => $page_meta,
'media_meta' => $media_meta
);
}
// encode as JSON
$encoded = json_encode($out);
// send POST request with all metadata and associated page IDs
$response = wp_remote_post( $target_site . '/wp-admin/admin-ajax.php?action=fh_meta_import', array(
'method' => 'POST',
'timeout' => 60,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => $encoded,
'cookies' => array()
)
);
// dump response and exit when done
var_dump($response); exit;
}
}
add_action('init', 'fh_export_page_metadata');
// Add this to the functions.php file of the RECEIVING site
function fh_receive_imported_meta(){
// get JSON data from incoming request
$data = json_decode(file_get_contents('php://input'), true);
// start counter
$count = 0;
// loop all incoming pages
foreach ( $data as $single_post ){
// update meta by ID
$page_meta = update_post_meta($single_post['page_id'], '_custom_page_meta', $single_post['page_meta']);
$media_meta = update_post_meta($single_post['page_id'], '_custom_media_meta', $single_post['media_meta']);
// incrememnt counter
$count++;
}
// output results and exit
echo 'success! Updated posts: ';
echo $count;
exit;
}
add_action( 'wp_ajax_fh_meta_import', 'fh_receive_imported_meta' );
add_action( 'wp_ajax_nopriv_fh_meta_import', 'fh_receive_imported_meta' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment