Wordpress Signed On User Lost - wordpress

I programmatically log in a user in Wordpress (before headers are sent), using a session variable from a previous page. Later in this same page, in the body section, I var_dump: wp_get_current_user(). This returns the WP_User I logged in with. In the 'log in' section I have tried combinations of wp_signon(), wp_set_current_user() and wp_set_auth_cookie().
The problem comes, when I navigate away from this page, the user isn't logged in anymore. When I use wp-login.php, the user stays logged in. I've struggled with this for quite a while and can't seem to find, why the user won't stay logged in.
Can someone help please. I'll add snippets of currently used code below:
$creds = array(
"user_login" => $_SESSION['email'],
"user_password" => $newPass,
"remember" => true
);
$user = wp_signon( $creds );
if ( is_a( $user, 'WP_User' ) ) {
wp_set_current_user( $user->ID, $user->user_login );
wp_set_auth_cookie( $user->ID, true );
}
// Code follows ...
<body>
<?php if ( is_user_logged_in() ) var_dump(wp_get_current_user()); ?>

Where is it being executed? You'll need to put it in an action. Use:
add_action('theme_setup','your_code');
function your_code(){
//signin code block goes here
};

I eventually moved a segment of the code to another file. Something I failed to include was that I used wp_create_user on the same page. As soon as I replaced wp_set_current_user and wp_set_auth_cookie with wp_signon and moved it to a separate page, everything worked perfectly.

Related

Redirecting using comment_post_redirect WordPress filter causes errors

I'm using the comment_post_redirect filter to redirect users to a custom page after a comment is submitted. The code works, but every now and then a user is not redirected and they get an error.
Here's my code:
function feedback_submitted_redirect( $location, $comment )
{
$location = get_site_url() . '/feedback-validation?commentid=' . $comment->comment_ID;
if_debug_logger( 'Redirecting to feedback validation', array('comment_id' => $comment->comment_ID, 'comment_author' => $comment->comment_author, 'url' => $location) );
return $location;
}
add_filter( 'comment_post_redirect', 'feedback_submitted_redirect', 11,2 );
Getting any helpful feedback from users as to what exactly is happening has been almost impossible and I'm unable to replicate the issue on both the dev and live sites, which makes fixing the problem a lot harder. There are also no errors in the debug.log or the logs in the public_html folder.
After adding some debugging info to the log, I can see that the redirect function always run, but every now and then users don't arrive on the redirection page.
I believe the error they're getting is the 500 server error as one of the users said it was an 'internal server error' (although, I'd think this would be logged in the error logs). Which makes me think the redirect is probably taking too long and it's being cut out.
I can't see anything in the code though that could cause an issue. I'm just returning a new location.
Any ideas as to what could cause an issue here? I've tried searching for possible causes but none seemed to be related.
Is it possible that the second argument ($comment) is not being set therefore causing an issue when I try to access its properties? I am going to add some checks to the function, just in case, but I can't think of any possible scenarios where the $comment won't be set as the filter is run after the comment is inserted into a db:
function feedback_submitted_redirect( $location, $comment )
{
if( isset( $comment ) && !empty( $comment->$comment_ID ) ) {
$location = get_site_url() . '/feedback-validation?commentid=' . $comment->comment_ID;
if_debug_logger( 'Redirecting to feedback validation', array('comment_id' => $comment->comment_ID, 'comment_author' => $comment->comment_author, 'url' => $location) );
}else{
if_debug_logger( 'Redirection to feedback failed', array( 'url' => $location ) );
}
return $location;
}
add_filter( 'comment_post_redirect', 'feedback_submitted_redirect', 10,2 );
Could it be that there is some content being outputted somewhere, causing the 'Headers already sent' error? Or could the server be running out of memory?
I guess I'm just trying to find any possible causes, so I can test for them and hopefully get to the bottom of this

Wordpress plugin form submitting to database on every browser refresh

