Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Gallery of Featured Images for sibling pages WordPress

  • SOLVED

I have a simple <strong>image.php</strong> file that shows a featured image:

<?php $image = wp_get_attachment_image_src( $attachment->ID, 'hero' ); ?>
<img src="<?php echo $image[0]; ?>">

Given this information, how do I get the ID number of the page that my (featured) image is attached to? I would then like to pass this page ID to a new query and build a thumbnail gallery of featured images from all pages that have the same parent. My attempted code for this new gallery query is shown below:

<?php
$args = array('post_type'=>'page', 'post_parent'=>$post->post_parent, 'post__not_in'=>array($post->ID), 'posts_per_page' => -1, 'meta_key' => '_thumbnail_id', 'orderby'=>'menu_order', 'order'=>ASC);
$loop = new WP_Query($args);
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();
if (has_post_thumbnail( $post->ID ) ) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' );
echo '<a href="'.get_attachment_link(get_post_thumbnail_id($post->ID), 'hero').'"><img src="'.$image[0].'"></a>';
}
endwhile;
endif;
wp_reset_query();
?>

Please can someone revisit my <strong>image.php</strong> code and tweak to give the desired result.

Many thanks

Answers (1)

2012-10-11

Christianto answers:

Hi

You can get the value of the post id ( which is the parent of the attachment id) by using this function on your functions.php:

function findPostID($attachID){
global $wpdb;
$postid = $wpdb->get_col($wpdb->prepare("SELECT post_parent FROM $wpdb->posts WHERE ID = $attachID"));
return $postid[0];
}


if the image was uploaded from the editor of featured post..

so in your image.php

<?php
global $featuredPost_ID;
$featuredPost_ID = findPostID($attachment->ID);
$image = wp_get_attachment_image_src( $attachment->ID, 'hero' );
?>
<img src="<?php echo $image[0]; ?>">


so you can pass the id from $featuredPost_ID to your loop,
depend on how your image.php included to the page you might want to add
global $featuredPost_ID;
before the loop..


designbuildtest comments:

Thanks Christianto, I've just ended up solving this myself I think by adding the following to the top of my page:

<?php
$pageid = $post->post_parent;
$parentid = get_post($pageid);
$parentid = $parentid->post_parent; ?>

and changing my query argument to:

$args = array('post_type'=>'page', 'post_parent'=>$parentid, 'post__not_in'=>array($pageid), 'posts_per_page' => -1, 'meta_key' => '_thumbnail_id', 'orderby'=>'menu_order', 'order'=>ASC);

Thanks for your help