【问题标题】:WP Woocommerce is_product_category not workingWP Woocommerce is_product_category 不起作用
【发布时间】:2015-01-06 05:06:36
【问题描述】:

我在我的 woocommerce 商店中销售单一产品,除了该产品之外,我还为他销售一些配件,因此我想使用两个模板。在content-single-product.php 文件旁边,我创建了另一个名为content-single-accessory.php 的文件并编辑该模板文件。

接下来我创建了两个类别:产品和配件,产品本身添加到产品类别中,配件添加到配件类别中。现在它来了我面临的问题。在single-product.php 里面我是这样做的:

    <?php if (is_product_category( 'product' )) { ?>

    <?php wc_get_template_part( 'content', 'single-product' ); ?>

    <?php } else  { ?>

    <?php wc_get_template_part( 'content', 'single-accessory' ); ?>

    <?php } ?>

当我访问带有产品类别的页面时,它不会显示产品模板,但会显示content-single-accessory.php。或者更清楚地说,上面的 if 语句根本不起作用,并且总是显示第二个模板。我在这里做错了什么?

谢谢!

【问题讨论】:

  • 您好,您是父类别的子类别吗?

标签: php wordpress if-statement woocommerce conditional


【解决方案1】:

请试试这个并告诉我:

<? 
$terms = get_the_terms( $post->ID, 'product_cat' );

foreach ($terms as $term) {
   if($term->slug == 'product') : ?>

      <?php while ( have_posts() ) : the_post(); ?>
         <?php wc_get_template_part( 'content', 'single-product' ); ?>
      <?php endwhile; // end of the loop. ?>
        <?php else :?>
            <?php wc_get_template_part( 'content', 'single-accessory' ); ?>
        <?php endif; 
}?>

编辑: 在开头添加&lt;?

【讨论】:

  • 此代码格式似乎不正确。这个 IF 语句在 WHILE 内结束,在外开始?
  • 是的,但是得到错误,你没有正确关闭东西
  • ok,试过了,效果和没用一样。还有其他建议吗?
  • 我在干净的 wp 安装中使用此代码并且可以正常工作
【解决方案2】:

这是在wordpress 中尝试使用is_product_category()is_category() 的好习惯,但是当情况不按您的方式进行时,不要让它变得复杂。

  1. 获取您当前的页面网址

    $current_url = (isset($_SERVER['HTTPS'])
                    ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    
  2. 并检查类别页面简单,

    if(strpos($current_url,'product-category') !=false
                              || strpos($current_url,'brand') !=false ) {
    
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多