Filter Protected Files using WP_Query Function

You can filter your private files protected by Prevent Direct Access Gold and display their protected URL using WordPress WP_Query function.

Here’s an example:

// Get protected files
$args = array(
   'post_type' => 'attachment',
   'meta_query' => array(
       array(
          'key' => '_pda_protection',
          'value' => '1'
      )
  )
);
$query = new WP_Query( $args );

// Get an array of protected attachments using $query->posts
$attachments = get_attachment_urls( $query->posts );

// Refer to the screenshot below for the returned array
print_r($attachments);

// e.g. display the first attachment title & URL
echo $attachments[0]->post_title . $attachments[0]->url;

// Get the protected file URL and update the results
function get_attachment_urls( $query_result ) {
	return array_map( function ( $attachment ) {
		$attachment->url = wp_get_attachment_url( $attachment->ID );
		return $attachment;
	}, $query_result );
}

Here’s what you’ll get from the $attachments variable

Lasted updated on October 15, 2019