While a user is creating a new post, how do I determine his current role?
I'm assuming you know what hooks of Wordpress you want to use. So skipping that part, it's pretty easy to get the current role of the user
$current_user = wp_get_current_user();
if ( !($current_user instanceof WP_User) )
return;
$roles = $current_user->roles; //$roles is an array
Now, you can iterate over that array to see if the user has a particular role.
Or, you can use current_user_can to look for specific capabilities, if you just want to check whether or not a user has a specific permission versus whether or not they're in the role. For example:
if (current_user_can('delete_posts')) {
//display the delete posts button.
}
This code will help you
<?php echo array_shift(wp_get_current_user()->roles); ?>
Related
Is there any way to retrieve the clean unhashed password value in the WooCommerce checkout page with any hook?
What I need to do: I need to create a Firebase Auth user when a new WordPress user is creating. If this is not possible, what would be the best practice to achieve this?
What I tried
First I tried to create a new custom field on checkout and retrieve it with:
function wh_CustomReadOrder($order_id)
{
$order = wc_get_order($order_id);
WC()->session = new WC_Session_Handler;
/*
* Next lets create a customer so we can access checkout fields
* If you will check a constructor for WC_Customer class you will see
* that if you will not provide user to create customer it will use some
* default one. Magic.
*/
WC()->customer = new WC_Customer;
/*
* Done. You can browse all chceckout fields (including custom ones)
*/
?>
<script type="text/javascript">
var order = <?php echo $order ?>;
var checkout_fields = <?php echo json_encode(WC()->checkout->checkout_fields) ?>
var email = order;
console.log(checkout_fields);
</script>
<?php
}
add_action('woocommerce_thankyou', 'wh_CustomReadOrder');
I get an array with all fields, but my custom field is not showing. But even if so, the WordPress password will still be different. The best way would be to simply get the WordPress password and then create the user in Firebase.
Do you have any idea?
As you will see in the wc-user-functions.php file, the function wc_create_new_customer is used when creating a new account.
For checking the checkout page you can use Conditional Tags
is_checkout() Returns true on the checkout page.
So to intercept the unhashed password you could use the woocommerce_created_customer hook. The $unhashed_password variable will contain the unhashed password.
function action_woocommerce_created_customer ( $customer_id, $new_customer_data, $password_generated ) {
// Returns true on the checkout page.
if ( is_checkout() ) {
$unhashed_password = $new_customer_data['user_pass'];
}
}
add_action( 'woocommerce_created_customer', 'action_woocommerce_created_customer', 10, 3 );
One approach I would consider is to build a custom webform for creating the customer's account. That way you can manipulate the data however you want.
For example, when the user submits the form, take the data, register the new user in WC/WP, send the data to firebase, then redirect.
The downside is that you'll have to manage the process a 100% and deal with any possible errors.
Another way:
Use the default WC or WP account creation form, but on submit -> prevent Default with Javascript, take the data (yes you can access the password before it's hashed), send it to Firebase, THEN, submit the form and let WC/WP save it in the database in a normal fashion.
I did it like this when I needed to send that data to an Email Management software. The user enters the values, hits submit: my code blocks the submit event, sends the data where I want it to, then submits the form.
Hope it helps!
I have two roles called Agent and Subagent.
I want to hide these two specific roles from the admin user list.
I tried using the pre_user_query filter but couldn't get it to work.
Could anyone please suggest a correct way to do it?
Thanks,
Simpler & safer:
add_filter('pre_get_users', function ($user_query) {
// use the sluglike role names, not their "display_name"s
$user_query->set('role__not_in', ['agent', 'subagent']);
});
role__not_in available since WP 4.4.
Caveat: the roles (and their user count) will still show up above the users table.
I found the perfect solution for what I wanted here: https://rudrastyh.com/wordpress/pre_user_query.html
add_action('pre_user_query','hide_all_agents_subagents');
function hide_all_agents_subagents( $u_query ) {
$current_user = wp_get_current_user();
if ( $current_user->roles[0] != 'administrator' ) {
global $wpdb;
$u_query->query_where = str_replace(
'WHERE 1=1',
"WHERE 1=1 AND {$wpdb->users}.ID IN (
SELECT {$wpdb->usermeta}.user_id FROM $wpdb->usermeta
WHERE {$wpdb->usermeta}.meta_key = '{$wpdb->prefix}capabilities'
AND {$wpdb->usermeta}.meta_value NOT LIKE '%agent%' AND {$wpdb->usermeta}.meta_value NOT LIKE '%subagent%')",
$u_query->query_where
);
}
}
I need to grant users a specific role (Editor, Administrator, etc.) along with all its capabilities on the fly in Wordpress, but I don't want to update their role in the database (so that the next time they come back, they will have their original role). How can I go about doing this?
Here's what I ended up doing:
add_filter( 'user_has_cap', 'override_caps' );
function override_caps($allcaps){
if( ... ){ // When to override caps
$role_name = 'administrator';
$role = get_role($role_name); // Get the role object by role name
$allcaps = $role->capabilities; // Get the capabilities for the role
$allcaps[$role_name] = true; // Add role name to capabilities
}
return $allcaps;
}
I'm using Formidable forms in Wordpress and have a form that registers users. I can use a radio button in the registration form to determine what their role will be. I have a hook for that. What I need, however, is a hook that will change the user role based on radio selection on form entry UPDATE. My current code only works on entry creation. Here is the code that assigns roles on registration:
add_filter('frmreg_new_role', 'frmreg_new_role', 10, 2);
function frmreg_new_role($role, $atts){
extract($atts);
if($form->id == 8){
if($_POST['item_meta'][280] == 'Job Applicant')
$role = 'applicant';
}
return $role;
}
"8" is the id of the form itself. "280" is the id of the radio button field where "Job Applicant" is one of the values. And "applicant" is one of our site's user roles.
I need an adaptation of this that will change the role after the entry has already been created, on update. The closest thing I can find is a hook that changes user role after a successful PayPal payment. I tried to combine the two but I couldn't get it to work. Here is the PayPal generated user role changer:
add_action('frm_payment_paypal_ipn', 'change_paid_user_role');
function change_paid_user_role($args){
$new_role = 'contributor'; //change this to the role paid users should have
if(!$args['pay_vars']['completed'])
return; //don't continue if the payment was not completed
if(!$args['entry']->user_id or !is_numeric($args['entry']->user_id))
return; //don't continue if not linked to a user
$user = get_userdata($args['entry']->user_id);
if(!$user)
return; //don't continue if user doesn't exist
$updated_user = (array)$user;
// Get the highest/primary role for this user
$user_roles = $user->roles;
$user_role = array_shift($user_roles);
if ( $user_role == 'administrator' )
return; //make sure we don't downgrade any admins
$updated_user['role'] = $new_role;
wp_update_user($updated_user);
}
UPDATE: the action hook should probably be: frm_after_create_entry according to Formidable forums.
Many times, researching the core files is more productive than any Google or Manual. Dropping the whole plugin directory in a code editor and researching for the string frm_after_create_entry takes us to the create() method where this hook happens.
After that, there's the update() method and it provides the action hook: frm_after_update_entry.
This hook passes two parameters: $id and $new_values['form_id']. I cannot reproduce your setup, so testing the hook is up to you.
Reference: Actions and filters are NOT the same thing…
In this example:
add_action( 'frm_after_update_entry', 'change_role_to_staff', 10, 2);
function change_role_to_staff( $form_id, $values ){
var_dump($values);
die();
}
As this is an action hook, nothing has to be returned.
There's no $roles or $atts, the parameters are the form ID and Values.
What you're looking for is inside $values.
var_dump() and die() are for debugging purposes and must be removed at once after testing.
Do your wp_update_user with this values and adapting your previous code.
I am creating a Wordpress website for multi author and want to set user role as per article submission. Means if any user have 0-10 article they will go to Contributor role, if 11-30 will go to Author role if 31-100 will go to Editor role.
Also I want to make registration system where default registration group will be Subscriber. They will get a link into verification email like
If you want to become a Contributor please click on below link. (To submit an article you must have at least Contributor permission)
http:// link will be here ... this link automatically change user role from Subscriber to Contributor.
Hope I will get solution from you expert. I am posting this issue with lots of hope from you friends.
What you want to do is when they post their submission check to see how many posts they have authored and then change the role. So in your theme's functions.php file you'd need a hook that is like this.
add_action('publish_post', 'update_roles');
and then a function to update the roles.
function update_roles()
{
global $wpdb;
// Get the author
$author = wp_get_current_user();
// Not sure if $author and $u are the same object I suspect they are.
// so this may not be necessary, but I found this code elsewhere.
// You may be able to do without this and just replace $u with $author later in the code.
// Get post by author
$posts = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_author = " . $author->ID );
$numPost = count($posts);
// Do the checks to see if they have the roles and if not update them.
if($numPost > 0 && $numposts <= 10 && current_user_can('subscriber'))
{
// Remove role
$author->remove_role( 'subscriber' );
// Add role
$author->add_role( 'contributor' );
}
...... other conditions .......
}
Using SQL statements (Database Queries) to get at Wordpress data is not in accordance with Wordpress coding standards . See Wordpress Handbook
It would be better to use count_user_posts function
See Function on the codex