从自定义分类法中的自定义帖子类型的帖子中提取第一个特色图像



我试图创建一个"类别"页面,其中显示了我所有的类别以及该类别的图像。而不是这个页面是静态的,我想拉出最近的帖子特色图片为该类别,并使用它作为类别图像。

我下面的代码有点工作,它拉出最近的特色图像,但它似乎不是特定于类别的(它只是拉出最近的。

只是为了澄清我使用的是自定义帖子类型和自定义分类法:

文章类型:图库分类:分类

<?php
$limit      = 999;
$counter    = 0;
$cats = get_terms([
'taxonomy' => 'categories',
'hide_empty' => false,
]);
foreach ($cats as $cat):
if ($counter < $limit) {
$args  = array(
'posts_per_page' => 1,
'post_type'   => 'gallery',
'taxonomy' => 'categories',
'cat' => $cat->cat_ID,
'ignore_sticky_posts' => 1
);
$posts = get_posts($args);
if ($posts) {
echo '<div class="col-md-3 category-list">';
while( have_posts() ) : the_post();
echo '<a href="' . get_category_link($cat->term_id) . '" ' . '><div class="cat-list-img">';
the_post_thumbnail();
echo '<h5 class="cl-title">' . $cat->name . '</h5>';
echo '</div></a>';
echo '</div>';
endwhile;
}
}
$counter++;
endforeach;
?>

由于一些帖子共享相同的类别,如果我能避免每个帖子使用相同的帖子,而是从下一个帖子中获取图像(而不是复制),那将是伟大的,但我不确定如何做到这一点,所以甚至没有尝试-如果它比听起来更容易,如果你也能指出我正确的方向,那将是伟大的。

如果没有帖子类型或分类法,就很难测试这是否有效。但是,这应该可以工作。

正如评论中所述,您需要使用get_the_ID(),我也认为您需要get_term_link函数而不是get_category_link,因为这将用于post分类法category是默认的WordPress类别分类法。

$limit   = 999;
$counter = 0;
$cats    = get_terms(
array(
'taxonomy'   => 'categories',
'hide_empty' => false,
)
);
foreach ( $cats as $cat ) :
if ( $counter < $limit ) {
$args    = array(
'posts_per_page'      => 1,
'post_type'           => 'gallery',
'ignore_sticky_posts' => 1,
'tax_query'           => array(
array(
'taxonomy' => 'categories',
'terms'    => $cat->term_id,
'field'    => 'term_id',
),
),
);
$results = new WP_Query( $args );
if ( $results->have_posts() ) {
echo '<div class="col-md-3 category-list">';
foreach ( $results->get_posts() as $the_post ) :
echo '<a href="' . esc_url( get_term_link( $cat->term_id, 'categories' ) ) . '"><div class="cat-list-img">';
$image = get_the_post_thumbnail( $the_post->ID, 'medium' ); // replace with whatever size you want here.
echo $image;
echo '<h5 class="cl-title">' . esc_attr( $cat->name ) . '</h5>';
echo '</div></a>';
echo '</div>';
endforeach;
}
}
$counter++;
endforeach;

为了避免重复,您可以将显示的post ID存储在一个数组中,如果在其他类别查询中再次出现,则忽略它。

$limit      = 999;
$counter    = 0;
$cats = get_terms([
'taxonomy' => 'categories',
'hide_empty' => false,
]);
$displayed_posts = array(); 
foreach ($cats as $cat):
if ($counter < $limit) {
$args  = array(
'posts_per_page' => 1,
'post_type'   => 'gallery',
'taxonomy' => 'categories',
'cat' => $cat->cat_ID,
'ignore_sticky_posts' => 1
);
$posts = get_posts($args);
if ($posts) {
echo '<div class="col-md-3 category-list">';
while( have_posts() ) :
the_post();
$post_id = get_the_ID();
if ( in_array( $post_id, $displayed_posts ) ) {
continue;
}
$displayed_posts[] = $post_id;
echo '<a href="' . get_category_link($cat->term_id) . '" ' . '><div class="cat-list-img">';
the_post_thumbnail();
echo '<h5 class="cl-title">' . $cat->name . '</h5>';
echo '</div></a>';
echo '</div>';
endwhile;
}
}
$counter++;
endforeach;

最新更新