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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.