0

I'm building a simple plugin that will allow us to add code to our site header by defining it on our settings page. However I haven't been able to make it allow scripts.

This is my current code:

public function sanitize( $input )
{
    $new_input = array();

    if( isset( $input['code'] ) )
        $new_input['code'] = sanitize_text_field( $input['code'] );

    return $new_input;
}

public function code_callback()
{
    printf(
        '<textarea type="text" id="code" name="pl-analytics[code]">%s</textarea>',
        isset( $this->options['code'] ) ? esc_attr( $this->options['code']) : ''
    );
}

How can this be done?

3
  • Look at sanitize_text_field(). The codex says it strips all tags. If you're trying to use the <script> tag (or any HTML tag for that matter) inside your text-area, it will strip it. Commented May 15, 2014 at 20:05
  • I see, is there a way to allow javascript without creating a vulnerability? / What should I look for if I created my own sanitising function? If you post your answer I will accept it! Commented May 15, 2014 at 20:24
  • You will always have a vulnerability if you allow JS. You should reconsider what your need is and if it could be accomplished in another way. Commented May 15, 2014 at 22:40

1 Answer 1

1

There's no way you can let JavaScript through without creating some kind of vulnerability. But the same is true of any filtering of inputs. As a developer you have to weigh up functionality against risk.

The wp_kses() function is probably what you're looking for. Have a read of Otto's post to learn more about it.

It's also on the Codex too.

Below is a rough example. Untested as I've strangely never had to add script tags before.

public function sanitize( $input )
{
    $new_input = array();

    $allowed = array(
        'script'    => array(
            'src' => array()
        )
    );

    if( isset( $input['code'] ) )
        $new_input['code'] = wp_kses( $input['code'], $allowed );

    return $new_input;
}

Your Answer

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

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