Skip to content

Instantly share code, notes, and snippets.

@Phoenix2k
Created June 22, 2017 16:04
Show Gist options
  • Save Phoenix2k/02abaa298d9173bcacbb06d4386f5a2b to your computer and use it in GitHub Desktop.
Save Phoenix2k/02abaa298d9173bcacbb06d4386f5a2b to your computer and use it in GitHub Desktop.
WordPress: Media files to CSV
<?php
global $post;
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => 'any', 'post_parent' => null );
$attachments = get_posts( $args );
$csv = "ID, Name, Title, Alt, Description, Caption, URL,\n";
if ( $attachments ) {
foreach ( $attachments as $post ) {
setup_postdata( $post );
$attachment = wp_prepare_attachment_for_js( get_the_ID() );
$csv .= '"' . str_replace( '"', '\"', $attachment[ 'id' ] ) . '"' . ",";
$csv .= '"' . str_replace( '"', '\"', $attachment[ 'name' ] ) . '"' . ",";
$csv .= '"' . str_replace( '"', '\"', $attachment[ 'title' ] ) . '"' . ",";
$csv .= '"' . str_replace( '"', '\"', $attachment[ 'alt' ] ) . '"' . ",";
$csv .= '"' . str_replace( '"', '\"', $attachment[ 'description' ] ) . '"' . ",";
$csv .= '"' . str_replace( '"', '\"', $attachment[ 'caption' ] ) . '"' . ",";
$csv .= '"' . str_replace( '"', '\"', get_site_url() . $attachment[ 'url' ] ) . '"' . "," . "\n";
}
wp_reset_postdata();
}
echo $csv;
wp_die();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment