Skip to content

Instantly share code, notes, and snippets.

@hellofromtonya
Created April 29, 2021 17:16
Show Gist options
  • Save hellofromtonya/0845229fa9b7c26668cd2738e4150abd to your computer and use it in GitHub Desktop.
Save hellofromtonya/0845229fa9b7c26668cd2738e4150abd to your computer and use it in GitHub Desktop.
Testing script for WordPress Trac ticket 28020
<?php
namespace Test\trac28020;
/**
* Add this file into the wp-content/mu-plugins folder.
*/
add_action( 'init', function() {
// Bail out if in the backend (Admin area). Only want to run this in the frontend.
if ( is_admin() ) {
return;
}
$user_id = get_current_user_id();
$get_user_by = get_user_by( 'id', $user_id );
// Run only if you're logged in.
if ( false === $get_user_by ) {
return;
}
echo "<h2>Current user => you</h2>";
print_results( $get_user_by );
echo "<h2>Changing to a different user</h2>";
// UID for this demo should be a subscriber
$user_id = 2;
wp_set_current_user( $user_id );
// $GLOBALS['current_user'] now contains a WP_User instance
$get_user_by = get_user_by( 'id', $user_id );
$from_userdata = get_userdata( $user_id );
print_results( $get_user_by, $from_userdata );
echo "<h2>Changing different user to be an admin</h2>";
// $from_userdata now also contains a WP_User instance, but not the same one
// Fun times with desynchronisation:
$from_userdata->set_role( 'administrator' );
print_results( $get_user_by, $from_userdata );
// Restore the user back to subscriber.
$from_userdata->set_role( 'subscriber' );
exit;
});
function print_results( $get_user_by, $from_userdata = null ) {
$user_id = get_current_user_id();
echo "<p>Current user ID is: {$user_id}</p>";
printf( '<p>Has admin rights? %s</p>', current_user_can('administrator' ) ? '👍': '👎' );
?>
<table>
<thead>
<th>Object source</th>
<th>Object ID</th>
</thead>
<tbody>
<tr>
<td>get_user_by()</td>
<td><?php echo spl_object_id( $get_user_by ); ?></td>
</tr>
<tr>
<td>$GLOBALS['current_user']</td>
<td><?php echo spl_object_id( $GLOBALS['current_user'] ); ?></td>
</tr>
<?php if ( null !== $from_userdata ) : ?>
<tr>
<td>get_userdata()</td>
<td><?php echo spl_object_id( $from_userdata ); ?></td>
</tr>
<?php endif; ?>
</tbody>
</table>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment