How to add more user data to URL - php

I need to add more user data to the URL. Currently, I am trying to add the $last_name string into my function, but I cant seem to get it right.
In the future, we might add more info into the URL depending on the user registering.
Please check the code below:
P.S. I got the base of the function here on Stackoverflow, however not sure which link. I have made changes to the function to suit my needs.
It is successful in pulling the first name.
function add_userid_page_url(){
$user_info = get_userdata(get_current_user_id());
$first_name = $user_info->first_name;
$last_name = $user_info->last_name;
if( is_user_logged_in() && is_page('my-account') && !isset( $_GET['fname'] ) ) : //Check User Logged In and Account Page and User Info not set in URL
wp_safe_redirect( add_query_arg('fname', $first_name, get_permalink() ) );
endif; //Endif
}
add_action('template_redirect', 'add_userid_page_url');

Just an update.
I figured out a way to add userinfo into URL structure.
For incase anyone needs it in future
<?php
function add_userid_page_url(){
$user_id = get_current_user_id();
$user_info = get_userdata($user_id);
$logged_in = array (
$first_name = $user_info->user_firstname,
$last_name = $user_info->user_lastname,
$email_address = $user_info->user_email,
);
if( is_user_logged_in() && is_page('my-account') && !isset( $_GET['user_details'] ) ) : //Check User Logged In and Page and User Id not set in URL
wp_safe_redirect( add_query_arg( 'user_details', $logged_in, get_permalink() ) );
endif; //Endif
}
add_action('template_redirect', 'add_userid_page_url');
?>

Related

Prevent site navigation for a user who has not agreed to the terms

Tring to prevent a logged in user from navigating the site if he has not approved the terms of use.
Terms of use is a checkbox that it's value is saved as user meta field.
I get ERR_TOO_MANY_REDIRECTS
add_action('template_redirect', 'confirmation_of_terms');
function confirmation_of_terms(){
$current_user_id = get_current_user_id();
if( $current_user_id > 0 ){
$permission = get_user_meta( $current_user_id, 'approval_of_regulations' , true );
if( empty( $permission ) ){
wp_redirect( 'example.com/welcome');
exit;
}
}
}

Pre-fill Woocommerce login fields with URL variables saved in session

I am using "Pre-fill Woocommerce checkout fields with Url variables saved in session" answer code, trying to populate Woocommerce login username and password with variables saved in session.
This is my customized code in functions.php so far:
// Save user data from URL to Woocommerce session, this works fine
add_action( 'template_redirect', 'set_custom_data_wc_session' );
function set_custom_data_wc_session () {
if ( isset( $_GET['sliced_client_email'] ) || isset( $_GET['tu_name'] ) ) {
$email = isset( $_GET['sliced_client_email'] ) ? esc_attr( $_GET['sliced_client_email'] ) : '';
$pw = isset( $_GET['password'] ) ? esc_attr( $_GET['password'] ) : '';
// Set the session data
WC()->session->set( 'custom_data', array( 'email' => $email, 'password' => $pw ) );
}
}
// Autofill checkout fields from user data saved in Woocommerce session, this is my problem
add_filter( 'woocommerce_login_form' , 'prefill_login_fields' );
function prefill_login_fields ( $xxx ) {
// Get the session data
$data = WC()->session->get('custom_data');
// Email
if( isset($data['email']) && ! empty($data['email']) )
$xxx['username']['default'] = $data['email'];
// Password
if( isset($data['password']) && ! empty($data['password']) )
$xxx['password']['default'] = $data['password'];
}
But of course I can't find the parameters to populate. On the checkout page there is $address_fields['billing_email'] but I can't find a similar parameter for the login page. Not sure what to put in $xxx and $xxx['username']['default'] and $xxx['password']['default'].
Thanks for the help!!
Alright so instead of using variables stored in session, I found a simple jQuery solution.
add_action('woocommerce_login_form','woocommerce_js_2');
function woocommerce_js_2()
{ // break out of php
?>
<script>
// Setup a document ready to run on initial load
jQuery(document).ready(function($) {
var r = /[?|&](\w+)=(\w+)+/g; //matches against a kv pair a=b
var query = r.exec(window.location.href); //gets the first query from the url
while (query != null) {
//index 0=whole match, index 1=first group(key) index 2=second group(value)
$("input[name="+ query[1] +"]").attr("value",query[2]);
query = r.exec(window.location.href); //repeats to get next capture
}
});
</script>
<?php } // break back into php

