3

I have several modules for a given position, but I only want to display one of them (selected randomly) on the front-end in a Gantry template.

Is there any way to do this?

1
  • I think you will need to duplicate and hack the position particle in core Gantry to do this. I did something similar some time ago displaying a different module depending on the time of day. Aug 14 '20 at 4:03
4

Have a look at the Module Helper documentation.

getModules(): Get modules by position

getModules(string $position) : array static
since 1.5

Arguments
$position string The position of the module

Response array
An array of module objects

and

renderModule(): Render the module.

renderModule(object $module, array $attribs = array()) : string static
since 1.5

Arguments
$module objectA module object.
$attribs array An array of attributes for the module (probably from the XML).

Response string
The HTML content of the module output.

This means that after declaring use Joomla\CMS\Helper\ModuleHelper;, you can simply:

  1. Fetch all of the modules at your designated position as an array.
  2. Randomly select a single module object from the array of objects using array_rand().
  3. Display/Echo the rendered module content.

Code:

$position = 'position-2';
$modules = JModuleHelper::getModules($position);
echo JModuleHelper::renderModule($modules[array_rand($modules)]);

This is effectively an extension of FFrewin's answer from 2014.


In your template, write the jdoc placeholder.

<jdoc:include type="modules" name="position-2" />

A short list of relevant pages to reference:

2
  • Thanks for the answer! That is good information. However, I am using a Gantry template, and I can't find where to put the codes.
    – shenkwen
    Jul 6 '20 at 12:55
  • @shenkwen I have updated my answer.
    – mickmackusa
    Jul 6 '20 at 22:37
3

If you're after a less code heavy way of doing it, you could use a mix of Regular Labs Modules anywhere and Regular Labs Articles Anywhere.

  • Create your modules, and assign them all to a new position called "Random"
  • Create a category called Random Modules
  • Create articles for each of the modules using Module plugin syntax
  • https://www.regularlabs.com/extensions/modulesanywhere/tutorial#how-to-use-it-syntax
  • Create one more module that is assigned to the position you want the random modules to appear
  • Use Articles Anywhere (note Pro edition needed for ordering) to make the module load a random article
  • {articles category="Random Modules" ordering="random" limit="1"}[title][fulltext]{/articles}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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