I use this to query all attachments of the current page or post I’m on â¦
$query_images_args = array(
'post_type' => 'attachment',
'post_mime_type' =>'image',
'post_status' => 'inherit',
'posts_per_page' => -1,
'post_parent' => $post->ID //$post->post_parent
);
$attachments = get_children($query_images_args);
if ( empty($attachments) ) {
$query_images_args = array(
'post_type' => 'attachment',
'post_mime_type' =>'image',
'post_status' => 'inherit',
'posts_per_page' => -1,
'post_parent' => $post->post_parent
);
}
$query_images = new WP_Query( $query_images_args );
$images = array();
foreach ( $query_images->posts as $image) {
$images[] = wp_get_attachment_image_src( $image->ID, 'large');
}
foreach ( $images as $image) {
if ( $image[1] >= 1024 )
$large_images[] = $image[0];
}
if ( !empty($large_images) ):
This works perfectly and queries only the images of the current post or page.
However I have one additional thing I want this piece of code to do:
If a page has no images attached and is a “child-page” of a page that has images attached I want to query the images of the “parent-page”.
Again:
parent-page -> has images attached
child-page -> has no images attached -> should query images of the parent-page
This could be done with $post->post_parent
$query_images_args = array(
'post_type' => 'attachment',
'post_mime_type' =>'image',
'post_status' => 'inherit',
'posts_per_page' => -1,
'post_parent' => $post->post_parent
);
However I have no idea how to differentiate between those two cases.
If a page has images attached I want my code to be 'post_parent' => $post->ID
, if a page is a child-page and has NO images attached I want the code to be 'post_parent' => $post->post_parent
Any ideas on that?
You can use
get_children
to check if it returns anything, then if it doesn’t, fetch the parent attachments.