Allow checkout without login for existing users only (woocommerce) - woocommerce

I'm trying to find a solution that will allow paying for an order without login for registered users only. Guests must not be able to pay for the order. I have already found some snippets which link orders if email exists or create a new account if not. I would like to simplify the purchase process for existing users but still avoid guest checkout for new customers.
Here is the code which I have already tried (it works to link orders to existing customers, but I would like to prevent guest checkout and new account creation during checkout). Actually there is no need to login users. I would like to simply allow to complete the order in case if the user (email or use ID) exists and decline if user do not exists.
`
//assign user in guest order
add_action( 'woocommerce_new_order', 'action_woocommerce_new_order');
function action_woocommerce_new_order( $order_id ) {
$order = new WC_Order($order_id);
$user = $order->get_user();
if( !$user ){
//guest order
$userdata = get_user_by( 'email', $order->get_billing_email() );
if(isset( $userdata->ID )){
//registered
update_post_meta($order_id, '_customer_user', $userdata->ID );
}else{
//Guest
}
}
}
`

Related

Choose Agent Field only set when user role is sales agent at Woocommerce Checkout

I am using B2b sales Agent Plugin for woocommmerce. The issue is, As guest user to checkout, they dont want to choose the agent. They want to buy directly without sales agent.
But as the sales agent roles, They need to chose the own sales agent user during checkout. Since, the sales agent should enable this field in order to get track the order from spesific sales agen.
The question is
How to unset the 'Choose agent' Field during the checkout is guest user.
How to automatically assigned to the specific sales agent, when the sales agent is currently log in, then buying the product on behalf of customer without to choose the sales agent field.
I try this code but critical error, i try to see the b2b sales agent documentation from B2b Sales Agen Documentation, but cannot solved
Here is the code snippet:
//edit checkout field b2b
add_filter( 'woocommerce_admin_billing_fields' , 'custom_override_b2b' );
function custom_override_b2b( $fields ) {
$user = wp_get_current_user();
if ( !in_array( 'sales_agent', (array) $user->roles ) ) {
unset($fields['wcb2bsa_sales_agent']['wcb2bsa_sales_agent']);
);
}
return $fields;
}
Thank you for helping me.
The Choose Sales agent at checkout
Please try this code, i remove wrong syntax ( additional ");" ) and add user check:
add_filter( 'woocommerce_admin_billing_fields' , 'custom_override_b2b' );
function custom_override_b2b( $fields ) {
$user = wp_get_current_user();
if(!$user){
return $fields;
}
if ( !in_array( 'sales_agent', (array) $user->roles ) ) {
unset($fields['wcb2bsa_sales_agent']);
}
return $fields;
}

How to segregate the Buddypress member page on multisite?

I have a BuddyPress social networks in a multi network WordPress install (WordPress multisite), thanks to LH Buddypress Multi Network plugin.
How can I prevent people from accessing to a profile page from another blog?
For example :
teacherSite, teacherUser
studentSite, studentUser
I have restricted access to site for non-member.
teacherUser can only connect on teacherSite.
And he can’t see in the directory other users from others blogs.
If studentUser knows the teacherUser username or if he finds or tests…
He can go to:
studentSite.domain.com/members/teacherUser/
And he can see the profile of teacherUser even though teacherUser is not linked to studentSite.
Fortunately, there is no information (because everything else is well segregated) except the name and the gravatar.
But he can still make a connection request or send him a private message!
teacherUser will not see any notification on teacherSite. But he will potentially receive an email which will redirect him to studentSite without being able to connect to it.
How to avoid this?
I'm guessing BuddyPress has somewhat the same user management system as WordPress.
We could compare the current user role with the queried user role. If they're different, we block and redirect.
<?php
/**
* Compare the queried user role with the current user role.
* If both don't match restrict profile access and redirect to current user profile.
*
* Case exceptions:
* - IF the current user IS the queried user.
* - IF the current user IS an Admin or Super-Admin.
*/
add_action( 'wp', function() {
if ( is_author() && get_queried_object() instanceof \WP_User ) {
if ( reset( get_queried_object()->roles ) === reset( wp_get_current_user()->roles ) || get_current_user_id() === get_queried_object_id() || current_user_can( 'manage_options' ) ) { // ... #see https://wordpress.org/support/article/roles-and-capabilities/#capability-vs-role-table
return;
} else {
header( 'Refresh: 2; ' . esc_url( get_author_posts_url( get_current_user_id() ) ) );
$args = array(
'back_link' => true,
);
wp_die( "Error, Restricted access. You're not allowed to view this profile.", 'Error, Restricted access', $args );
};
};
} );

