Wordpress: Change user role conditionally - wordpress

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

Related

Get password value in WooCommerce checkout

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!

Save custom fields to user meta on WooCommerce Checkout for new user who is registering on checkout

I have added several custom fields to my checkout that only appear when a user is checking out as a guest for the first time. My checkout process requires that the user create an account to complete checkout.
I have added four fields using the woocommerce_form_field method and then I have tried modifying the code provided in the answer here to achieve what I want. However, I have tried several checkouts, creating new accounts to check if the custom field values save into the new users' profile, but it doesn't seem to be working.
Here is one example of a solution I tried which did not work:
function reigel_woocommerce_checkout_update_user_meta( $customer_id) {
if ( ! empty( $_POST['practitioner_license_number'] ) ) {
$pln = sanitize_text_field( $_POST['practitioner-license-number'] );
update_user_meta($customer_id, 'practitioner_license_number', $pln);
}
}
add_action('woocommerce_created_customer', 'reigel_woocommerce_checkout_update_user_meta', 10, 2);
practitioner-license-number is my custom field added using the woocommerce_form_field method. I modified the code at the link above, so that the function runs on woocommerce_created_customer and then in update_user_meta I'm trying to pass the customer ID so that it saves the meta to the user profile that is created.
Would appreciate help trying to solve this. Most of the questions/answers on this subject assume that the user is logged in and already has an account, which is not the case here.
From the code you share, I think the problem lies in incorrectly passing to the $_POST,
perhaps practitioner_license_number vs practitioner-license-number.
You can use the code below to see if your hook works, if the value is written in the database you know that the problem is indeed elsewhere.
It might help to share the code you used for the custom fields too?
function action_woocommerce_created_customer( $customer_id, $new_customer_data, $password_generated ) {
$pln = 'test';
update_user_meta( $customer_id, 'practitioner_license_number', $pln);
}
add_action( 'woocommerce_created_customer', 'action_woocommerce_created_customer', 10, 3 );

Wordpress - Change forum role from outside bbPress by checking user status

I would like to check the user status and update their bbPress forum role accordingly. (Not the Wordpress role.)
The purpose is to add functionality to the BP-Registration-Options plugin that moderates user registration (In BuddyPress. Currently the plugin sets the user status to 69 while the user is unapproved, and blocks access to BuddyPress functionality. However, the user is still able to login.
When they log-in, bbPress automatically sets the user forum role according to your setting in the back end. In this case it is set to 'spectator'. When the user is approved by the admin their status changes and I want it to also update the bbPress role to 'participant'.
Here is my first attempt:
function bp_registration_options_additional() {
if ( is_user_logged_in() ) {
$user_ID = get_current_user_id();
$user = get_userdata( $user_ID );
if (69 !== $user->user_status ) {
// Here is where I need help.
//How to set the bbPress forum role to 'Participant'?
}
}
}
add_action( 'wp_loaded', 'bp_registration_options_additional' );
Thanks!
WP: 3.8
bbPress: Version 2.5.2
EDIT: A bit of additional information. The meta_key for the forum roles is: wp_capabilities. The meta_value of a user with the forum role 'spectator; is: a:2:{s:10:"subscriber";b:1;s:13:"bbp_spectator";b:1;}
Had the same requirement - to update the wp_capabilities field -
$wp_user_capabilities_arr = array(
"subscriber" => true,
"bbp_participant" => true
);
update_user_meta($wp_user_id, "wp_capabilities", $wp_user_capabilities_arr);
And after update the data looks like:
a:2:{s:10:"subscriber";b:1;s:15:"bbp_participant";b:1;}

Wordpress Private/Public Posts Security.

I have a quick question to ask.
I've setup a wordpress site with custom theme that has the functionality to set posts "Private/Public" where as you can guess all post marked as private can only be seen by users who are logged in, and public everyone can see.
How I accomplished this was using a custom field "access" and each post can set this custom field to private or public in the edit post screen. Then to display these posts I run a custom loop query with a "is_user_logged_in()" conditional statement. It that statement is true I include all posts with the "access" fields set to both "private/public" and if the statement fails ie the user is not logged in only include posts with "access" set to public. I have used similar loop queries for all single page loops etc.
Now while this works a treat I have concerns over how secure this approach is. Thats were your help comes in. How secure do you think this is? Would it be easy to trick the loop into displaying private post to a user thats not logged in? Can you reccommed a better more secure way of handling private/public posts that can be set by a select number of users on the backend?
ideas much appreciated.
Rob.
maybe I understood all wrong , but -
What You describe is just like the wordpress Default behavior for private posts .
Hence , I do not really understand wh you need a custom field for that .
Custom Fields have the habit of being [ab]used for everything, even if not needed :-)
That being said ,you can use the post_status() function to check for your status
if ( get_post_status ( $ID ) == 'private' )
{
// this is 'private';
}
else
{
// this is public 'public';
}
So you could use
get_post_status ( get_the_ID() )
or if you want to put it at the head of the loop after the the_post() part:
if( get_post_status()=='private' ) continue;
you could wrap it also with is_user_logged_in() if you want .
Point is , there is already a default place in wordpress where "private" is defined . so there is no need to define it elsewhere ( like custom field ).
You can even create your own custom post status with register_post_status() ..
the best way IMHO however , is to filter all the posts on the posts_where
add_filter('posts_where', ' privates_control');
function privates_control($where) {
if( is_admin() ) return $where;
global $wpdb;
return " $where AND {$wpdb->posts}.post_status != 'private' "; // or add your custom status
}
This function simply mofifies the query using the posts_where filter. Codex Link
You can modify it to your needs (add / remove conditions / user levels / user control

How to know the role of current user in WordPress?

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); ?>

Resources