Forum

Thread tagged as: Question

Randomising content - using RAND adding a lot to load time

Hi,

I'm using Perch Content Custom with a sort order of RAND to randomise the URL on a CTA button. Both the list of URLs and the CTA button itself has its own Region.


<a href="<?php perch_content_custom('CTA Single URL',array( 'template' => 'CTAs-urls.html', 'sort' => 'urls', 'count' => 1, 'sort-order' => 'RAND' )); ?>"> <?php perch_content('CTA Panel Single'); ?> </a>

Using RAND is casing the page load to go from 167ms (when using ASC) to 1.28 seconds, which isn't acceptable to the client who is very hot on his SEO and page speed.

I couldn't find an alternative way of randomising only part of a template which is why I split it out into two.

This maybe a shot in the dark but is there a better way of achieving this?

Sarah Evans

Sarah Evans 0 points

  • 6 years ago
Drew McLellan

Drew McLellan 2638 points
Perch Support

Randomising is pretty inefficient due to MySQL limitations.

There could be a better way. How many items are in the region?

There are 7 items (URLs) in that region

Drew McLellan

Drew McLellan 2638 points
Perch Support

Ok, I would do something like:

<?php 
$urls = perch_content_custom('CTA Single URL',array(
        'template'    => 'CTAs-urls.html',
        'split-items' => true,
));
if (count($urls)) echo $urls[rand(0, count($urls)-1)];
?>

Thanks Drew you're a star!

Out of interest is there a reason you asked how many items were in that region, could there be too many for this approach?

Drew McLellan

Drew McLellan 2638 points
Perch Support

Yes, you wouldn't want to pull hundreds or thousands of items into PHP memory, that would perform worse than the MySQL query.

Hi Drew,

I've just noticed this sometimes returns nothing, I've checked to make sure there isn't a blank item in the region it could be using and there isn't. Any thoughts?

Many thanks.

Drew McLellan

Drew McLellan 2638 points
Perch Support

If you do the following, what do you get?

print_r($urls);

I get


Array ( [0] => /forms/quote_ma1 [1] => /forms/quote_mb1 [2] => /forms/quote_mc1 [3] => /forms/quote_md1 [4] => /forms/quote_me1 [5] => /forms/quote_mf1 [6] => /forms/quote_mg1 )

Which looks correct

Drew McLellan

Drew McLellan 2638 points
Perch Support

Does your code include the -1 as per above? I did forget that and edit it in a few seconds after I originally posted the code.

That was it, I must have got to it before you edited it. Thank you!