How Can I add Email Verification Functions For WooCommerce

I would like to add Email verification procedure when user registers in WooCommerce. WordPress then emails a verification link to user's email. If link is clicked, it then activates the user's account. How would I do that?
I have used the code provided by Amit Kayshap and refined it to include extra checks and functions like automatically logging a user in after their account has been activated, resulting in a much smoother user experience.
Update: Unlike the original code, this one will not require any existing user to confirm their email address as well.
Like the code I based it upon, it is designed to run on a WordPress installation running WooCommerce. It also works if you have disabled the standard WordPress registration page.
You'll need an empty page with the URL yoursite.com/verify/ that builds on a template that contains <?php wc_print_notices(); ?> within its content container. It'll replace the /sign-in/ destination from the original code and will handle almost all messages created by this code.
Next, add this code to your theme's functions.php:
function wc_registration_redirect( $redirect_to ) { // prevents the user from logging in automatically after registering their account
wp_logout();
wp_redirect( '/verify/?n=1'); // redirects to a confirmation message
exit;
}
function wp_authenticate_user( $userdata ) { // when the user logs in, checks whether their email is verified
$has_activation_status = get_user_meta($userdata->ID, 'is_activated', false);
if ($has_activation_status) { // checks if this is an older account without activation status; skips the rest of the function if it is
$isActivated = get_user_meta($userdata->ID, 'is_activated', true);
if ( !$isActivated ) {
my_user_register( $userdata->ID ); // resends the activation mail if the account is not activated
$userdata = new WP_Error(
'my_theme_confirmation_error',
__( '<strong>Error:</strong> Your account has to be activated before you can login. Please click the link in the activation email that has been sent to you.<br /> If you do not receive the activation email within a few minutes, check your spam folder or click here to resend it.' )
);
}
}
return $userdata;
}
function my_user_register($user_id) { // when a user registers, sends them an email to verify their account
$user_info = get_userdata($user_id); // gets user data
$code = md5(time()); // creates md5 code to verify later
$string = array('id'=>$user_id, 'code'=>$code); // makes it into a code to send it to user via email
update_user_meta($user_id, 'is_activated', 0); // creates activation code and activation status in the database
update_user_meta($user_id, 'activationcode', $code);
$url = get_site_url(). '/verify/?p=' .base64_encode( serialize($string)); // creates the activation url
$html = ( 'Please click here to verify your email address and complete the registration process.' ); // This is the html template for your email message body
wc_mail($user_info->user_email, __( 'Activate your Account' ), $html); // sends the email to the user
}
function my_init(){ // handles all this verification stuff
if(isset($_GET['p'])){ // If accessed via an authentification link
$data = unserialize(base64_decode($_GET['p']));
$code = get_user_meta($data['id'], 'activationcode', true);
$isActivated = get_user_meta($data['id'], 'is_activated', true); // checks if the account has already been activated. We're doing this to prevent someone from logging in with an outdated confirmation link
if( $isActivated ) { // generates an error message if the account was already active
wc_add_notice( __( 'This account has already been activated. Please log in with your username and password.' ), 'error' );
}
else {
if($code == $data['code']){ // checks whether the decoded code given is the same as the one in the data base
update_user_meta($data['id'], 'is_activated', 1); // updates the database upon successful activation
$user_id = $data['id']; // logs the user in
$user = get_user_by( 'id', $user_id );
if( $user ) {
wp_set_current_user( $user_id, $user->user_login );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $user->user_login, $user );
}
wc_add_notice( __( '<strong>Success:</strong> Your account has been activated! You have been logged in and can now use the site to its full extent.' ), 'notice' );
} else {
wc_add_notice( __( '<strong>Error:</strong> Account activation failed. Please try again in a few minutes or resend the activation email.<br />Please note that any activation links previously sent lose their validity as soon as a new activation email gets sent.<br />If the verification fails repeatedly, please contact our administrator.' ), 'error' );
}
}
}
if(isset($_GET['u'])){ // If resending confirmation mail
my_user_register($_GET['u']);
wc_add_notice( __( 'Your activation email has been resent. Please check your email and your spam folder.' ), 'notice' );
}
if(isset($_GET['n'])){ // If account has been freshly created
wc_add_notice( __( 'Thank you for creating your account. You will need to confirm your email address in order to activate your account. An email containing the activation link has been sent to your email address. If the email does not arrive within a few minutes, check your spam folder.' ), 'notice' );
}
}
// the hooks to make it all work
add_action( 'init', 'my_init' );
add_filter('woocommerce_registration_redirect', 'wc_registration_redirect');
add_filter('wp_authenticate_user', 'wp_authenticate_user',10,2);
add_action('user_register', 'my_user_register',10,2);
If you are running a multilingual site, you can make the code translation-ready very easily. Just change the text strings like this: __( 'Text you want to translate', 'your-theme' ) This allows translation plugins like WPML to add the string to a translation table in the your-theme text domain.
Note that any string containing a variable like .$url. will generate a new string every time a different user activates its function. To circumvent this (and prevent string spamming into your database), we can translate them directly in the code:
if(ICL_LANGUAGE_CODE=='de'){
wc_add_notice( __( 'German error message' ), 'error' );
} else {
wc_add_notice( __( 'English error message' ), 'error' );
}
In this example, the german message will be output if the user's language code is detected as de (Also works if it is a variation like de_DE_formal), else it will output the english message.
Edit: I updated the code to not require an existing user to retroactively confirm their email address.

