2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WordPressの簡易CSVエクスポートメモ

Posted at

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');
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?