0
votes

Is it possible to modify the URLs of the image attachments for the current post, so that the browser receives html with modified URLs in the img tags?

I don't want to be updating the image attachment attributes.

I'm looking for the same flexibility as exists for the post content, being that it's possible to read-in, modify then return the_content of a post.

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

One possibility is to use output buffering to catch the final HTML, using ob_start() etc

But is there some more targeted method for parsing post image attachments?

1

1 Answers

1
votes

I've answered my own question using output buffering. Note I'm using a Genesis theme, so have access to additional hooks such as genesis_after_content which is after the loop and before the footer, thus the full html content is already prepared. This gives access to the featured image URLs (not possible from get_the_content) plus any/all image URLs from featured page/post widgets, etc... whatever you see in the rendered content.

<?php
//at start of php script set output buffering
ob_start();
session_start();

//script does stuff

if (isset($_SESSION['some_variable_is_set'])) {
    add_action( 'genesis_after_content', 'my_replace_image_urls');
    //used genesis_after_content hook as full html content is now prepared
}

function my_replace_image_urls() {
  $full_content = ob_get_clean();
  //modify $full_content as needed
  echo $full_content;
}