How to display a username in jQuery( document ).ready?

451 Views Asked by At

I am using WordPress, I added some content after a div class, is it possible to display the logged-in username inside this document ready?

Here is my code. the shortcode not working inside jQuery, but it is working on a WordPress page, I already add the shortcode "[current_user]" to function.php.

jQuery( document ).ready(function($) {
$('.uap-account-affiliatelinks-tab2 :lang(zh-hans)').append('<div id="affiliate_student_referal"><span>Student Instruction Link: https:f-tutor.com/zh-hans/?ref=[current_user]); ?></span>;
});

1

There are 1 best solutions below

0
Hillel On

That [shortcode] only works on the back-end (PHP), in order to use it on the front-end (JavaScript/jQuery) you'll need to make that information available when the page is rendered - either by generating a JS constant with the username, or by setting an attribute to one of the page elements ( for example) and then read it with JS.

Option 1

Add to header.php:

<?php echo '<script>const USER_NAME="' . do_shortcode('[current_user]') . '";</script>'; ?>

Option 2

On header.php - add to <body> tag (usually before body_class()):

<body data-username="<?php echo do_shortcode('[current_user]'); ?>" <?php body_class(); ?>>

in jQuery use:

$("body").data("username");

Option 3

There is also a neat solution for your problem, suggested by another user here: https://stackoverflow.com/a/52981490/7013797