In my WordPress theme, I have partials folder containing 10 files named with a numerical suffix and I would like to use
get_template_part to choose 1 random file from of these 10. I thought the simplest way to do this would be by by naming the files with a numerical difference and echoing a random number between 1 and 10—which would be added to the end of the file name listed in
Currently I have the following, although I realise you can’t run PHP in PHP. Can they be combined with this logic?
<?php get_template_part('partials/template-', echo(rand(1,10)) ); ?>
Files in partial folder named:
template-1.php template-2.php template-3.php [...] template-10.php
get_template_part and the echo number be combined to achieve this?
There’s a couple things:
- You need to remove the
-(hyphen) from the
get_template_part()since WP adds that.
- You can pass the random number through a variable.
// Assign the rand number to a variable $number = rand( 1, 10 ); // use the variable in the template part get_template_part('partials/template', $number );