Skip to content
Public Ticket #2417

FYI: Sanitizing Google Analytics Code

Conversation thread

Peoples_Pundit replied

Customer Reply

Most welcome! I updated it to add two urls that helped us.

PenciDesign replied

Staff Reply

Hi,

Thank you for your feedback. We're appreciate that.

I will send that issues for our developers and tell with them to check and fixed itsmile.png No worries.

Best Regards,

PenciDesign

Peoples_Pundit started the conversation

Conversation Start

Hi folks,

\

Just wanted to let you know about an issue we ran into and show you how we fixed it. 

\

Basically, the function to sanitize the customizer setting for the Google Analytics code in "Footer Options" was stripping all the script tags because it was using wp_kses_post( $html ). That only allows tags default $allowed_tags for post content.

\

We had to create another function for the sanitizer.php file. It is as follows:

\
\
public function script_textarea( $script_textarea )\
    {\
        $allowed_html = array(\
            'script' => array(\
                'async' => array(),\
                'src' => array()\
            )\
        );\
        return wp_kses($script_textarea, $allowed_html);\
    }\
\

Then, in the 09-footer.php file, we changed the callback from 'html' to the following:

\
\
$wp_customize->add_setting( 'penci_footer_analytics', array(\
    'sanitize_callback' => array( $sanitizer, 'script_textarea' )\
) );\
\

We also noticed that the "section" assigned to the header code was the footer, not the header. In 03-header.php, we changed the following section to:

\
\
$wp_customize->add_control( 'custom_code_inside_head_tag', array(\
    'label'       => esc_html__( 'Add Custom Code Inside <head> tag', 'pennews' ),\
    'section'     => 'penci_panel_header',\
    'settings'    => 'custom_code_inside_head_tag',\
    'type'        => 'textarea',\
) );\
\

That also has to be sanitized for the allowed script tags.

\

Prior, it would echo out the analytics code minus the tags in the footer, which was visible below the footer to users/visitors.

These two urls were solid resources for this fix:

https://gist.github.com/ControlledChaos/a68997f4a348d447132033332a4e50f1

https://divpusher.com/blog/wordpress-customizer-sanitization-examples

Want to join this conversation or access attachments? Sign in first.