WordPress: get all the post attachments from the database

WordPress: get all the post attachments from the database

How to get all the post attachments of a WordPress site by running a simple query on the database.

Imagine that you want to create a remote resource grabber that fetches all your attachments stored on a WordPress site. You don't want to use Loop functions, because you simply need a function that returns an array of URLs. You also want all the attachments of your site returned by this function. Let's see how to accomplish this task.

The simplest and quickest way is to run a direct query to the WordPress database:

function get_all_attachments() {

	global $wpdb;
	
	$results = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file'");
	$attachments = array();
	$i = 0;
	$upload_dir = wp_upload_dir();
	$uploads_url = $upload_dir['baseurl'] . '/';
	
	foreach($results as $result) {
	
		$attachment_url = $uploads_url . $result->meta_value;
		$attachments[$i++] = $attachment_url;
	
	
	}
	
	return $attachments;

}

The above function returns an indexed array containing the absolute URLs to your attachments. If you want to be a little more selective, you can use PHP string matching to select only particular file types (such as PDF or videos).