【问题标题】:How to show category image if no featured image is set in Wordpress?如果在 Wordpress 中没有设置特色图像,如何显示类别图像?
【发布时间】:2017-09-19 09:42:44
【问题描述】:

我可以为帖子这样做吗?

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

我现在要做的是,如果特色图片不存在,则显示类别图片。

有人可以帮我解决这个问题吗?

我现在有这个:

    <?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);
}

问题:未显示类别图像,即使未设置缩略图/特色图像。

【问题讨论】:

    标签: php wordpress function posts


    【解决方案1】:

    在您的函数中,您传递了错误的变量 - 没有 $post。只需将其更改为 $recent["ID"],就像您之前所做的那样。

    【讨论】:

    • 谢谢,但它不起作用。它只获取类别名称,但不获取图像……所以,这个:get_categories_with_images($recent["ID"],' ,') 不起作用。
    猜你喜欢
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2012-01-30
    • 2013-02-26
    • 2023-04-01
    • 2013-04-21
    相关资源
    最近更新 更多