perqedelius
perqedelius

Reputation: 105

ACF get_field not returning value inside function with foreach loop

I have a function that loops all Woocommerce subcategories for the current category. Inside the subcategory loop there is an advanced-custom-field that is supposed to display an icon. But I do something wrong so it doesn't show up. What am I doing wrong?

This is the function.

function pab_display_subcategories() {
    if ( is_product_category() ) {

        $term_id  = get_queried_object_id();
        $taxonomy = 'product_cat';

        // Get subcategories of the current category
        $terms    = get_terms([
            'taxonomy'    => $taxonomy,
            'hide_empty'  => false,
            'parent'      => get_queried_object_id()
        ]);

        $output = '
        <div class="bde-wooproductslist breakdance-woocommerce">
            <div class="woocommerce">
                <ul class="products">';
        
                    // Loop through product subcategories WP_Term Objects
                    foreach ( $terms as $term ) {
                        $term_link = get_term_link( $term, $taxonomy );
                        
                        $output .= '<li class="product-category product pab-cat-list"><a href="'. $term_link .'">';
                        
                        $cat_icon = get_field( 'cat_icon', $term->term_id );
                        if ( $cat_icon ) :
                            $output .= '<div class=""><img src="'. esc_url( $cat_icon['url'] ). '" alt="'. esc_attr( $cat_icon['alt'] ) .'" class="pab-wc-category-icon"></div>';
                        endif;

                        $output .= '<div class="pab-cat-list-text">'. $term->name .' '. $term->term_id .'<i class="fa-solid fa-chevron-right"></i></div>
                        </a></li>';
                    }

                echo $output . '
                </ul>
            </div>
        </div>';
    }
}
add_shortcode( 'pab_display_subcategories_content','pab_display_subcategories' );

Upvotes: 0

Views: 32

Answers (1)

Akshay Kumar
Akshay Kumar

Reputation: 55

Try this , hope it will work.

get_field( 'cat_icon', 'term_' . $term->term_id );

Upvotes: 0

Related Questions