2

I have a plugin where I am trying to instantiate a new class but every time the plugin was enabled, the page kept dying saying the object already exists. Upon investigating, I found out that it only happens in Category Page and not Article page.

So I removed everything in the code and had the following code:

class plgContentFoobar extends JPlugin
{
  public function onContentPrepare($context, &$row, &$params, $page = 0)
  {
    echo 1;
  }
}

On the Article page, it just outputs once as expected but on a category page; it outputs 15 times. Is there anything I need to be aware which is causing this on the category pages?

2
  • How many articles are displayed on the category page?
    – Lodder
    Commented Jun 23, 2016 at 13:10
  • @Lodder 14 articles on that page.
    – sifu
    Commented Jun 23, 2016 at 13:25

2 Answers 2

3

Right, so the function executes 15 times and you have 14 articles assigned to a category.

If you open the following file:

components\com_content\views\article\view.html.php

you see the event dispatched on line 161:

$dispatcher->trigger('onContentPrepare', array ('com_content.article', &$item, &$item->params, $offset));

Then in this file:

components\com_content\views\category\view.html.php

You also see it dispatched on line 106:

$dispatcher->trigger('onContentPrepare', array ('com_content.category', &$item, &$item->params, 0));

As you are on the category view and have 14 articles assigned to the category, the onContentPrepare is dispatched 14 times and then once again from the category view.

2
  • That explains it. Marking it as an answer but is it possible to dispatch the onContentPrepare just once? What I am trying to do requires the code to run just once otherwise it fails which explains why it worked on Article Page and not Category page.
    – sifu
    Commented Jun 23, 2016 at 13:54
  • It would be best to create a new question, showing the full code your using
    – Lodder
    Commented Jun 23, 2016 at 14:05
1

Contnet plugins fire on each content portion - each module, each article on a blog page and so on. If you want to replace something unsing one run of a plugin you should use a system plugin and onAfterRender

    function onAfterRender() {
            $body = JResponse::getBody();
            // replace what you need in the $body
            JResponse::setBody($body);
   }
1
  • This is the appropriate answer for what I wanted to do but for the question I asked, I will keep the 'Marked Answer' as the one above.
    – sifu
    Commented Jun 28, 2016 at 14:20

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.