เพิ่มปุ่ม Export

// Export เพิ่มปุ่ม Export

function admin_post_list_add_export_button( $which ) {

global $typenow;




if ( 'data'=== $typenow &&'top'=== $which ) {

?>

<inputtype="submit"name="export_all_posts"class="button button-primary"value="<?php _e('Export CSV'); ?>"/>

<?php

}

}




add_action( 'manage_posts_extra_tablenav', 'admin_post_list_add_export_button', 20, 1 );

function func_export_all_posts() {

if(isset($_GET['export_all_posts'])) {

$arg = array(

'post_type'=>'data',

'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="export-data.csv"');

header('Pragma: no-cache');

header('Expires: 0');




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




fputcsv($file, array('ชื่อ', 'นามสกุล', 'Username', 'Password', 'อีเมล์', 'โทร', 'เพศ', 'อายุ', 'การศึกษา', 'ตำแหน่ง', 'หน่วยงาน', 'จังหวัด', 'ประเทศ'));




foreach ($arr_post as $post) {

setup_postdata($post);




$categories = get_the_category();

$cats = array();

if (!empty($categories)) {

foreach ( $categories as $category ) {

$cats[] = $category->name;

}

}




$post_tags = get_the_tags();

$tags = array();

if (!empty($post_tags)) {

foreach ($post_tags as $tag) {

$tags[] = $tag->name;

}

}




fputcsv($file, array(get_field('name',$post->ID), get_field('lastname',$post->ID), get_field('username',$post->ID), get_field('password',$post->ID), get_field('E-mail',$post->ID), get_field('phone',$post->ID), get_field('sex',$post->ID), get_field('age',$post->ID), get_field('school',$post->ID), get_field('position',$post->ID), get_field('company',$post->ID), get_field('province',$post->ID), get_field('country',$post->ID)));

}




exit();

}

}

}




add_action( 'init', 'func_export_all_posts' );

Write A Comment