How can I have users only see their content in Wordpress?

This goes beyond posts and media. I have several CPT's and a calendar. Is there a way to have wordpress check the user name and only show content they have created?
In the backend, to filter all post types that are shown and restrict the visualization you can use pre_get_posts.
add_action( 'pre_get_posts', 'users_own_content_so_12761756' );
/**
* Show only posts of the current user in the dashboard
* affects posts, pages, media and custom post types
*/
function users_own_content_so_12761756( $wp_query_obj )
{
// Restrict hook to the backend
if( !is_admin() )
return;
global $current_user;
get_currentuserinfo();
// http://php.net/manual/en/function.is-a.php
if( !is_a( $current_user, 'WP_User') )
return;
if( !current_user_can( 'administrator' ) )
$wp_query_obj->set( 'author', $current_user->ID );
}
After applying this code, you'll notice that the post count is not correct: it'll show the total count and not the user count. To adjust that, refer to this Q&A: Update post counts (published, draft, unattached) in admin interface.
You'll need to care about user roles and capabilities as well, blocking the rights to edit someone else's posts/pages/cpts. That's because a user can type in the browser address example.com/wp-admin/post.php?post=POST_ID&action=edit and access the post, if he/she has the rights to do so.
you can try adding this to the loop
<?php $author = get_the_author();
$current_user = wp_get_current_user();
if($author != $current_user->user_nicename) {
echo "permission denied";
break;
} ?>
I use the members plugin to create a custom-defined role for users.
http://wordpress.org/extend/plugins/members/

Access User Meta Data on User Registration in Wordpress

I am attempting to carry out a few functions when a user registers on a wordpress site. I have created a module for this which carries out the following function:
add_action( 'user_register', 'tml_new_user_registered' );
function tml_new_user_registered( $user_id ) {
//wp_set_auth_cookie( $user_id, false, is_ssl() );
//wp_redirect( admin_url( 'profile.php' ) );
$user_info = get_userdata($user_id);
$subscription_value = get_user_meta( $user_id, "subscribe_to_newsletter", TRUE);
if($subscription_value == "Yes") {
//include("Subscriber.Add.php");
}
echo "<pre>: ";
print_r($user_info);
print_r($subscription_value);
echo "</pre>";
exit;
}
But it seems that i am not able to access any user meta data as at the end of this stage none of it is stored.
Any ideas how i execute a function once Wordpress has completed the whole registration process of adding meta data into the relevant tables too?
I attempted to use this:
add_filter('user_register ','tml_new_user_registered',99);
But with no luck unfortunately.
Thanks in advance!
I read at the action reference api page that the user id is passed as user ID. Try substituting your $user_id for $user_ID.
I don't think the user metadata is available at the point where this action hook is triggered. From the Codex
"Not all user meta data has been stored in the database when this action is triggered. For example, nickname is in the database but first_name and last_name are not (as of 3.9.1). The password has already been encrypted when this action is triggered."

Resources