Forums

[resolved] Randomly loading an included file (5 posts)

  1. 3Plumes
    Member
    Posted 9 months ago #

    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.

  2. Digital Raindrops
    Member
    Posted 9 months ago #

    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

  3. 3Plumes
    Member
    Posted 9 months ago #

    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 );
    ?>
  4. Digital Raindrops
    Member
    Posted 9 months ago #

    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

  5. 3Plumes
    Member
    Posted 9 months ago #

    Works like a charm!! Thanks David.

    Karl

Reply

You must log in to post.

About this Topic