How to check if a category is protected using PHP
WooCommerce Protected Categories provides a class you can use in your own code to check a category's visibility - for example, is the category private or password protected? The class is Barn2\Plugin\WC_Protected_Categories\Category_Visibility
.
To use this class, you create a new instance specifying the category ID (the term ID):
$my_category = new \Barn2\Plugin\WC_Protected_Categories\Category_Visibility( 34 );
Then, use one of the methods provided to check whether it is public, protected, or private:
if ( $my_category->is_public() ) {
// category is public
}
if ( $my_category->is_protected() ) {
// category is protected - this could be password, role or user protected
}
if ( $my_category->is_password_protected() ) {
// category is password protected
}
if ( $my_category->is_user_protected() ) {
// category is user protected
}
if ( $my_category->is_role_protected() ) {
// category is role protected
}
if ( $my_category->is_private() ) {
// category is private
}
Each of these methods also accepts an optional $check_ancestors
flag (defaults to false
). If you set this to true
, the function will check any ancestors of the current category as well:
if ( $my_category->is_password_protected( true ) ) {
// this category or one of its ancestors is password protected
}
To check whether a protected category has been unlocked by any method (password, current user, etc), you can use the is_unlocked()
function:
if ( $my_category->is_unlocked() ) {
// category is unlocked for the current user
}
To view the full API for this class, and the rest of the plugin, please refer to the plugin API documentation.