Search code examples
wordpressimagepluginscategories

Category images are not displaying in WordPress


I have categories list with there respective images. I am able to get the category name and description but I am not getting the category image. I tried the below code.

<ul>
  <?php
    $categories = get_categories( array(
        'taxonomy'   => 'category',
        'orderby'    => 'name',
        'parent'     => 0,
        'hide_empty' => 0, 
    ) );
    
        foreach ( $categories as $category ) 
        {
        $cat_ID        = $category->term_id;
        $category_name = $category->name;
        $category_desc = $category->description;
        //$category_img = $category->category_images;
        $category_images = get_option('category_images');?>

       <li>
       <?php
       echo $category_name;
       echo $category_desc;
       echo $category_images; //display the path of image for temporary
          ?>         
      </li>
      <?php } ?>
    </ul>

I tried below code as well

 $category_image = '';
  if ( is_array( $category_images ) && array_key_exists( get_query_var('cat'), $category_images ) ){
  $category_image = $category_images[get_query_var('cat') 
}

I am getting the image but only getting first image.

var_dump($category)

enter image description here


Solution

  • As per the comments in the question, you store the images in the option table, as an array indexed by the term id.

    Meaning that if you want to fetch that array entry/image, you need to call it like this

    <?php echo $category_images[$cat_ID];?>

    If you have stored is as an array, with alt texts, src, name etc. you can access that array like this

    <?php echo $category_images[$cat_ID]['exampleIndexAltText'];?>

    You were jut lacking the last logical part of, how to retrieve what you have stored.