phpwoocommerceproductadvanced-custom-fieldshook-woocommerce

How to display an ACF field in WooCommerce product category archive pages


Using Advanced custom fields plugin ACF, I added an image field to the product category and can't get it to display after the main content (below products) using the code below:

add_action( 'woocommerce_after_main_content', 'wc_add_lower', 100 );
function wc_add_lower() { 
    
    ?>
        <?php the_field('lower'); ?>
    <?php
}

How to display the image (from ACF field) in WooCommerce product category archive pages?


Solution

  • There are some mistakes in your code and some considerations:

    1. The woocommerce_after_main_content is a global hook. It means it runs on multiple WooCommerce pages: archive-product.php and single-product.php. So without a conditional check like is_product_category() your custom field will also display on single product page.

    2. You use the_field() which is good for simple and plain text or HTML, but if you use image, you might consider using get_field() instead. It all depends on how the field is set up (please see this answer). Here are also references to get_field() and the_field().

    The below code will display the ACF image field after the main content, on woocommerce Archive/Category pages, the following way:

    /*Adding ACF custom metadata field after the main content woocommerce product category page*/
    add_action( 'woocommerce_after_main_content', 'wc_add_lower', 100 );
    function wc_add_lower() {
        // Execute the code only on WooCommerce product category pages
        if ( is_product_category() ) {
            // Get the current product category object
            $term = get_queried_object();
            // Store ACF field 'lower' for the current product category (taxonomy term)
            $lower_image = get_field('lower', $term);
            // Check if the field has a value and output sanitized image & alt text
            if ( $lower_image ) {
                echo '<img src="' . esc_url( $lower_image['url'] ) . '" alt="' . esc_attr( $lower_image['alt'] ) . '">';
            }
        }
    }
    

    Related questions and sources: