Export data custom post type to excel wordpress WIP

# Adding button in backend
 add_action( 'restrict_manage_posts', 'add_export_button' );
 function add_export_button() {
     $screen = get_current_screen();

     if (isset($screen->parent_file) && ('edit.php?post_type=property' == $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
     }
 }

 # Adding export function for custom post,
 add_action( 'init', 'func_export_all_posts' );
 function func_export_all_posts() {
     if(isset($_GET['export_all_posts'])) {
         $arg = array(
                 'post_type' => 'property',
                 'post_status' => 'publish',
                 'posts_per_page' => 100,
             );

         global $post;
         $arr_post = get_posts($arg);
         if ($arr_post) {

             header('Content-type: application/vnd.ms-excel');
             header('Content-Disposition: attachment; filename="wp.xlsx"');
             header('Pragma: no-cache');
             header('Expires: 0');

             $file = fopen('php://output', 'w');

             fputcsv($file, array('post_id', 'post_title'));

             foreach ($arr_post as $post) {
                 setup_postdata($post);
                 fputcsv($file, array( get_the_id(), get_post_field( 'post_title', get_post() ) ));
             }

            //  exit();
         }
     }
 }

Leave a Reply

Your email address will not be published. Required fields are marked *