没有真正有效的方法来做到这一点。您要么进行3次查询,要么创建自己的SQL查询并使用global $wpdb;
. 为了简单起见,我使用了3查询方法。
如果我们知道slug或id,我们可以将它们传递给税务查询。因为示例代码没有显示我们需要运行get_terms()
首先获得可能的艺术家:
$artists=获取术语(数组(\'taxonomy\'=>\'Artister\',\'hide\\u empty\'=>false,);
我们可以使用get_posts()
要获取特定艺术家的一系列帖子,请执行以下操作:
$art1_posts = get_posts( array(
\'posts_per_page\' => 1, // Only return 1 post
\'orderby\' => array( // Order by Date
\'post_date\' => DESC
),
\'tax_query\' => array( array( // Get first artist posts - inefficient
\'taxonomy\' => \'artists\',
\'field\' => \'term_id\',
\'terms\' => $artists[0]->term_id
) ),
\'meta_key\' => \'_thumbnail_id\', // Only return posts that have a post thumbnail
) );
以上只是一个示例,因为它使用
$artists[0]
. 相反,我们希望遍历可用的艺术家,并将结果存储在单独的数组中。最终结果可能如下所示:
$featured_image_arr = array();
$artists = get_terms( array(
\'taxonomy\' => \'artist\',
\'hide_empty\' => false,
) );
// If we have artists, loop through them, get the latest post, add to our featured image arr
if( ! empty( $artists ) ) {
foreach( $artists as $artist ) {
$artist_posts = get_posts( array(
\'posts_per_page\' => 1,
\'orderby\' => array(
\'post_date\' => DESC
),
\'tax_query\' => array( array(
\'taxonomy\' => \'artists\',
\'field\' => \'term_id\',
\'terms\' => $artist->term_id
) ),
\'meta_key\' => \'_thumbnail_id\',
) );
// Skip empty artists.
if( empty( $artist_posts ) ) {
continue;
}
$featured_image_arr[] = array(
\'artist\' => $artist,
\'artist_post\' => $artist_posts[0],
\'thumbnail_id\'=> get_post_meta( $artist_posts[0]->ID, \'_thumbnail_id\', true ),
\'thumbnail_url\'=> wp_get_attachment_image_url( $thumbnail_id, \'full\' ),
);
}
}
// If we have featured images, show them.
if( ! empty( $featured_image_arr ) ) {
foreach( $featured_image_arr as $arr ) {
printf( \'<div class="artistbox" style="background-image: url( %1$s )"><a href="/artists/%2$s">%3$s</a></div>\',
$arr[\'thumbnail_url\'],
$arr[\'artist\']->slug,
$arr[\'artist\']->name
);
}
}