Skip to content

Instantly share code, notes, and snippets.

@leroyrosales
Created November 23, 2020 02:03
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 leroyrosales/ba27241874819bffe9e6b779604fbadd to your computer and use it in GitHub Desktop.
Save leroyrosales/ba27241874819bffe9e6b779604fbadd to your computer and use it in GitHub Desktop.
Creates button to export all posts in WP into a CSV
add_action( 'restrict_manage_posts', 'add_export_button' );
function add_export_button() {
$screen = get_current_screen();
if (isset($screen->parent_file) && ('edit.php' == $screen->parent_file)) {
?>
<input type="submit" name="export_all_posts" id="export_all_posts" class="button button-primary" value="Export All Posts">
<script type="text/javascript">
jQuery(function($) {
$('#export_all_posts').insertAfter('#post-query-submit');
});
</script>
<?php
}
}
add_action( 'init', 'func_export_all_posts' );
function func_export_all_posts() {
if(isset($_GET['export_all_posts'])) {
$arg = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
);
global $post;
$arr_post = get_posts($arg);
if ($arr_post) {
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="wp.csv"');
header('Pragma: no-cache');
header('Expires: 0');
$file = fopen('php://output', 'w');
fputcsv($file, array('Post Title', 'URL'));
foreach ($arr_post as $post) {
setup_postdata($post);
fputcsv($file, array(get_the_title(), get_the_permalink()));
}
exit();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment