如何从一些选定的类别中获取第一张图像

时间:2013-11-17 作者:AgepRoem

下面是一个场景。我必须建立我的客户端,他想用拇指抓取一些类别显示在他的主页上。所以我的路线是,只需找到该类别的第一篇帖子并获取其缩略图,但我不知道如何做到这一点。我遵循了这个准则https://stackoverflow.com/questions/15607840/display-first-last-post-from-each-categories-in-wordpress, 但它将显示所有类别,我不知道如何只提取某些(选定的)类别。

因此,问题是:

我的路线正确吗?或者你可以建议我另一条路线或方法

$categories = get_categories(\'hide_empty=0&orderby=id\');
$include="";

foreach($categories as $category):
    $cat_field = \'rockable_cat_\' . $category->cat_ID;
    if( //some argument return true )   
    $include .= \'<div class="danboru"><a href="\'.get_category_link( $category->term_id ).\'" title="\' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . \'">\'.$category->cat_name.\'</a></div>\';
endforeach;

if($include)
$include = substr($include, 0, -1); //Remove the last comma
return $include;
已解决。。!!这是我的完整代码

从所选类别中获取类别名称

function rockable_build_cat_exclude(){

    $categories = get_categories(\'hide_empty=0&orderby=id\');
    $exclude="";

    foreach($categories as $cat):
    $cat_field = \'rockable_cat_\' . $cat->cat_ID;
    if( get_option($cat_field) and get_option($cat_field)==\'false\')
        $exclude .= "" . $cat->cat_name . ",";      
    endforeach;     

    if($exclude)
    $exclude = substr($exclude, 0, -1); //Remove the last comma


    return $exclude;
}
把它放在前面的代码(index.php)

<?php
$exclude = rockable_build_cat_exclude();
$exclude_array = explode(",",$exclude);

foreach ($exclude_array as $value){
    $cat_query = new WP_Query(array(\'category_name\'=>$value,\'showposts\'=>1));
    if ($cat_query->have_posts()):while($cat_query->have_posts()):$cat_query->the_post();

    $category_id = get_cat_ID( $value );?>
    <div class="danboru">
        <?php the_post_thumbnail(\'home-thumb\');?>
        <a href="<?php get_category_link( $category_id );?>" title="<?php echo esc_attr( sprintf( __( "View all posts in %s" ), $value ) ) ;?>"><?php echo $value;?></a>
    </div>

    <?php endwhile;
    endif;
}

?>
如果您有一些建议或更好的解决方案,请分享您的想法。

1 个回复
SO网友:s_ha_dum

我觉得你的解决方案太复杂了。WP_Query 可以完成几乎所有的工作,只需构建meta_query 查找缩略图。代码略为截断,但其大意如下:

$categories = array(1,2,3); // your specific category IDs
$first_thumb = new WP_Query(
  array(
    \'posts_per_page\' => count($categories),
    \'category__in\' => $categories,
    \'meta_query\' => array(
      array(
        \'meta_key\' => \'_thumbnail_id\',
        \'compare\' => \'EXISTS\'
      )
    ),
  )
);
if ($first_thumb->have_posts()) {
  while ($first_thumb->have_posts()) {
    $first_thumb->the_post();
    the_post_thumbnail();
  }
}

结束

相关推荐