attachments icon indicating copy to clipboard operation
attachments copied to clipboard

Retrieve Attachments Outside The Loop doesn't work

Open im4aLL opened this issue 6 years ago • 0 comments

For custom post type - retrieving attachments don't work

$query = new WP_Query([
	'post_type'        => 'news',
	'posts_per_page'   => 5,
]);

echo '<pre>';
print_r($query->posts);
echo '</pre>';

wp_reset_query();

$attachments = new Attachments( 'attachments', 13 ); // post ID 13 has 4 attachments
echo $attachments->exist() ? 'yes' : 'no'; // result is - no. Thought it has data!

Temporary fix

  • Use get_post_meta to retrive post meta where meta key is attachments example - get_post_meta( $post_id, 'attachments', true ) then json decode
  • You will receive an array by your registered attachment eg. my_attachments
  • Then loop through result and use wp_get_attachment_url to get URL.

im4aLL avatar Dec 26 '19 07:12 im4aLL