【WordPress】管理画面の一覧テーブルにCSVダウンロードボタンを追加する方法

【WordPress】管理画面の一覧テーブルにCSVダウンロードボタンを追加する方法 WordPress

WordPressで投稿やカスタム投稿の一覧をCSV形式で出力したいという要望は、管理業務やデータ分析の現場でよくあります。この記事では、管理画面の一覧テーブルにCSVダウンロードボタンを追加し、一覧に表示されているデータをそのままCSVとして出力する方法を紹介します。

CSV出力用のカスタムアクションを追加する

まず、管理画面でCSVダウンロードリクエストを検知し、データを出力する処理をfunctions.phpに記述します。


function export_custom_post_csv() {
  if (!is_admin() || !current_user_can('manage_options')) return;
  if (!isset($_GET['export_csv']) || $_GET['export_csv'] !== 'true') return;

  $post_type = isset($_GET['post_type']) ? sanitize_key($_GET['post_type']) : 'post';

  header('Content-Type: text/csv; charset=UTF-8');
  header('Content-Disposition: attachment; filename="' . $post_type . '-list.csv"');
  $output = fopen('php://output', 'w');

  $args = array(
    'post_type'      => $post_type,
    'post_status'    => 'publish',
    'posts_per_page' => -1,
  );
  $query = new WP_Query($args);

  fputcsv($output, array('ID', 'タイトル', '公開日'));

  if ($query->have_posts()) {
    while ($query->have_posts()) {
      $query->the_post();
      fputcsv($output, array(get_the_ID(), get_the_title(), get_the_date('Y-m-d')));
    }
  }

  fclose($output);
  exit;
}
add_action('admin_init', 'export_custom_post_csv');

投稿一覧画面にCSVボタンを追加する

次に、管理画面の投稿一覧テーブルの上にCSVダウンロード用のボタンを追加します。


function add_csv_export_button() {
  $screen = get_current_screen();
  if ($screen->base === 'edit' && post_type_exists($screen->post_type)) {
    $url = add_query_arg(array(
      'export_csv' => 'true',
      'post_type'  => $screen->post_type
    ), admin_url('edit.php'));

    echo '<div class="wrap"><a href="' . esc_url($url) . '" class="button button-primary">CSVダウンロード</a></div>';
  }
}
add_action('manage_posts_extra_tablenav', 'add_csv_export_button');

manage_posts_extra_tablenavフックを使うことで、投稿一覧の上部または下部に任意のHTMLを出力できます。

出力されるCSVの内容をカスタマイズする

タイトルや公開日だけでなく、カスタムフィールドや投稿者名、タクソノミーなどを出力したい場合は、fputcsvの中身を自由に拡張可能です。


$author = get_the_author();
$custom_value = get_post_meta(get_the_ID(), 'your_custom_field', true);
fputcsv($output, array(get_the_ID(), get_the_title(), $author, $custom_value));

まとめ

WordPressの管理画面にCSVダウンロード機能を組み込むことで、投稿データのバックアップや分析、帳票出力などの運用が効率化できます。プラグインに頼らず独自に実装することで、必要な項目だけを柔軟に出力できる点が大きなメリットです。