Change links automatically to affiliate links

The code you found works if you’re using the Classic Editor. It takes POST data (as in, a POST HTTP request) and converts it before it enters the database. So, in addition to only updating a certain meta field, it also only works from the point you add the code forward. Any old links aren’t affected.

Assuming you probably want to affect existing links as well as new ones, you can filter the_content instead. This will work in the Classic Editor too, but also with the Block Editor.

This should put you on the right path – you’ll just need to work out the right regular expression to identify an Amazon link’s query string. (If you already know that none of your Amazon links have query strings, you can skip the regular expression completely and just go ahead and do the str_replace() step.)

<?php
// Add a filter to `the_content`, which is called when pulling the post data out of the database
add_filter('the_content', 'wpse_357790_add_amazon_affiliate');
function wpse_357790_add_amazon_affiliate($content) {
    // See if "amazon.com" is found anywhere in the post content
    if(strpos($content, 'amazon.com') !== false) {
        // Capture all Amazon links and their query strings
        // TO DO: work out the correct regex here. This next line is not complete.
        preg_match_all('\?tag=[^&]+(&|")', $content, $matches);
        // Add the affiliate query string to each URL
        foreach($matches as $url) {
            $content = str_replace($url, $url . '?tag=myafftag-02', $content);
        }
    }
    // Always return the content, even if we didn't change it
    return $content;
}
?>

Benefits: will work with either editor, filters all post content, works on all content – already-published and not-yet-created.

error code: 523