Site icon Hip-Hop Website Design and Development

Change links automatically to affiliate links

My goal:

I want external links to shops I’m affiliated with (for example amazon) to automatically get the affiliate ID attached to it.

Example:

link I put in my blog post editor https://www.amazon.com/dp/B07K344J3N/

changes in frontend to https://www.amazon.com/dp/B07K344J3N/?tag=myafftag-02

What I have found:

The creator of the theme I’m using is offering something very close to what I’m looking for:

add_action('wpfepp_form_actions', 'link_change_custom');
function link_change_custom($data){
if ( !empty( $_POST['rehub_offer_product_url'] ) ) {

    $url = $_POST['rehub_offer_product_url'];

    $checkdomain = 'amazon.com';
    if (!empty($url) && strpos($url, $checkdomain) !== false) :

        $afftag = 'myafftag-02'; //our affiliate ID
        $affstring = 'tag='; // url parameter for affiliate ID

        if (parse_url($url, PHP_URL_QUERY)): //check if link has query string
            if (strpos($affstring, $url) !== false) : //check if link already has affiliate ID
                $url = preg_replace("/(".$affstring.").*?(z|&)/", "$1".$afftag."$2", $url);
            else:
                $url = $url.'&'.$affstring.$afftag;
            endif;   
        else:
            $url = $url.'?'.$affstring.$afftag;
        endif;

    endif;  

    update_post_meta( $data['post_id'], 'rehub_offer_product_url', esc_url($url) );
}     
}

The problem:

It only works on links that are stored in the field “rehub_offer_product_url”, but I want it to work on any links to amazon I put in the content of my blog posts.

I appreciate any help.