Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Gary Stewart
Gary Stewart
14,142 Points

Escaping echo'd Javascript within Wordpress?

I have the following line of code within one of my Wordpress sites which works great:

if (!is_user_logged_in()){
        echo "<script>alert('You must be logged in to place a vote!');window.location='http://localhost/wordpress/log-in/';</script>";

I am now escaping data before the sites launch and am wondering the best way to escape the Javascript here for security, I am aware of the esc_js() function but am not sure how best to implement it?


2 Answers

Sean T. Unwin
Sean T. Unwin
28,688 Points

I would suggest using wp_localize_script. You will have to put your alert code into a .js file (and register or enqueue it first) though and possibly add a trigger (boolean), or some other method, so that wp_localize_script() can pass a value to a variable in order to show the alert.

In this tutorial example, it is recommending to pass the alert string using this function so that it may translated if need be, which is a good practice, as well.

Gary Stewart
Gary Stewart
14,142 Points

Is it necessary to escape this if it is hard coded within a page php template? Nothing is getting called from the database or inputted to alter the code written within the file?

Excuse my new learning on this area! :)