Instead of conditionally adding an add_action()
call, you can just add it and run the function it hooks to—its callback—conditionally instead.
For example:
add_action( 'woocommerce_product_additional_information', 'wpse407073_callback' );
add_action( 'woocommerce_after_shop_loop_item', 'wpse407073_callback' );
function wpse407073_callback( $product = null ) {
if ( empty( $product ) ) {
global $post;
$product = $post;
}
if ( 'X' === get_post_meta( $product->ID, 'my-custom-meta-field', true ) ) {
echo '<img src="image.jpg" alt="Image Name">';
}
}
A few points:
- Having looked quickly at WooCommerce’s code,
woocommerce_after_shop_loop_item
doesn’t pass anything to the callback, andwoocommerce_product_additional_information
passed 1 parameter,$product
, which I’m assuming is a custom post. That’s why I added a check for an empty$product
in the callback. - This code hasn’t been tested, and is meant as a possible starting point, not a finished product.
- If you have questions about WooCommerce’s hooks, you should check with WooCommerce’s documentation and/or their support team.