woocommerce offtopic – Conditionally run function based on custom meta value?
I’m looking for a way to conditionally display an image within certain Woocommerce hooks that I choose based on whether a value is true within a custom meta field for the products on my site.
For example, if my custom meta value for a product is “X”, then I print custom html (containing an image) for the Woocommerce hooks ‘woocommerce_product_additional_information’ and ‘woocommerce_after_shop_loop_item’. However if the meta value is empty, then no image is printed for a particular product post.
So far this is the code I’ve been trying to make work within my theme’s functions.php file for a single hook. The ‘add_action’ function works for displaying images within a hook, but I can’t figure out how to get the if statement to work.
if ( get_post_meta($post_id->ID, 'my-custom-meta-field', true) ) :
add_action( 'woocommerce_product_additional_information', 'print_custom_html' );
function
print_custom_html
(){ ?> <img src="image.jpg" alt="Image Name"> <?php }
endif;
My questions:
-
How can I conditionally run the ‘add_action’ function based on whether my custom product meta has a value of ‘X’ or not?
-
How can I customize my ‘add_action’ function to work with more than one Woocommerce hooks?
Many thanks!
Leave an answer