I've written a filter function to replace all image URLs in a post with URL from the Uploads directory of my site. However, when using the content_save_pre
, filter it won't actually work - but if I use the content_edit_pre
filter, it works. Here is my code:
$oldPostContent = $post->post_content; // pass old content into function as argument
function get_the_post_imgs($oldPostContent) {
global $post;
$newPostContent = $oldPostContent;
$newPostContent = preg_replace_callback(
"/<img.*src=[\"']([^\"']*)[\"'].*>/i", // pattern to match to (i.e the contents of an <img src="..." /> tag)
function ($match) {
return "hello world"; // obviously it's a lot more complicated than this but for your sake i've massively simplified it so the src="..." content is just replaced with "hello world" for now
},
$oldPostContent
);
return $newPostContent; // return new manipulated content
}
add_filter('content_save_pre', 'get_the_post_imgs'); // this doesn't work on the content, but if I use content_edit_pre, it does work
I've added some comments along the way to help you out. I'm pretty sure it's not a problem with the regex (http://regex101.com/r/aP4fU9) so it's something to do with my code not working the way content_save_pre
needs it to work.
Thanks for any help :)
/<img.*src=[\"']([^\"']*)[\"'].*>/i
(screenshot for you in case you still have the problem: cl.ly/Uml7) Also in regards to the syntax highlighter making all the code red, any question I go on for the WordPress StackExchange has this problem right now, not sure if it'd be doing it for you as well? :/img
regex you posted. It is not part of the regex. I have not seen the syntax problem on any question in the last hour or so besides yours. What are you using to edit code?