Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

WordPress

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:

<?php
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>";
        exit;
    }
?>

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?

Thanks!

2 Answers

Sean T. Unwin
Sean T. Unwin
28,660 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! :)