Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create single product template

I need to make individual template for each product in my woocommerce site.

Is there a method to do something similar like single-product-9455.php

I believe I can make template using categories like this

<?php
    if ( has_term( 'custom-1', 'product_cat' ) ) {
        wc_get_template_part( 'content', 'custom-1' );
    }
    elseif ( has_term( 'custom-2', 'product_cat' ) ) {
        wc_get_template_part( 'content', 'single-product-custom-2' );
    }
    else {
        wc_get_template_part( 'content', 'single-product' );
    }
?>

But that would lead to quite many unnecessary categories since every product needs a custom template.

Is there a way to target product id?

Body css class is not enough. I need a template for each.

like image 939
niksos Avatar asked Jul 10 '26 00:07

niksos


1 Answers

You can, but you don't want to do this. It could get very messy as / if the site grows. A sensible direction would be and use conditionals.

Otherwise, if the rabbit hole sounds good you may want to create a new category for each product to hook a conditional...

1) Create a woocommerce folder in your theme directory if it doesn't exist.

2) In this directory called "woocommerce" duplicate your content-single-product.php file and name the new one content-single-product-TEMPLATENAME.php

Also copy the woocommerce template file single-product.php from woocommerce to your directory called woocommerce and find the folowing line:

3) Find the following line in the single-product.php you just copied over.

woocommerce_get_template_part( 'content', 'single-product' );

Change this to:

if (is_product_category( '1CATEGORY') // Where this is the category name
{
    // Category name 1
    woocommerce_get_template_part( 'content', 'single-product-TEMPLATENAME' );
}
elseif (is_product_category( '2CATEGORYNAME') 
{
    // category name 2
    woocommerce_get_template_part( 'content', 'single-product-TEMPALTENAME2' );
}
else
{
    // You will allows want to default to the single product template.
    woocommerce_get_template_part( 'content', 'single-product' );
} //endif

If there is a way to hook from a product id you wouldn't want to. This would require the product to be there in advance which makes no sense from a development / business perspective.

Revisions welcomed.

like image 154
ham-sandwich Avatar answered Jul 13 '26 14:07

ham-sandwich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!