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?
There are some mistakes in your code and some considerations:
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.
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:
Hook into woocommerce_after_main_content
on category pages only.
It will dynamically target the correct category on which the field is being displayed, by using: get_queried_object()
.
It ensures that the ACF function fetches the correct data tied to the current category, by passing get_field()
to a variable.
Conditional check, if the ACF field is not empty, and otherwise not output anything.
It will display the image as santizied output, using esc_url()
and esc_attr()
.
/*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: