Support » Themes and Templates » Randomly loading an included file

  • Resolved 3Plumes

    (@3plumes)


    I’ve been using the following code to a template file in my theme:

    <?php include (TEMPLATEPATH . '/inc_customcode.php'); ?>

    I wanted to load a file randomly (when the page loads) and as such tried the following (which doesn’t work):

    <?php include (TEMPLATEPATH . '/inc_customcode_<?php echo(rand(1,2)); ?>.php'); ?>

    Does anyone know how I can modify the code to do this?

    Thanks in advance.

Viewing 4 replies - 1 through 4 (of 4 total)
  • You do not need the second <?php ;?>

    UNTESTED:

    <?php include (TEMPLATEPATH . '/inc_customcode_' .mt_rand(1,2) .'.php'); ?>

    Maybe use a couple of variables make it cleaner to read.

    <?php
    $rand_id = mt_rand(1,2);
    $file_name = TEMPLATEPATH . '/inc_customcode_'.$rand_id.'.php';
    if(file_exists( $file_name ) ) include_once($file_name);
    ?>

    HTH

    David

    Thread Starter 3Plumes

    (@3plumes)

    Thanks. I tried the code but I’m getting an error on the 4th line:

    Parse error: syntax error, unexpected T_IF

    The following is what I added:

    <?php
    $rand_id = rand(1,2);
    $file_name = TEMPLATEPATH . '/inc_home_content_'.$rand_id.'.php'
    if(file_exists( $file_name )) include_once( $file_name );
    ?>

    I missed the semi-colon off the end (line 3), use mt_rand() it is quicker!
    $file_name = TEMPLATEPATH . '/inc_home_content_'.$rand_id.'.php';

    I updated the previous post 🙂

    David

    Thread Starter 3Plumes

    (@3plumes)

    Works like a charm!! Thanks David.

    Karl

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Randomly loading an included file’ is closed to new replies.