0

I would like to hide one specific product for all not logged in users. Suppose $post is that post. I used the hooks:

add_action( 'wp', 'WC_Query::remove_product_query' ) ;

and

remove_action( 'pre_get_posts', 'WC_Query::pre_get_posts' );

but none of them seem to be working.

 global $post;
    if( get_post_type() == "product" )
    {
       if(is_user_logged_in()){
          return;
       }

        add_action( 'wp', 'WC_Query::remove_product_query' ) ;
        remove_action( 'pre_get_posts', 'WC_Query::pre_get_posts' );
        $post->post_content = 'Hidden';

        return;
    }
  • you can use private status instead of public, incase you dont have any other requirements – Piyush Rawat Nov 27 '17 at 9:16
  • @PiyushRawat No i have other requirements. thank you.. – Steve Nov 27 '17 at 9:22
  • This code works on my localhost. Here it is : pastebin.com/FpZ5Ys4w – Piyush Rawat Nov 27 '17 at 9:42
1

This code is tested and works fine on a fresh WP and WooCommerce installation.

if ( !is_user_logged_in()) {
  function exclude_product_from_users($q){
    $current_user = wp_get_current_user();
    $prodcuts_ids = array(648);
    $q->set( 'post__not_in', $prodcuts_ids );
  }
  add_action( 'woocommerce_product_query', 'exclude_product_from_users' );
  function return_from_product_page(){
    global $post;
    $prodcuts_ids = array(648);
    if(in_array( $post->ID , $prodcuts_ids)){
        wp_redirect(home_url('/'));
        exit();
    }
  }
  add_action('wp', 'return_from_product_page');
}

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.