Site icon Experience Wordpress Developer Online – Design Develop and Maintenance Support

List categories with images for post

So, you have Extra custom fields for your categories and you have set an image url for each category then next thing we have to do is create our get_categories_with_images function:

Here is the code , Paste this code in your function.php file of your active child theme (or theme).

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

It’s can display category with image.

Exit mobile version