Last active
August 29, 2015 14:27
-
-
Save Ritesh-patel/b8cbb7529c9a793051cc to your computer and use it in GitHub Desktop.
Code snippet to get all attached media in WordPress and store the file paths into a text file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Put this script along with wp-load.php only | |
$curr_dir = getcwd(); | |
include_once( $curr_dir . '/wp-load.php' ); | |
if( defined( 'ABSPATH' ) ){ | |
remove_all_filters( 'wp_get_attachment_url' ); | |
remove_all_filters( 'get_attached_file' ); | |
$args = array( | |
'post_type' => 'attachment', | |
'posts_per_page' => -1, | |
'post_status' => 'any', | |
); | |
$posts_query = new WP_Query( $args ); | |
$posts = $posts_query->posts; | |
$file_paths = array(); | |
$file_ids = array(); | |
foreach( $posts as $post ){ | |
$attached_file = get_attached_file( $post->ID ); | |
$file_paths[] = $attached_file; | |
$meta_data = wp_get_attachment_metadata( $post->ID ); | |
$file_name = basename( $attached_file ); | |
$mime_type = $post->post_mime_type; | |
$mime = explode( '/', $mime_type ); | |
if( $mime[ 0 ] == 'image' ) { | |
if( $meta_data[ 'sizes' ] ) { | |
foreach( $meta_data[ 'sizes' ] as $media_size ) { | |
$file_paths[] = str_replace( $file_name, $media_size['file'], $attached_file ); | |
} | |
} | |
} | |
$file_ids[] = $post->ID; | |
} | |
sort( $file_paths ); | |
$file_content = ''; | |
$fp = fopen( $curr_dir . "/file-paths.txt","wb"); | |
foreach( $file_paths as $file_path ){ | |
$file_content .= $file_path . PHP_EOL; | |
} | |
echo $file_content; | |
fwrite( $fp,$file_content ); | |
fclose( $fp ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment