Halloween Sale 15% off Ends in See the plans
PHP

Remove Ad Click IDs From Links in Your Content

Strips tracking parameters such as fbclid, gclid, msclkid and Mailchimp or HubSpot IDs from links in your posts (often pasted in by accident), so you do not pass your visitors' ad tracking along to other sites.

Don’t have WPIDE yet? Install it on your site

Code

// Query parameters removed from links.
$wpide_click_ids = array( 'fbclid', 'gclid', 'gbraid', 'wbraid', 'dclid', 'msclkid', 'yclid', 'igshid', 'mc_cid', 'mc_eid', '_hsenc', '_hsmi', 'ttclid', 'twclid', 'li_fat_id' );

add_filter( 'the_content', function ( $content ) use ( $wpide_click_ids ) {
    if ( ! preg_match( '/[?&](' . implode( '|', array_map( 'preg_quote', $wpide_click_ids ) ) . ')=/', $content ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
        return $content;
    }

    $tags = new WP_HTML_Tag_Processor( $content );

    while ( $tags->next_tag( 'a' ) ) {
        $href = (string) $tags->get_attribute( 'href' );
        if ( false !== strpos( $href, '?' ) ) {
            $clean = remove_query_arg( $wpide_click_ids, $href );
            if ( $clean !== $href ) {
                $tags->set_attribute( 'href', $clean );
            }
        }
    }

    return $tags->get_updated_html();
}, 20 );

Notes

UTM campaign tags are kept on purpose; add utm_source and friends to the list if you want those removed too.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.