I am using Woocommerce and I have products in a category called B2B whose single_product.php is only to be shown to people with the capability read_b2b.

<?php if ( have_posts() ) : ?>
<?php do_action('woocommerce_before_shop_loop'); ?>
<?php if (is_product_category('b2b')) && if current_user_can('read_b2b') { ?>
  //*** In this case show the PRODUCT with the LOOP ***
       <?php while ( have_posts() ) : the_post(); ?>
       <?php woocommerce_get_template_part( 'content', 'single-product' ); ?>
       <?php endwhile; // end of the loop. ?>
<?php } else { 
  //*** show error message ***
  echo '<p>You have to be a registered b2b user to see this product</p>';

Can you help me get this hack to work for single-product.php?


My guess is that your problem is here:

if (is_product_category('b2b'))

Taking a look at the Woocommerce Documention for Conditional Tags is_product_category() will return true on product category archives. Therefore, it will never be true on the single product page.

What I think you need instead is has_term() which checks a post for a particular term. Therefore I would suggest you change your conditional to:

<?php if (has_term('b2b', 'product_cat')) && if current_user_can('read_b2b') { ?>

You might want to take a look at the WooCommerce documentation, I'd think you may want to use the hook/filter woocommerce_before_main_content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.