TransWikia.com

Randomly render one of the modules in a given position

Joomla Asked by shenkwen on September 5, 2021

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?

2 Answers

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}

Answered by Patrick Jackson on September 5, 2021

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 JoomlaCMSHelperModuleHelper;, 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:

Answered by mickmackusa on September 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP