WordPressの簡易CSVエクスポート。拡張フィールド対応。
functions.php
/**
* 何もしない
*/
function my_dummy() {
}
/**
* サブメニュー登録(Export CSV)
*/
function my_register_custom_submenu_page() {
// tools.php は不要。
add_submenu_page( 'tools.php', 'Export CSV', 'Export CSV', 'manage_options', 'my-export-csv','my_dummy');
}
add_action('admin_menu', 'my_register_custom_submenu_page');
/**
* CSVエクスポート
*/
function my_export_csv() {
// ID, タイトルと拡張フィールド
$fields = array('ID','post_title','zip','pref','city','tel');
$fp = fopen('php://temp','r+');
$q = new WP_Query(array(
'nopaging'=>1,
'orderby'=>'ID',
'order'=>'ASC',
));
fputcsv($fp, $fields, ',', '"');
if ($q->have_posts()) :
while($q->have_posts()) : $q->the_post();
$data = array();
foreach ($fields as $fld) :
switch($fld) :
case 'ID' : $data[] = get_the_ID();break;
case 'post_title':$data[] = get_the_title(); break;
default :
// 拡張フィールド
$v = get_field($fld);
if (is_array($v)) :
$data[] = join($v,',');
else :
$data[] = $v;
endif ;
endswitch;
endforeach;
fputcsv($fp, $data, ',', '"');
endwhile;
endif;
wp_reset_postdata();
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=export.csv');
rewind($fp);
while (($buf = fgets($fp)) !== false) :
echo mb_convert_encoding($buf,'SJIS-win',mb_internal_encoding());
endwhile;
fclose($fp);
}
/**
* アドミン初期時
* page=my-export-csvがあれば、EXPORT処理
*/
function my_admin_init(){
$page = isset($_GET['page']) ? $_GET['page'] : '';
if ($page === 'my-export-csv') :
my_export_csv();
exit();
endif;
}
add_action('admin_init', 'my_admin_init');