MonkeySee... MonkeySee... - 3 years ago 175
PHP Question

How to display post thumbnail with modified url in php?

I am using a WordPress content protection plugin with a feature that can watermark images when javascript is disabled on the browser. The feature is working on images within the post as follows...
Firstly it performs a redirect to a no-javascript php script when it detects the browser is not supporting javascript. Then it gets the content of the current post, matches any/all img src URLs within the content, modifies the img src URLs (so that the images are parsed via a php script that applies the image watermarking), then returns the post content with the modified URLs. All good.

However, most of the images that I wish to protect are set as featured images (aka post thumbnails), and thus are not part of the content. I'm not getting any support from the plugin author (paid plugin). So I'm looking to modify the plugin.

I am aware of wp_get_attachment_image_src() and the_post_thumbnail_url() as means of fetching the featured image URL. But I can't find any means of returning a modified featured image URL for the current post.

So what I am after is a small script that, for the current post/page, allows me to access the featured image URL and return a modified URL for display by the browser (same concept as for getting, modifying and returning the_content of a post). I don't want to be changing the image attachment details. Is it possible?

Please, no comments/discussion on the merits (or rather futility) of content/image protection. That's a different discussion altogether.

Thank you in advance for any support provided!!

Answer Source

It's impossible to understand your scenario, but at first glance it seems like you should look into the filter wp_get_attachment_image_attributes to modify a returning post-thumbnail url.

If we breakdown what you say:

But I can't find any means of returning a modified featured image URL for the current post.

Get the $attachment id/ post-thumbnail from scenario; in the loop/ or when is_feed() or is_single() or wherever, when-ever you need to protect the output. (cant help more without your context) Pass the image into the filter:

function change_or_filter_the_url($attr, $attachment, $size){
    if(is_admin()) return $attr;
    if($size != 'post-thumbnail') return $attr;
    $attr['src'] = ... do stuff with the url here ...
    return $attr;
add_filter('wp_get_attachment_image_attributes', 'change_or_filter_the_url', 10, 3);

But I guess its more than that to complete your answer. Take a look at this thread about Is it possible set a featured image with external image URL. It about the same objectives in a kind of way. You might get a point into right direction from all that code to approach an understandable question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download