我认为您可以使用另一种方法:编写一个自定义sql查询,获取子页面缩略图附件的ID,如果找到,则调用wp_get_attachment_image_src
在此ID上检索URL:
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 );
}
在中输入上一个函数后
functions.php
, 在模板中(可能是
page.php
), 这样使用:
<?php
global $post;
if ( is_page() ) {
$thumbnails = my_get_thumbnails();
if ( ! empty( $thumbnails[\'parent\'] ) ) {
$format = \'<div class="parent-thumb"><img src="%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
函数也可用于
获取非当前帖子的父/子帖子缩略图,只需将帖子ID或帖子对象作为第一个参数传递