# Export Selected Posts to CSV

> Adds an "Export to CSV" bulk action to the Posts and Pages screens that downloads the selected items with ID, title, status, author, dates, categories, link and word count.

- Type: PHP
- Runs: Admin only
- Category: [Admin](https://wpide.com/library/category/admin/)
- Tags: bulk-actions, export, csv
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/admin-bulk-export-csv/

## Code

```php
foreach ( array( 'post', 'page' ) as $wpide_type ) {
    add_filter( "bulk_actions-edit-{$wpide_type}", function ( $actions ) {
        $actions['wpide_export_csv'] = 'Export to CSV';
        return $actions;
    } );

    add_filter( "handle_bulk_actions-edit-{$wpide_type}", function ( $redirect, $action, $post_ids ) {
        if ( 'wpide_export_csv' !== $action || ! current_user_can( 'edit_posts' ) ) {
            return $redirect;
        }

        $rows = array( array( 'ID', 'Title', 'Status', 'Author', 'Published', 'Modified', 'Categories', 'URL', 'Words' ) );
        foreach ( $post_ids as $post_id ) {
            $post = get_post( $post_id );
            if ( ! $post || ! current_user_can( 'read_post', $post_id ) ) {
                continue;
            }
            $rows[] = array(
                $post->ID,
                $post->post_title,
                $post->post_status,
                get_the_author_meta( 'display_name', $post->post_author ),
                $post->post_date,
                $post->post_modified,
                implode( ', ', wp_list_pluck( (array) get_the_category( $post->ID ), 'name' ) ),
                get_permalink( $post ),
                str_word_count( wp_strip_all_tags( $post->post_content ) ),
            );
        }

        if ( defined( 'WP_CLI' ) && WP_CLI ) {
            return $redirect; // Nothing to download from the command line.
        }

        nocache_headers();
        header( 'Content-Type: text/csv; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename=posts-' . gmdate( 'Y-m-d' ) . '.csv' );
        $out = fopen( 'php://output', 'w' );
        fwrite( $out, "\xEF\xBB\xBF" ); // UTF-8 BOM for Excel.
        foreach ( $rows as $row ) {
            // Prevent spreadsheet formula injection.
            fputcsv( $out, array_map( function ( $cell ) {
                return is_string( $cell ) && preg_match( '/^[=+\-@]/', $cell ) ? "'" . $cell : $cell;
            }, $row ) );
        }
        fclose( $out );
        exit;
    }, 10, 3 );
}
```

## Notes

Opens directly in Excel or Google Sheets; add columns in the $row array.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Export Selected Posts to CSV" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
