Eneses
Eneses

Reputation: 11

Display ACF field/image below the product title in WooCommerce archive pages

I'm using Advanced Custom Fields Plugin and I could just display the text field below the product title on the Archive page but I also need to display image as a logo on the same location (under the text field).

This is the code I'm using for the display the text field and it works:

add_action( 'woocommerce_after_shop_loop_item_title', 'custom_field_display_below_title', 2 );
function custom_field_display_below_title(){
    global $product;

    // Get the custom field value
    $custom_field = get_post_meta( $product->get_id(), 'oa1', true );

    // Display
    if( ! empty($custom_field) ){
        echo '<p class="ozel-alanlar">'.$custom_field.'</p>';
    }
    
}

And I also tried to this code to display image field but it doesn't work:

add_action( 'woocommerce_after_shop_loop_item_title', 'custom_image_display_below_title', 2 );
function custom_image_display_below_title() {
    global $product;

    // Get the custom field value
    $oa2 = get_post_meta( $product->id, 'oa2', true );

    // Display
    if ( ! empty( $oa2 ) ) {
        echo '<img src="' . $oa2 . '" />';
    }

}

This is the result: Image 1

And the custom fields I created;

Image 2

Image 3

Upvotes: 0

Views: 2447

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

As you are using Advanced custom fields, you need to use get_field() dedicated function instead. The image field need to be set as "Image Url". Now the code will be:

add_action( 'woocommerce_after_shop_loop_item_title', 'custom_field_display_below_title', 2 );
function custom_field_display_below_title(){
    global $product;

    // Display ACF text
    if( $text = get_field( 'oa1', $product->get_id() ) ) {
        echo '<p class="ozel-alanlar">' . $text . '</p>';
    }

    // Display ACF image
    if( $image_url = get_field( 'oa2', $product->get_id() ) ) {
        echo '<img src="' . $image_url . '" />';
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

You will get something like:

enter image description here

ACF image field documentation

Upvotes: 1

Related Questions