1

What is the safe way to print tracking code / pixel code before </head> tag or </body> tag from theme options.

In header.php I printed the following code before the </head> tag

if ( get_theme_mod( 'before_head' ) !== '' ) {
    echo get_theme_mod( 'before_head' );
}

But user can add malicious script in before_head field.

How to output safe/escaped data?

0

It sounds like you're trying to implement a general purpose field for users to enter any kind of tracking code/JS into. This approach gives users the most flexibility but it means that you are trusting them to put whatever JavaScript that they want into the header and footer. By default, users need the administrator or super admin roles to edit theme options, so as long as your admins are trusted, this should be okay. WordPress will add slashes to the option values when they are saved, so use stripslashes() on the output.

Another approach would be to have a specific field for each script that you'd like to output. Have the user enter their ID/identifier/or whatever piece of unique information is required for a particular snippet. Then in your output function, concatenate and escape (using esc_js()) the user entered value into the boilerplate JS snippet. This is pretty rigid, but it would give you tight control over what the user is able to add to the site.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.