I’m struggling to get a custom field to correctly display on a Woocommerce single product page. Things I know are working:
- I know for sure I’m editing the corect section of Woocommerce – I have my override templates in a /woocommerce directory inside my theme and I’ve successfully made other changes (this is my first ACF Pro change).
- I know the custom field exists, and is being correctly displayed on the woocommerce product pages in the backend.
- I know that the image I’ve associated to this particular custom field (called ‘custom_bg’) is in the media library.
- I know the section where I’m trying to add this field is outside the loop.
Things I’ve tried:
<img src="<?php echo get_field('custom_bg', 98); ?>"></img>
– (98 is the id of the Woo product) shows nothing
<img src="<?php the_field('custom_bg', 98); ?>"></img>
– shows nothing
<?php $productID = get_the_ID(); ?>
<?php echo $productID; ?>
<img src="<?php echo get_field('custom_bg', 98); ?>"></img>
– nothing
function action_woocommerce_before_main_content() {
$productID = get_the_ID();
echo '<img src="' . get_field('custom_bg', $productID) . '"></img>';
};
// add the action
add_action( 'woocommerce_before_main_content', 'action_woocommerce_before_main_content', 10, 2 );
put this in the functions.php file – nothing
So now I’m stuck. Hopefully I’ve just made a rookie error, but I can’t see the wood for the trees. Help me Obi Wan!
Ok, in way of an update, I’ve done a bit more investigation and discovered the following. Using <?php echo get_field('custom_bg', $product->ID); ?>
correctly displays the image from the custom field – YAY!
However, this only works on certain products! Right now, during testing, I only have two active Woocommerce products, with IDs 98 and 106. I’ve added some debug code to the page so I know what the current page ID is at any time. When I visit product 106, the debug code correctly shows 106, and the custom_bg field is displayed. And when I visit product 98 I see 98 in the debug code but no custom_bg field displays. What’s most perplexing is when I visit my Woocommerce Shop page, the debug code shows 98.
Is this expected behaviour? Is the ID clash what’s stopping the custom_bg field from displaying?
I’m going to add another product to see if it displays there…