[Solved] Modify the content area via plugin - replacing <img for <amp-img

Hello, quick question:
I’m modifying the <img into <amp-img in the content area.
To do that I created a plugin: OnWebPagePrerender

Until here I got what I need but the last step I need is to save that $output back into the "content"
can anyone help me with that part, please?
~ unless there is a better way to do it!

<?php
$docID = $modx->resource->get('id');
$obj = $modx->getObject('modResource', array(
    'id'=>$docID
)); 
$html = $obj->get('content');
$output = preg_replace('/<img(.*?)\/?>/', '<amp-img$1></amp-img>', $html);

$modx->log(modX::LOG_LEVEL_ERROR, "Running: $output");

return;

Any help will be welcome!!! :+1:
Thank you very much!

IIRC, it’s

$modx->resource->_output = 'whatever';

I could be wrong.

I think Bob is right and you have to change the value of $modx->resource->_output like in these examples.

$modx->resource->_output already contains the markup for the whole page at this point and the tags have been processed. You can’t just read the value of the content field in this event and handle it separately.

Thanks @bobray and @halftrainedharry .
The next question here is: is my approach right?

I only need to replace the img tags for amp-img so the JS will read and process them.
In my mind a plugin OnWebPagePrerender is the way to go, will you do it that way?

What is your recommendation?

Cheers!

It should be possible to do that. Just read the value of $modx->resource->_output and change that, instead of querying the object ($modx->getObject('modResource', array('id'=>$docID));).


If the replace should only take place in the content and you can’t isolate this part of the page in $modx->resource->_output, then maybe take a look at the event OnLoadWebDocument instead.

Amazing!!!
Problem solved and I think it will be very useful for other users, thanks @bobray and @halftrainedharry for your help! :+1: :+1: :+1:

Here the solution:

Plugin name: ampImages
System Event: OnWebPagePrerender
Code:

<?php
$html = $modx->resource->_output;
//replace <img for <amp-img
$ampHtml = preg_replace('/<img(.*?)\/?>/', '<amp-img$1></amp-img>', $html);
$modx->resource->_output = $ampHtml;

//just to check in the Error Log
$modx->log(modX::LOG_LEVEL_ERROR, "Running: " .  $modx->resource->_output);

return;

This simple code will replace the <img tags to <amp-img to be processed via JS.

Enjoy it! :+1:

1 Like

I’m glad you got it sorted. :slight_smile:

just make sure to add an unset to free memory after running the preg_replace, depending on the PHP version you are running on, could bump into memory leak issues, here’s a link where the issue its explained, I don’t know if this kind of memory leaks are alredy managed inside MODX but with this things its better safre than sorry.

I’ll check mate, thanks! :+1: :+1: