Search code examples
wordpressadvanced-custom-fieldstaxonomywp-list-categories

List WP Categories with Custom field Values


I added a Field Group using ACF plugin to the default WP Category Add/Edit screen so that I can add additional values to categories such as category icon/background image, checkbox to displayed on home or not and assign it as one of the popular categories.

enter image description here

I'm trying to list all the categories on the homepage based on popularity checkbox along with their icon and background image.

I have two image fields such as category_icon for storing category icon and category_bg_image for storing category background image.

Below is the code where I'm able to list the Categories however the custom field values of icon and background image isn't showing.

 if (have_posts() ) :
  while (have_posts() ) : the_post(); 

$args=array( 

'hide_empty' => '0',
'meta_key' => 'popular_services_category'
 );

  $categories=get_categories($args);

   foreach($categories as $category) {
  echo '<li>'  . $category->name . '</li>';

      global $post;
      $terms = get_the_terms($post->ID, 'category');
      
      if( !empty($terms) )
      {
      $term = array_pop($terms);
      $custom_field = get_field('category_icon', 'category_' . $term->term_id );
     
      echo '<li>'  . $custom_field['url'] . '</li>';
     
   }      
   }
   endwhile;

Solution

  • I was able to solve the issue with little modification and I am posting it here for others to be helpful.

      if (have_posts() ) :
      while (have_posts() ) : the_post();
    
          $args=array( 
            'hide_empty' => '0',
            'meta_key' => 'popular_services_category'
                     );
    
              $categories=get_categories($args);
    
          foreach($categories as $category) 
             {
                 echo '<li>'  . $category->name . '</li>';
    
                 $image = get_field('category_icon', $category->taxonomy . '_' . 
                 $category->term_id );
                 $image_bg = get_field('category_bg_image', $category->taxonomy . '_' . $category->term_id );
    
                 // Check if the image exists
                 if ( $image ) : ?>
                    <img src="<?php echo $image['url']; ?>" />
                    <img src="<?php echo $image_bg['url']; ?>" />
                 endif; 
              }
       endwhile;