John Davidson

php - Assign WordPress current username value in a var in javascript

0 comments
Message:


I'm using livewebinar embed code and i'm try to pass the Current WordPress user name in Embed Javascript


Here is the code


<script type='text/javascript'>

var _options = {
'_license_key':'***-***-***',
'_role_token':'',
'_registration_token':'',
'_widget_containerID':'embedWidget',
'_widget_width':'100%',
'_widget_height':'100vh',
'_widget_nickname': I NEED TO PASS THE CURRENT WPUSER IN THIS PARAMETER, <<<<<<<-----------

}; .............. <script>

The goal is Get the Current Wordpress user name value and pass it inside _nickname parameter



My Answer:
You can achieve this by using the WordPress wp_localize_script function to pass the current user's username to your JavaScript code. Here's an example of how you can do this:

In your WordPress theme's functions.php file, add the following code:

php
function add_current_user_to_script() {
if (is_user_logged_in()) {
$current_user = wp_get_current_user();
wp_localize_script('your-script-handle', 'current_user', array(
'username' => $current_user->user_login
));
}
}
add_action('wp_enqueue_scripts', 'add_current_user_to_script');


Replace 'your-script-handle' with the handle of the script where you want to access the current user's username.

In your JavaScript code, you can now access the current user's username like this:

javascript
console.log(current_user.username);


This will output the current user's username in the browser console. You can then use this value in your Livewebinar embed code as needed.

Rate this post

3 of 5 based on 1813 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us