dan_2300
dan_2300

Reputation: 1

ACF get image from product term

I would like to display a brand logo on my product pages. I use Advanced Custom Fields (ACF) to insert the image on the taxonomy "Brand".

https://snipboard.io/JcYvM4.jpg

I have tried the code below, and tried to do as on the page here, but it doens't work...

https://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/

*The image return format is "Array".

function action_woocommerce_before_variations_form(  ) { 

    $queried_object = get_queried_object(); 
    $taxonomy = $queried_object->taxonomy;
    $term_id = $queried_object->term_id;  
    
    $image = get_field('brand_logo', $taxonomy . '_' . $term_id);
    echo '<img src="'.$image['url'].'" />';
    
}; 
         
// add the action 
add_action( 'woocommerce_before_variations_form', 'action_woocommerce_before_variations_form', 10, 0 ); 

Upvotes: 0

Views: 488

Answers (2)

ZecKa
ZecKa

Reputation: 2934

The woocommerce_before_variations_form is call on product page.

So if when you call get_queried_object() WordPress will return Product Object, not brand term.

So

  1. Get brand(s) with your product id with get_the_terms function
  2. Iterate on your brands and get image with get_field function
  3. (optional) get brand link
  4. Display your image
<?php 

function prefix_add_brand_before_variations_form() {
    // First get brand(s) with your product id. 
    $brands = get_the_terms(get_the_id(), 'brand');
    
    // get_the_terms return false or an array, so 
    if(!$brands) {
        return;
    }
    foreach ($brands as $brand) {
        $image = get_field('brand_logo', $brand);
        $brand_url = get_term_link($brand);
        if (is_array($image)) : ?>
            <a href="<?php echo $brand_url ?>">
                <img src="<?php echo $image['url']; ?>" />
            </a>
        <?php
        endif;
    }
}

add_action('woocommerce_before_variations_form', 'prefix_add_brand_before_variations_form', 10, 0); 

Upvotes: 0

ZealousWeb
ZealousWeb

Reputation: 1751

You can try like this:

<?php
$category_icon = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$category-logo = wp_get_attachment_url( $category_icon );
?> 

Upvotes: 0

Related Questions