The question:
I’ve made a custom template for a category called “shop” on the products tab. I’ve read some of the previous topics that mention doing an if conditional to the templete checking the category its in.
I’ve tried this and had no luck so went to making a template called single-product-shop.php, I then wrote a conditional to load the particular page template and placed it within single-product.php.
However Now I seem to generate a php warning.
<?php while ( have_posts() ) : the_post(); ?>
<?php
if( has_term( 'shop', 'product_cat' ) ) {
$file = 'single-product-shop.php';
} else {
$file = 'single-product-default.php';
}
global $woocommerce;
load_template( $woocommerce->template_url . $file );
?>
<?php endwhile; // end of the loop. ?>
If someone could please point out what I’m doing wrong, I would be most greatful.
Thanks
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
Woocommerce has it’s own function woocommerce_get_template_part()
for loading template parts, use it like this:
woocommerce_get_template_part( $slug, $name );
which refers to the according file {$slug}-{$name}.php
or used like this:
woocommerce_get_template_part( $slug );
refers to the file {$slug}.php
, it automatically
Looks in yourtheme/slug(-name).php and yourtheme/woocommerce/slug(-name).php
it can be used with a conditional like this:
if( has_term( 'shop', 'product_cat' ) ) {
woocommerce_get_template_part( 'single-product-shop' );
} else {
woocommerce_get_template_part( 'content', 'single-product' );
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0