Authenticate out WP to get current user

I am trying to get user detail out side wordpress file (But same server) and for that I am using this code
<?php
define( 'WP_USE_THEMES', false ); // Do not use the theme files
define( 'COOKIE_DOMAIN', false ); // Do not append verify the domain to the cookie
define( 'DISABLE_WP_CRON', true ); // We don't want extra things running...
//$_SERVER['HTTP_HOST'] = ""; // For multi-site ONLY. Provide the
// URL/blog you want to auth to.
// Path (absolute or relative) to where your WP core is running
require("/var/www/yourdomain.com/htdocs/wp-load.php");
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
} else {
$creds = array();
// If you're not logged in, you should display a form or something
// Use the submited information to populate the user_login & user_password
$creds['user_login'] = "";
$creds['user_password'] = "";
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error( $user ) ) {
echo $user->get_error_message();
} else {
wp_set_auth_cookie( $user->ID, true );
}
}
if ( !is_wp_error( $user ) ) {
// Success! We're logged in! Now let's test against EDD's purchase of my "service."
if ( edd_has_user_purchased( $user->ID, '294', NULL ) ) {
echo "Purchased the Services and is active.";
} else {
echo "Not Purchased";
}
}
?>
but it doesn't worked, I am creating custom dashboard out wp, which user wp info, as back-end. So please tell me what wrong am i doing? Any help is highly appreciated.
Since you are using easy-digital-downloads be sure it was included
if ( !function_exists( 'edd_has_user_purchased' ) ) {
require_once 'path-to-plugin/user-functions.php';
}
In your if ( !is_wp_error( $user ) ) statement you can use
echo "<p>ID: ".$user->ID;
echo "<p>Name: ".$user->data->display_name;
echo "<p>Login: ".$user->data->user_login;
echo "<p>Email: ".$user->data->user_email;
echo "<p>URL: ".$user->data->user_url;
echo "<p>Registered: ".$user->data->user_registered;
to show user wp info.
Try
print_r($user);
to overview all accessible fields

Redirect if it's not certain user - wordpress

