wordpressamazon-web-serviceswordpress-featured-image

Wordpress - How to modify URI of Featured image before it loaded


I'm using Wordpress 4.5. In an earlier time I used local server to store image (include Featured Image, for example: wp-content/uploads/2016/03/aaabbbccc.jpg). Now I want to move it to AWS S3 Bucket and Cloudfront, and I don't wanna make change in Wordpress's Database and decided to write a plugin to join my cloudfront domain (replace the current domain) to wp-content link every time it retrieve from Database, such as: https://xxyyzzqqaa.cloudfront.net/wp-content/uploads/2016/03/aaabbbccc.jpg.

I use an action hook in my plugin :

add_action( 'the_post', 'change_featured_image' );

Now I don't know what to do next ? Please give me some suggest, thanks in advance !


Solution

  • I found the solution for my problem, it's very easy but I'm newbies with WP so I can't see this.

    In your plugin, or where you wanna catch this event when WP load, add this filter:
    add_filter( 'post_thumbnail_html', 'change_featured_image' );
    With:

    I got some confusing in this function, I don't know the variable to get value. Finally , I found it in WP API document, every vars build-in filter use, you can use too.

    Here's the sample code:

    function change_featured_image($attr)
    {
    
        global $wpdb;
    
        $opt = get_option('s3dcs_status');//My value in `wp_options`
        if(empty($opt)) echo $attr;
        else{
            /// Preparing variables
            $pattern = '~(http.*\.)(jpe?g|png|[tg]iff?|svg)~i';
               $m = preg_match_all($pattern,$attro,$matches);
            $il = $matches[0][0];
            $tail = explode("wp-content", $il)[1];
            $s3dcs_remote_link = get_option('s3dcs_cfs3in') . "/wp-content" . $tail;
                   echo str_replace($il, $s3dcs_remote_link, $attr) ;
        }   
    }
    

    That's all. If you have an issue, please post in here to everyone can know.