Skip to content

Instantly share code, notes, and snippets.

@aolin480
Last active April 1, 2016 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aolin480/40d5d3b422444635ffca49400948d52d to your computer and use it in GitHub Desktop.
Save aolin480/40d5d3b422444635ffca49400948d52d to your computer and use it in GitHub Desktop.
Export Wordpress Post by ID - by setting a temporary author, assigning it to the post, then reverting temp author
<?php
/*
NOT TOTALLY FUNCTIONAL - NOT TOTALLY FUNCTIONAL - NOT TOTALLY FUNCTIONAL - YOU MAY HAVE TO WORK IT INTO YOUR PROJECT DIFFERENTLY
*/
add_action('admin_init', function(){
if( isset( $_GET['di_export'] ) ) :
// post id = 177 // Collision Center
$post_id = 877;
// insert a new temp user
$userdata = array(
'user_login' => '_di_export',
'user_url' => '',
'user_pass' => 'awesome1234', // When creating an user, `user_pass` is expected.
'role' => 'administrator'
);
$_temp_author_id = wp_insert_user( $userdata );
// get the original post by ID
$post = get_post($post_id);
// set the start date to make sure we are only exporting a single post, and the correct post
$start_date = date( 'Y-m', strtotime($post->post_date) );
// set end date the same as start date to export only one post
$end_date = $start_date;
// grab the original author ID to revert original post author back
$original_author_id = $post->post_author;
// set the posts' author to the temporary one
$post->post_author = $_temp_author_id;
// update the post with temporary author
$post_updated = wp_update_post($post);
// if post was updated and a temp author ID exists, then export the post by corresponding ID
if( $post_updated && $_temp_author_id ) :
$args = array(
'content' => 'page',
'author' => $_temp_author_id,
'start_date' => $start_date,
'end_date' => $end_date
);
include_once(ABSPATH.'/wp-admin/includes/export.php');
export_wp($args);
// set the post author back to the original author
$post->post_author = $original_author_id;
// update/revert the post to how it was before exporting
$post_updated = wp_update_post($post);
wp_delete_user( $_temp_author_id, $original_author_id );
die();
endif;
endif;
});
// NOT TOTALLY FUNCTIONAL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment