I think you can use a different approach: write a custom sql query that get the ids of the thumbnails attachment of the children pages, and if found call wp_get_attachment_image_src
on this ids to retrieve the urls:
function my_get_thumbnails( $post = NULL, $which="both" ) {
// first we get the post, if no post is passed we use global post
if ( empty( $post ) ) global $post;
if ( is_numeric($post) ) $post = get_post( $post );
if ( ! $post instanceof WP_Post ) return;
$children = FALSE;
$parent = FALSE;
// if we want children posts thumbnail...
if ( $which !== 'parent' ) {
// run a query to get attachment id set as thumbnail in children posts
global $wpdb;
$q = "SELECT {$wpdb->postmeta}.meta_value FROM {$wpdb->postmeta}
JOIN {$wpdb->posts} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id
WHERE {$wpdb->postmeta}.meta_key = '_thumbnail_id'
AND {$wpdb->posts}.post_parent = %d";
$thumb_ids = $wpdb->get_col( $wpdb->prepare( $q, $post->ID ) );
// if some results, call wp_get_attachment_image_src on all ids to get image urls
if ( ! empty( $thumb_ids ) ) {
$children = array_map( function($tid) {
$img = wp_get_attachment_image_src( $tid, 'large' ); // <-- SET SIZE HERE
return $img[0];
}, $thumb_ids );
}
}
// if we want parent post thumbnail...
if ( $which !== 'children' && $post->post_parent ) {
$tid = get_post_thumbnail_id( $post->post_parent );
if ( $tid ) {
// get the url of parent post thumbnail
$img = wp_get_attachment_image_src( $tid, 'large' ); // <-- SET SIZE HERE
$parent = $img[0];
}
}
// if we want only children posts thumbnail return them
if ( $which === 'children' ) return $children;
// if we want only parent post thumbnail return it
if ( $which === 'parent' ) return $parent;
// if we want bot return an array with both
return array( 'children' => $children, 'parent' => $parent );
}
After you have entered previous function in functions.php
, in your template (probably page.php
), use it like so:
<?php
global $post;
if ( is_page() ) {
$thumbnails = my_get_thumbnails();
if ( ! empty( $thumbnails['parent'] ) ) {
$format="<div class="parent-thumb"><img src="https://wordpress.stackexchange.com/questions/139667/%s" alt="" /></div>";
printf( $format, $thumbnails['parent'] );
}
if ( is_array( $thumbnails['children'] ) && ! empty( $thumbnails['children'] ) ) {
$open = '<div class="child-thumb"><img src="';
$close="" alt="" /></div>";
echo $open . implode( $close . $open, $thumbnails['children'] ) . $close;
}
}
?>
my_get_thumbnails
function can be used also to
- get the parent/children post thumbnails also for a post that is not the current, simply passing a post ID or a post object as first argument
- get only the parent post thumbnail passing ‘parent’ as second argument
- get only the children post thumbnails passing ‘children’ as second argument