List categories with images for post

So, you have extra custom fields for your categories and have set an image URL for each category. The next thing we need to do is create our get_categories_with_images function:

Here is the code. Paste this code in your functions.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 = '';
        }
        $cats[] =  $cat_image . '' .$cat->name .'';
    }
    return implode($separator , $cats);
}

This function will display the categories with images. For more details, click here.

Leave a Comment

Scroll to Top