WordPress の 記事 を CSV で ダウンロード する
この記事は 2016年 2月 16日 に書かれた記事です。
この記事は WordPress Version 4.4.2 の時の記事です。
WordPress の 記事 を CSV で ダウンロード したいと 依頼がありまして 作成してみました
今回は テンポラリファイル を 作成しない オンメモリ の ダウンロードになりますので
膨大な 記事があるサイトでは コチラは 使わないでください
多分 メモリが枯渇して 落ちてしまうことがあるかと思います
// wp-load.php が 有るところまで ディレクトリ移動して 読み込みます
require_once( __DIR__ . '/../wp-load.php' );
// content_array に 投稿データを 配列で 用意します
$content_array = array();
$content_array[] = array(
'title',
'content',
);
$the_query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => -1,
) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ) :
$the_query->the_post();
$post_data = array();
$post_data[] = get_the_title();
$post_data[] = get_the_content();
$content_array[] = $post_data;
endwhile;
endif;
wp_reset_postdata();
// post.csv で ダウンロード させます
ob_start();
$file_name = 'post.csv';
$stream = fopen( 'php://output', 'w' );
foreach( $content_array as $fields ) {
fputcsv( $stream, $fields );
}
header( 'Content-Type: application/octet-stream' );
header( "Content-Disposition: attachment; filename=$file_name" );
echo mb_convert_encoding( ob_get_clean(), 'SJIS-win', 'UTF-8' );
こんな感じで 作成しました
I referred to Qiita | mikakane.
http://qiita.com/mikakane/items/0571de92afe4653f78d6
結構 雑に作ってしまったので
ココ 危険だよ!! とか ココ もっと スマートに出来るよ!! とか
ありましたら コメントください!!