[Solved] How to properly use a hook to create template for custom product type in a plugin such as Woocommerce? [closed]


You may use an action in the format woocommerce_YOUR_PRODUCT_TYPE_add_to_cart to reach the goal. Here is the example.

  • The following code is for putting in functions.php, if you are writing a plugin. Please remember to change the callback.

eg. you have a product type called Special, you want to add the add-to-cart template for it.

  • add the action filter woocommerce_special_add_to_cart
  • add the action function woocommerce_special_add_to_cart
// it is better to follow the naming conventions in Woocommerce for the ease of understanding

add_action( 'woocommerce_special_add_to_cart', 'woocommerce_special_add_to_cart', 30 );
function q363582_special_add_to_cart() {
   /**
     * Output the special product add to cart area.
     */
    function woocommerce_special_add_to_cart() {
        wc_get_template( 'your-own-path/special.php' ); // if you have arguments, you could use, read the the manual links of this function for reference
    }
}

For the path, since Woocommerce allow template customisation in theme, so your path could be something like your-theme/single-product/add-to-cart/special.php if you use wc_get_template() function.

The woocommerce_special_add_to_cart action will be called by another action woocommerce_template_single_add_to_cart which will read the type of the product and create the respective action.

// usage
wc_get_template( $template_name, $args = array(), $template_path="", $default_path="" )

According to this function, you may also use your own $template_path, so I think this should meet your need.

For details, you may read docs:
wc_get_template()

For the usage of wc_get_template(), you may refer to source code for examples of default product types like grouped, variation and so on:
wc-template-functions.php

solved How to properly use a hook to create template for custom product type in a plugin such as Woocommerce? [closed]