0

I am using two WordPress plugins - Snippets for inserting PHP code and Scripts n Styles for inserting JavaScript.

My goal is to take a logged-in user's email address and pre-populate a form.

The PHP code in Snippets is:

<?php
function get_user() {
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
}
add_action( 'init', 'get_user', 10 );
?>

The code in Scripts n Styles is:

<script type="text/javascript">
window.onload = function () {

var useremail = "<?php echo json_encode($user_email); ?>";

document.getElementsByName("ElementName")[0].value = useremail;
}
</script>

But instead of getting [email protected] I get the quoted text inserted into the form:

<?php echo json_encode($user_email); ?>

Any idea of what is going wrong or a better way to achieve the same result?

4
  • 1
    Is the code in script and styles rendered with php or is it just a javascript file? Commented Jan 29, 2018 at 17:30
  • JavaScript is embedded into the head element Commented Jan 29, 2018 at 17:33
  • It should work like expected, see 3v4l.org/ffDZf Commented Jan 29, 2018 at 17:46
  • The JS is embedded into the head, but the php code in the JavaScript will not be parsed. Scripts n Styles does not run PHP on the JavaScript string, just prints it out as is. Commented Jan 4, 2019 at 19:41

1 Answer 1

2

WordPress has a useful function to localize scripts to be passed from PHP to be used in JavaScript. This can be done by using the wp_localize_script() function before enqueueing the script.

Here is an example of this in use from the WordPress Codex. https://codex.wordpress.org/Function_Reference/wp_localize_script

Registering and enqueueing the script:

// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );

// Localize the script with new data
$translation_array = array(
    'some_string' => __( 'Some string to translate', 'plugin-domain' ),
    'a_value' => '10'
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );

// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );

Using that data in JavaScript:

// alerts 'Some string to translate'
alert( object_name.some_string);

Here is a good writeup on how this works: http://www.webtipblog.com/localize-scripts-in-wordpress-to-use-php-variables-in-javascript/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.