0
votes

I am developing a wordpress website which uses woocommerce for e-commerce functionality. I have 3 categories on the website and each one will have it's own template assigned for products within these categories.

I have created the templates and have got two of them working fine. However I'm not sure how to call the third template within my single-product.php file which contains the following code to change the templates depending on what category the product is assigned to:

<?php while ( have_posts() ) : the_post(); ?>

  <?php global $post;
  $terms = wp_get_post_terms( $post->ID, 'product_cat' );
  foreach ( $terms as $term ) $categories[] = $term->slug;

  if ( in_array( 'legal', $categories ) ) {
  woocommerce_get_template_part( 'content', 'single-product-legal' );
  } else {
  woocommerce_get_template_part( 'content', 'single-product-merc' );
  } ?>

<?php endwhile; // end of the loop. ?>

the templates i have are:

  1. single-product-legal (custom template)
  2. single-product-merc (default woocommerce template)
  3. single-product-show (custom template)

The categories are legal, show and merchandise.

I need help with the php code so I can switch between the 3 templates. Not sure if I should use a switch statement, or how to implement it or if I could use elseif or how to implement that. Even if there's a completely different way to achieve this, I'd love to know.

Any pointers would be appreciated.

1

1 Answers

0
votes

The best it to use elseif:

  if ( in_array( 'legal', $categories ) ) {
    woocommerce_get_template_part( 'content', 'single-product-legal');
  }elseif (in_array('show', $categories)){
    woocommerce_get_template_part('content', 'single-product-show');
  }else {
    woocommerce_get_template_part( 'content', 'single-product-merc');
  } 

Rather than adding a seperate elseif for merchandise you can just do it in the else like above because by default if it is not legal or show it must be merchandise, but you may just add another elseif as well with the same basic structure.