WordPress Get Logged In User Info for Front End

Objective

Get logged in user information to use in javascript.

  • In order to use user information on the front end with Javascript or jQuery, you can use wp_localize_script
  • wp_localize_script creates a Javascript object that can be accessed by javascript.
    • function: wp_localize_script($handle, $nameOfObject, $dataStoredInObject)
    • $handle: script handle the data will be attached to
    • $nameOfObject: Name of Javascript Object
    • $dataStoredInObject: single or multi-dimensional array
    • Reference

Step 1: How to include wp_localize_script in a plugin

<?php

/**
 * Plugin Name: Bliksem Sandbox Plugin
 * Version: 1.0.0
 * Description: Sandbox development for
 * Author: Andre Nell
 * Author URI: http://www.simplifysmallbiz.com/
 *
 *
 * @package Bliksem
 * @author Andre Nell
 * @since 1.0.0
 */

if (!function_exists('get_option')) {
  header('HTTP/1.0 403 Forbidden');
  die; // Silence is golden, direct call is prohibited
}

// DEFINE CONSTANTS
define('BS_NAME_VERSION', '1.0.1');
define('BS_NAME_PLUGIN_URL', plugin_dir_url(__FILE__));

// IMPLEMENTATION
function bs_enqueue_bs_frontend_scripts()
{
    global $current_user;
    $current_user = wp_get_current_user(); 
    
    wp_register_script('bs-sandbox-js', BS_NAME_PLUGIN_URL . 'js/sandbox.js', array('jquery'), '1.0.0', true);
    wp_enqueue_script('bs-sandbox-js');

    wp_localize_script('bs-sandbox-js', 'theUser', array(
        'roles' => $current_user->roles,
    ));

}
add_action('wp_enqueue_scripts', 'bs_enqueue_bs_frontend_scripts');

Step2: How to access the data stored in the Javascript Object created in Step 1

jQuery(window).load(function ($) {
    var user_roles = theUser.roles;
    console.log(user_roles);
    if (jQuery.inArray("Subscriber", user_roles)) {
        console.log("is in array");
    } else {
        console.log("is NOT in array");
    }
});