I have created a page for a certain user in wordpress. Let's say his username is John. I am looking for PHP script that allow only 'John' to access that page and if users with different username other than 'John' tries to access the page they are redirected to another page.
I am new to PHP, so here's some code I have tried. But it redirects all users, even the user with username 'John'
<?php $user_info = get_userdata(1);
$username = $user_info->user_login;
if ( $username=='John' ) {
echo '';
} else {
wp_redirect( home_url() );
exit;
}
?>
Here's a wordpress page with parameters to get userdata - https://codex.wordpress.org/Function_Reference/get_userdata
You can use wp_get_current_user() function instead.
global $current_user;
get_currentuserinfo();
$username = $current_user->user_login;
if ( $username == 'John' ) {
echo '';
} else {
wp_redirect( home_url() );
exit;
}
This may solve your problem.
add_action( 'init', 'blockusers_init' );
function blockusers_init() {
global $current_user;
$current_user = wp_get_current_user();
if ( 'John' == $current_user->user_login ) {
//your desire page url
wp_redirect( 'your page url' );
exit;
} else {
wp_redirect( home_url() );
exit;
}
}
Take reference from
add_action( 'init', 'blockusers_init' );
function blockusers_init() {
if ( is_admin() && ! current_user_can( 'administrator' ) &&
! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
wp_redirect( home_url() );
exit;
}
}
https://premium.wpmudev.org/blog/limit-access-to-your-wordpress-dashboard/
Try this : First check if user is logged_in if yes then take the user information and do what ever you want with it
if(is_user_logged_in()){
$current_user = wp_get_current_user();
if($current_user->user_login == "John"){
wp_safe_redirect("Where ever you want");
exit;
}
else
wp_safe_redirect(home_url('/'));
NOTE : Make sure to check your username in database , I set my username as my lastname.

Redirect to billing address setup page if the user metadata is not set

I want to make sure that all customers who register on my WordPress (with WooCommerce) site fill up their billing information before doing anything else.
Whenever customers login for the first time, filling up the billing information should be the first thing they do.
To do this, I added the following code in my themes's function.php:
add_action( 'wp', 'is_billing_address_set' );
function is_billing_address_set()
{
$curr_url = $_SERVER['PHP_SELF'];
if(is_user_logged_in ()){
if(strstr($curr_url, 'my-account/edit-address/billing') == false){
$current_user_id = get_current_user_id ();
$billing_country = get_user_meta ($current_user_id, 'billing_country', true);
if($billing_country == null || $billing_country == false || $billing_country == ""){
wp_redirect( 'https://localhost/my-account/edit-address/billing/' );
}
}
}
}
I know this is a wrong approach since it will create an infinite redirect loop.
In my wp_redirect function I am hard coding the absolute URL so I will have to change this code everytime my server location changes.
How can I solve this problem correctly?
---- (update) : This is tested and work perferctly
Finally you don't need any hook to do what you want, you just need to paste this snippet in your function.php file. With this approach, you will prevent:
Infinite redirect loop
Hardcoding the absolute URL
Simplified condition with empty()
Url errors on multi language website
I have test it, and it works just perfectly:
if(is_user_logged_in ()){
// Queried URL
$curr_url = home_url(add_query_arg(array(),$wp->request));
// localisable "Edit billing information" path
$edit_billing_path = __('/my-account/edit-address/billing', 'woocommerce');
// Target URL
$targ_url = home_url($edit_billing_path);
if ( !strstr($curr_url, $targ_url) ) {
$user_id = get_current_user_id ();
$billing_country = get_user_meta ($user_id, 'billing_country', true);
if ( empty( $billing_country ) ) {
wp_redirect( $targ_url );
}
}
}
With this little piece of code you can avoid, as you want, logged user to do anything until they have filled and completed their billing information.
You can also use multiple conditions based on different billing fields to redirect user. This way each field has to be filled and completed. This is just an example, and you can add, replace or remove any field to feet your needs:
if(is_user_logged_in ()){
// Queried URL
$curr_url = home_url(add_query_arg(array(),$wp->request));
// localisable "Edit billing information" path
$edit_billing_path = __('/my-account/edit-address/billing', 'woocommerce');
// Target URL
$targ_url = home_url($edit_billing_path);
if ( !strstr($curr_url, $targ_url) ) {
$user_id = get_current_user_id ();
// Using multiple condition based on user multiple billing fields
$first_name = get_user_meta ($user_id, 'billing_first_name', true);
$last_name = get_user_meta ($user_id, 'billing_last_name', true);
$address = get_user_meta ($user_id, 'billing_address_1', true);
$city = get_user_meta ($user_id, 'billing_city', true);
$country = get_user_meta ($user_id, 'billing_country', true);
if ( empty( $first_name ) && empty( $last_name ) && empty( $address ) && empty( $city ) && empty( $country ) ) {
wp_redirect( $targ_url );
}
}
}
All code is tested and working.
References:
How to get the current URL using wordpress… (Getting current queried Url)
Codex: home_url() (An alternative to hard coded Url)
Using empty(), is_null(), isset() or array_key_exists() as conditions
Gettex - I18n for WordPress Developers (Localisable strings)
This is the solution for plain url permalink and for preserving admins to be redirected in backend...
maybe useful for those who don't get this working
if( is_user_logged_in () && !is_admin() ){
// interroghiamo l'url corrente
global $wp;
$curr_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//$curr_url = home_url(add_query_arg(array(),$wp->request));
// path per la localizzazione
$edit_billing_path = __('/myaccount/edit-address/fatturazione', 'woocommerce');
// Target URL
$targ_url = home_url($edit_billing_path);
if ( !strstr($curr_url, $targ_url) ) {
$user_id = get_current_user_id ();
$billing_city = get_user_meta ($user_id, 'billing_city', true);
if ( empty( $billing_city ) ) {
wp_redirect($targ_url);
//echo $targ_url;
//echo $curr_url;
}
}
}

Categories