Search code examples
phpwordpressrandomecho

Echo random number inside Wordpress' get_template_part


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 get_template_part.

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

Can get_template_part and the echo number be combined to achieve this?


Solution

  • There's a couple things:

    1. You need to remove the - (hyphen) from the get_template_part() since WP adds that.
    2. You can pass the random number through a variable.
    <?php
        // Assign the rand number to a variable 
        $number = rand( 1, 10 ); 
        // use the variable in the template part
        get_template_part('partials/template',  $number ); 
    ?>