0

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:

  1. How can I conditionally run the 'add_action' function based on whether my custom product meta has a value of 'X' or not?

  2. How can I customize my 'add_action' function to work with more than one Woocommerce hooks?

Many thanks!

1 Answer 1

0

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, and woocommerce_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.
1
  • Thanks! With a few adjustments this solution worked perfectly. Commented Jun 27, 2022 at 3:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.