0

So I'm currently using Woocommerce and managed to figure how to override templates based on the documentation. Now I have a problem, so i managed to override a specific template let's say upsell.php. Right now I need to create another upsell.php template that provides a different layout. Lets just call it up-sell-alternate.php

Now my question is it possible to create a hook and fetch that custom template even though it is not part of the woocomerce templates.

I need to reuse various parts of woocommerce templates and provide a different layouts for each of them. I cannot to find something that fits my question on the documentation of woocommerce

1

You could consider using the good ol' get_template_part( string $slug, string $name = null, array $args = array() function, which is a native WP function. Especially now as it supports the third parameter for passing data to the template file (since WP 5.5).

Create a function (in your (child) theme functions.php file) that wraps around some get_template_part() call and hook it onto suitable action that WooCommerce provides.

https://developer.wordpress.org/reference/functions/get_template_part/

EDIT 30.8.2020

You could for example have the following structure in your (child) theme directory,

/my-child-theme
--/parts
----/my-template-part.php
----/my-template-part-alt.php

To use the custom template parts, you could do the following in your functions.php file.

add_action( 'some_woocommerce_template_action', 'my_fancy_template_part' );
function my_fancy_template_part() {
    // pass data to the template part in an array
    $args = array(
        'key_1' => 'foo',
        'key_2' => 'bar',
    );
    get_template_part( '/parts/my-template-part', null, $args );
}

add_action( 'some_other_woocommerce_template_action', 'my_fancy_template_part_alternative' );
function my_fancy_template_part_alternative() {
    // get a "named" part with shared prefix
    get_template_part( '/parts/my-template-part', 'alt' );
}

If you passed $args as the third parameter to get_template_part(), you can the access them in your template part file like so,

echo $args['key_1']; // foo
  • Sorry for my ignorance but how do I call the template using the function, I'm still new with wordpress and woocommerce. <?php get_template_part( 'path/to/file', 'optional-slug' ); ?> is it something like this? – clestcruz Aug 28 '20 at 23:39
  • @clestcruz Yes, along those lines. I added some examples to my answer oh how to use the function with action hooks. – Antti Koskinen Aug 30 '20 at 6:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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