I am developing a wordpress plugin, backend is working as I need but I am facing issue in frontend, I have created a shortcode page from I am posting few values to next page but when I refresh the next it is sending values to database again and again. I want to stop it, here is function:
function technician_checklist_report_generated(){
global $current_user;
global $wpdb;
$submit="";
if($_POST['customerid']!=""){
$crow = $wpdb->get_row( 'SELECT customer_id, firstname, lastname, createdon, marina, vesselmodel, vesselname, vesselyear
FROM wp_yacht_customers
WHERE customer_id= '.$_POST['customerid']
);
}
if($crow->customer_id!=""){
$table = 'wp_yatch_vessel_config_checklist';
array_pop($_POST); // delete last element in post array (submit)
$data = $_POST;
$format;
$wpdb->insert( $table, $data, $format );
}
require(dirname(__FILE__) .'/view/technician-start-reporting.php');
}
add_shortcode('technician-start-reporting',
'technician_checklist_report_generated');
When I reach to technician-start-reporting page it is sending data to MySQL again and again on browser refresh.
Is there any other way to go another page because I used wp_redirect and it showing error "header already sent... :
You can only use wp_redirect before content is sent to the browser.
Rather than process the form in the template[insite shortcode], you can hook an earlier action, like wp_loaded (this will be triggered before headers being sent).
<?php
add_action( 'wp_loaded', 'wpv_process_form' );
function wpv_process_form(){
if( isset( $_POST['customerid'] ) ):
// process form, and then
wp_redirect( get_permalink( $pid ) ); // redirect to desired page id
exit();
endif;
}
this way you'll be using less queries too.

How to display a user's avatar by user-id in wordpress via shortcode?

I've looked through lots of documents, few of them showed a shortcode to display the avatar using user_id.
The closest one is from Github, and it displays the current logged-in user, like this:
<?php
function shortcode_user_avatar() {
if(is_user_logged_in()) { // check if user is logged in
global $current_user; // get current user's information
get_currentuserinfo();
return get_avatar( $current_user -> ID, 24 ); // display the logged-in user's avatar
}
else {
// if not logged in, show default avatar. change URL to show your own default avatar
return get_avatar( 'http://1.gravatar.com/avatar/ad524503a11cd5ca435acc9bb6523536?s=64', 24 );
}
}
add_shortcode('display-user-avatar','shortcode_user_avatar');
?>
But this isn't enough, what I want is to add a parameter for me to choose the userid, and it will end like this:
[display-user-avatar id="user-id"]
Can anybody show me the way to make it?
Thanks!
I've already solve this problem, here is the code:
function shortcode_user_avatar($atts, $content = null) {
extract( shortcode_atts(
array('id' => '0',), $atts
)
);
return get_avatar( $user_id, 96 ); // display the specific user_id's avatar
}
add_shortcode('avatar','shortcode_user_avatar');
Just paste it to theme's functions.php and enter the shortcode [avatar id="xxx"], and replace "xxx" to the user id.
It's actually my first shortcode, and I'm really happy that it's working!

Send custom refereal code to registration in WordPress

I'm passing a referral code that I'm saving to wp_usertmeta with a custom field added in functions.php
So far, so good!
Link to wp register: wp-login.php?action=register&ref=2
I save the referral code with:
<?php $ref = $_GET['ref']?>
It works BUT, if i enter a username thats already taken i get the standard error message from WordPress that it's taken.
When this happens the URL reloads to: wp-login.php?action=register and i cant use $_GET['ref']
Is there any alternative way to do this?
The easiest way to solve this would be to save the $_GET['ref'] value to a cookie or the PHP session. Once the user is registered, you can refer to the cookie/session to save to the database using the user_register action hook. Once it is saved, you should clear this value if it is a cookie unless it is needed for something else to reduce the size of each request.
//set the cookie
if ( isset( $_GET['ref'] ) ){
setcookie( "ref", $_GET['ref'] );
}
Then save the value using the action hook
add_action( 'user_register', 'my_user_register' );
function my_user_register( $user_id ){
if ( isset( $_COOKIE['ref'] ) ){
// save the ref to the user meta
update_user_meta( $user_id, 'ref', $_COOKIE['ref'] );
// delete the cookie
setcookie( "ref", null, -1 );
}
}

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