0

I have searched high and low to find an answer, but can't seem to find one anywhere.

<?php
$f_contents = file("x.txt"); 
$line = $f_contents[rand(0, count($f_contents) - 1)];
echo($line);
?>

Currently I am getting random results on every page load, but need to return the string only once. I am using Wordpress, so I would preferably like a way to do this only when a page is created.

Any ideas?

3
  • Only once between all page loads? Commented Jul 29, 2013 at 14:08
  • 1
    Where did you put this code? which file? Commented Jul 29, 2013 at 14:08
  • Yes only once Jason. The code is within page content, inside of a list. The file is a text document with links, one per row. Commented Jul 29, 2013 at 14:47

3 Answers 3

2

You can use the PHP built in uniqid() function:

http://php.net/manual/en/function.uniqid.php

Sign up to request clarification or add additional context in comments.

1 Comment

This isn't going to load from the OP's file though!
0

You need to add a piece of meta information to your page when it gets created.

You can do this by creation your own plugin.

Comments

0

Add an option containing the posts ID and only set this option if it doesn't yet exist.

function random_option($id, $file){

if(get_option("rand_option".$id))
     return get_option("rand_option".$id);

$f_contents = file($file); 
$value = $f_contents[rand(0, count($f_contents) - 1)];
add_option( "rand_option".$id, $value );

return $value;

}

then call it:

echo random_option(get_the_ID(), "file.txt");

1 Comment

or if you only want to return it once across all page loads set the first return to 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.