如果没有设置特色图片,如何显示类别图片?

时间:2017-09-19 作者:Siyah

我可以为帖子做这个吗?

我有我正在获取的最新帖子,我正在显示这些帖子的缩略图(特色图片),如果它们存在的话。

What I want to do now, is to show category images IF the featured image does not exist.

有人能帮我吗?

目前我有一个:

    <?php 

    $args = array( \'numberposts\' => \'5\' );
    $recent_posts = wp_get_recent_posts($args);
    $category = get_the_category(); 
    foreach( $recent_posts as $recent ){
        if($recent[\'post_status\']=="publish"){
        if ( has_post_thumbnail($recent["ID"])) {
            echo \'<a href="\' . get_permalink($recent["ID"]) . \'" title="Look \'.esc_attr($recent["post_title"]).\'" >\' .   get_the_post_thumbnail($recent["ID"], \'thumbnail\').\'<div class="browse_category_name"> \' . $recent["post_title"]. \'<div> \' . get_the_author_meta(\'display_name\', $recent["post_author"]). \'</div></div></a></li> \';
        } else{
            echo \'<a href="\' . get_permalink($recent["ID"]) . \'" title="Look \'.esc_attr($recent["post_title"]).\'" >\' .  get_categories_with_images($post->ID,\' ,\') . $recent["post_title"].\'</a></li> \';
        }
         }
    }
    ?>
这是我的functions.php:

function get_categories_with_images($post_id,$separator ){

    //first get all categories of that post
    $post_categories = wp_get_post_categories( $post_id );
    $cats = array();

    foreach($post_categories as $c){
        $cat = get_category( $c );
        $cat_data = get_option("category_$c");

        //and then i just display my category image if it exists
        $cat_image = \'\';
        if (isset($cat_data[\'img\'])){
            $cat_image = \'<img src="\'.$cat_data[\'img\'].\'">\';
        }
        $cats[] =  $cat_image . \'<a href="\'.get_category_link( $c ) . \'">\' .$cat->name .\'</a>\';
    }
    return implode($separator , $cats);
}
问题:即使未设置缩略图/特征图像,也不会显示类别图像。

2 个回复
SO网友:Jacob Peattie

你有一个拼写错误。在你的循环中,你正在检查has_post_thumbnail($recent["ID"]), 但是$recent[\'ID\'] 不会设置,因为foreach$decent:

foreach( $recent as $decent ){

SO网友:Annapurna

将代码更改为:

<?php 

$args = array( \'numberposts\' => \'5\' );
$recent = wp_get_recent_posts($args);
$category = get_the_category(); 
foreach( $recent as $decent ){
    if($decent[\'post_status\']=="publish"){
    if ( has_post_thumbnail($decent["ID"])) {
        echo \'<a href="\' . get_permalink($decent["ID"]) . \'" title="Look \'.esc_attr($decent["post_title"]).\'" >\' .   get_the_post_thumbnail($decent["ID"], \'thumbnail\').\'<div class="browse_category_name"> \' . $decent["post_title"]. \'<div> \' . get_the_author_meta(\'display_name\', $decent["post_author"]). \'</div></div></a></li> \';
    } else{
        echo \'<a href="\' . get_permalink($decent["ID"]) . \'" title="Look \'.esc_attr($decent["post_title"]).\'" >\' .  get_categories_with_images($post->ID,\' ,\') . $decent["post_title"].\'</a></li> \';
    }
     }
}
?>
这篇文章现在是$DELANCE,而不是$NEXT

结束