No matter how many ways I try, I can't get it to work. I must mention that I have used this snippet for other purposes, such as restricting the possibility of buying if the product contains a certain tag or a certain category.
But to do this based on the user role, I just haven't been able to pull it off. I remember this did work like a couple of months ago, but now, it just doesn't work anymore. Is there something I'm missing?
add_filter('woocommerce_is_purchasable', 'modo_catalogo_por_rol_usuario', 10, 2 );
function modo_catalogo_por_rol_usuario( $is_purchasable, $product ) {
$user = wp_get_current_user();
$catalog_roles = array('cliente_empresa_limited', 'cliente_modo_catlogo', 'administrator'); //add your user roles here
$roles = ( array ) $user->roles;
$is_purchasable = true;
if ( in_array( $catalog_roles, $roles ) ) {
$is_purchasable = false;
}
return $is_purchasable;
}
The following code will restrict the ability to purchase products based on user role. The user roles cliente_empresa_limited, cliente_modo_catlogo, and administrator will be able to purchase without restriction:
/* Restrict the ability to buy products based on the user role.
Roles 'cliente_empresa_limited', 'cliente_modo_catlogo',
and 'administrator' will be able to purchase */
function modo_catalogo_por_rol_usuario(){
$user = wp_get_current_user();
$user_meta=get_userdata( $user->ID );
$user_roles=$user_meta->roles;
if ( ( in_array( 'cliente_empresa_limited', (array) $user_roles ) ) || ( in_array( 'cliente_modo_catlogo', (array) $user_roles ) ) || ( in_array( 'administrator', (array) $user_roles ) ) ) {
return true;
}
else {
return false;
}
}
add_filter( 'woocommerce_is_purchasable', 'modo_catalogo_por_rol_usuario' );
Add the code above in functions.php file of your active child theme or active theme. It is tested and it works.
You should use array_intersect which will return an array of matches between two arrays. If the count is greater than 0, then it will be true.
add_filter( 'woocommerce_is_purchasable', 'modo_catalogo_por_rol_usuario', 10, 2 );
function modo_catalogo_por_rol_usuario( $is_purchasable, $product ) {
$user = wp_get_current_user();
$catalog_roles = array( 'cliente_empresa_limited', 'cliente_modo_catlogo', 'administrator' ); // add your user roles here.
$roles = (array) $user->roles;
if ( 0 < count( array_intersect( $catalog_roles, $roles ) ) ) {
$is_purchasable = false;
}
return $is_purchasable;
}
Related
I have the following function that runs on catalogue page and shows or hides specific products from users based on their role. If the user is customer then he can see the products that have checked the set_catalog_visibility (ACF).
The issue is that this function is slowing down my catalogue and i need to optimize it so it will run faster.
add_action('pre_get_posts', function( $query ){
$user = wp_get_current_user();
if ( $query->is_main_query() && is_woocommerce()) {
if (!check_user_role(array('customer','administrator')) || !is_user_logged_in() ) {
$product_ids = get_post_ids_by_meta_key_and_value('prd_clients', 1);
foreach($product_ids as $id){
// Get an instance of the product
$product = wc_get_product($id);
// Change the product visibility
$product->set_catalog_visibility('hidden');
// Save and sync the product visibility
$product->save();
}
}
else{
$product_ids = get_post_ids_by_meta_key_and_value('prd_clients', 1);
foreach($product_ids as $id){
// Get an instance of the product
$product = wc_get_product($id);
// Change the product visibility
$product->set_catalog_visibility('visible');
// Save and sync the product visibility
$product->save();
}
}
}
});
You can done it simply like this:
add_action(
'pre_get_posts',
function( $query ) {
if ( $query->is_main_query() && is_woocommerce() ) {
if ( ! is_user_logged_in() && ( is_user_logged_in() && ! check_user_role( array( 'customer', 'administrator' ) ) ) ) {
$product_ids = get_post_ids_by_meta_key_and_value( 'prd_clients', 1 );
if ( ! empty( $product_ids ) ) {
$query->set( 'post__not_in', $product_ids );
}
}
}
}
);
I have a form setup for users to fill in after they register on my WordPress site. Ive setup the form using Contact Form 7, and have a radio button called radio-766 that has two options: subscriber and customer.
I want the user to pick one of these two options, then when they submit the form, it will change their user role.
Below is what I have so far... I've grabbed snippets from online and tried to create my own, but it isn't working. Any ideas on how I can get this to work?
function tm_cf7_roles_posted_data( $posted_data ) {
// Stop if user is not logged in.
if ( ! is_user_logged_in() )
return;
ob_start();
$role = sanitize_key( $posted_data['radio-766'] );
if ( ! in_array( $role, array( 'subscriber', 'customer' ) ) )
return;
$user = new WP_User( get_current_user_id() );
$index = key( $user->roles );
$user_role = $user->roles[ $index ];
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_action( 'wpcf7_posted_data', 'tm_cf7_roles_posted_data' );
Should I be including the form name or ID anywhere? Can't find info on this
Any help is so appreciated!
EDIT
I feel like there is nothing connecting this function to the CF7 form named "After LinkedIn", so I found this snippet of code, just not sure how to integrate and get working
if (!isset($cfdata->posted_data) && class_exists('WPCF7_Submission')) {
// Contact Form 7 version 3.9 removed $cfdata->posted_data and now
// we have to retrieve it from an API
$submission = WPCF7_Submission::get_instance();
if ($submission) {
$formdata = $submission->get_posted_data();
}
} elseif (isset($cfdata->posted_data)) {
// For pre-3.9 versions of Contact Form 7
$formdata = $cfdata->posted_data;
} else {
// We can't retrieve the form data
return $cfdata;
}
// Check this is the user registration form
if ( $cfdata->title() == 'After LinkedIn') {
As per the Contact form 7 plugin author is_user_logged_in() will work on below to cases in form submission:
subscribers_only: true set in the additional setting in form. OR
Set WPCF7_VERIFY_NONCE to true using add_filter( 'wpcf7_verify_nonce', '__return_true' );
For more information click here.
Also, to change the user role you can do the following:
add_action( 'wpcf7_posted_data', 'tm_cf7_roles_posted_data' );
function tm_cf7_roles_posted_data( $posted_data ) {
$submission = WPCF7_Submission::get_instance();
$wpcf7 = WPCF7_ContactForm::get_current();
$formID = $wpcf7->id();
if ( $submission ) {
if( $formID == "YOUR-FORM-ID" ) {
if ( is_user_logged_in() ) {
$role = sanitize_key( $posted_data['radio-766'][0] );
if ( ! in_array( $role, array( 'subscriber', 'customer' ) ) )
return;
// Getting the WP_User object
$user = wp_get_current_user();
// The user exists
if( $user && $user->exists() ) {
// Check if user already has that role or not
if ( !in_array( $role, (array) $user->roles ) ) {
// Remove all the previous roles from the user and add this one
// This will also reset all the caps and set them for the new role
$user->set_role( $role );
}
}
}
}
}
}
If you only want to add a new role to the user and retain the existing role then instead of set_role use below:
// Add a new role to the user while retaining the previous ones
$user->add_role( $role );
As for programatically setting a user role you can just take the user object and use the set_role() function to change their role to whatever you want as long as that role has been defined.Try this way
function tm_cf7_roles_posted_data( $posted_data ) {
// Stop if user is not logged in.
if ( ! is_user_logged_in() )
return;
ob_start();
$role = sanitize_key( $_POST['radio-766'] );
if ( ! in_array( $role, array( 'subscriber', 'customer' ) ) )
return;
$user = new WP_User( get_current_user_id() );
$index = key( $user->roles );
$user_role = $user->set_role($role);
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_action( 'wpcf7_posted_data', 'tm_cf7_roles_posted_data' );
Is it possible to create a function via functions.php that restricts users from creating pages based on their user role? So for example, users with the user role "limited" can only create 5 pages.
When they reach this amount, the "Create new page" button must be gone or they have te receive a message that they reached there limit and have to contact there admin.
I know there is a plugin called Bainternet Posts Creation Limits but this is causing some problems.
Is something possible with a function?
EDIT:
Ok, I tried the code below but aint working and to be honest my coding skills are to poor to make something of it.
Anybody else any ideas?
You could try something like this:
Step 1: Upon user creation: give your user the capability 'publish_pages'
Step 2: Save in the user_meta how many pages the user has created.
Step 3: If the user has 5 or more pages remove the capability from this user.
STEP 1 & 2 (untested):
add_action( 'user_register', 'user_registered', 10, 1 );
function user_registered( $user_id ) {
// ADD CAPABILITY
$user = new WP_User( $user_id );
if ( ! empty( $user->roles ) && is_array( $user->roles ) && in_array( 'YOURROLEHERE', $user->roles ) ) {
$user->add_cap( 'publish_pages');
update_user_meta($user_id, 'numberofpages', 0);
}
}
STEP 3 (untested):
add_action('publish_page', 'user_published_page');
function user_published_page(){
// GET CURRENT USER
$user_id = get_current_user_id();
$user = new WP_User( $user_id );
// CHECK ROLE
if ( ! empty( $user->roles ) && is_array( $user->roles ) && in_array( 'YOURROLEHERE', $user->roles ) ) {
// GET NUMBER OF PAGES CREATED
$numberofpages = intval(get_user_meta($user_id, 'numberofpages', true));
if($numberofpages >= 5){
$user->remove_cap( 'publish_pages');
} else {
update_user_meta($user_id, 'numberofpages', $numberofpages + 1);
}
}
}
I found the answer from Nathan Powell but I can not apply this function to a specific user role. I want this function applies only for user "author" role.
I've been using :
if ( !current_user_can( 'author' )):
and I'm wondering how to place it.
Try below code:
function wpse_199918_wp_editor_settings( $settings, $editor_id ) {
$current_user = wp_get_current_user();
if ( $current_user->roles[0] === 'author' ) {
$settings['tinymce'] = false;
$settings['quicktags'] = false;
$settings['media_buttons'] = false;
}
return $settings;
}
add_filter( 'wp_editor_settings', 'wpse_199918_wp_editor_settings', 10, 2 );
I got this code that will apply tax free on a user role regardless of what they order, which is fine.
But now I need another user role that will apply tax free on specific products id, and I'm not sure how to acomplish that.
The code im using right now for tax free on all products for specific user role is:
// Apply a different tax rate based on the user role.
function wc_diff_rate_for_user( $tax_class, $product ) {
// Getting the current user
$current_user = wp_get_current_user();
$current_user_data = get_userdata($current_user->ID);
if ( in_array( 'administrator', $current_user_data->roles ) || in_array( 'userrolename', $current_user_data->roles ) )
$tax_class = 'Zero Rate';
return $tax_class;
}
add_filter( 'woocommerce_product_tax_class', 'wc_diff_rate_for_user', 1, 2 );
// Fin Apply a different tax rate based on the user role.
Here is the code that will apply this "Zero Rate" tax class for some defined products and some defined user roles:
add_filter( 'woocommerce_product_tax_class', 'wc_diff_rate_for_user', 1, 2 );
function wc_diff_rate_for_user( $tax_class, $product ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Define HERE your targeted products IDs
$products_ids_arr = array(12 ,15, 24);
// Define HERE your targeted user roles
$users_role_arr = array('administrator', 'userrolename');
//Getting the current user data
$user_data = get_userdata(get_current_user_id());
foreach ($users_role_arr as $user_role)
if ( in_array( $user_role, $user_data->roles ) && in_array( $cart_item->id, $products_ids_arr ) ) {
$tax_class = 'Zero Rate';
break;
}
return $tax_class;
}
This code is tested and works.
Code goes in any php file of your active child theme (or theme) or also in any plugin php files.
CASE 1 Via code
You can use add role function like
<?php add_role( $role, $display_name, $capabilities ); ?>
Example
add_role('basic_contributor', 'Basic Contributor', array(
'read' => true, // True allows that capability
'edit_posts' => true,
'delete_posts' => false, // Use false to explicitly deny
));
CASE 2 : Via Plugin
https://wordpress.org/plugins/user-role-editor/