2

I need a Joomla 4 Plugin to overwrite a marker in Custom Fields of type text or textarea with the article's title.

I added a onPrepareContent() method where I have access to the articles title as well as the custom field. Here is what I did so far:

class PlgContentMyReplacer extends CMSPlugin
{
    ...

    public function onContentPrepare($context, &$article, &$params, $page = 0)
    { 
        if(!in_array($context, array('com_content.article')))
        {
            return true;
        } 
            
        $article->jcfields[7]->value = str_replace('[LOCATION]', $article->title, $article->jcfields[7]->value); // This seems not to work
    
        return true; 
    }

    ...

}

$article->jcfields[7] is my custom field and [LOCATION] the marker I want to replace with the article's title.

This approach seems not to work. How can I overwrite the custom field's data before sending it to the browser?

3
  • I tried a mock up your code and it appears to work as far as the replace is concerned. What is the value of $article->jcfields[7]->value before and after your str_replace line?
    – Irata
    Sep 7, 2022 at 6:18
  • The $article->jcfields[7]->value is changed like expected after the str_replace. Its just that this change is not reflected on the final website.
    – cappu
    Sep 7, 2022 at 9:22
  • At the line after the onContentPrepare is triggered is the value for $article->jcfields[7]->value still changed? I am thinking that either another plugin with onContentPrepare is replacing the value which might show up after the return from the trigger or later on something is changing the value. Either way you have to work through the code and find where the value is reverting back to the original value if you are certain it is being changed in this Plugin.
    – Irata
    Sep 7, 2022 at 14:30

1 Answer 1

1

I finally found the solution. I had to switch to a system Plugin. There inside the onAfterRender() function I can grab the whole body and the document title and replace the marker - like this:

public function onAfterRender()
{ 
    $body = $this->app->getBody();
    $document = $this->app->getDocument();
    $title = $document->getTitle();
        
    $body = str_replace('[LOCATION]', $title, $body);
    $this->app->setBody($body);

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.