我正在开发一个wordpress网站,该网站使用woocommerce进行电子商务功能。我在网站上有3个类别,每个类别都有自己的模板,分配给这些类别中的产品。
我已经创建了模板,并且有两个工作正常。但是,我不知道如何在我的single-product.php文件中调用第三个模板,该文件包含以下代码,以根据产品分配给的类别更改模板:
<?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. ?>
我拥有的模板是:
这些类别是合法的,展示和商品。
我需要PHP代码的帮助,所以我可以在3个模板之间切换。不确定我是否应该使用switch语句,或者如何实现它,或者我是否可以使用elseif或如何实现它。即使有一种完全不同的方式来实现这一点,我也很想知道。
任何指针将不胜感激。
最好使用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');
}
而不是为商品添加单独的elseif,你可以在上面的其他地方这样做,因为默认情况下,如果它不合法或显示它必须是商品,但你可以只添加另一个具有相同的基本结构。