WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to maybe do too much in a shortcode call. Here's the code I have:

function randnumber_func( $atts ){
 $digits = 4;
 $randnumber = rand(pow(10, $digits-1), pow(10, $digits)-1);
 $space = "\r\n";
 $myFile = "offer_codes.txt";
    $fh = fopen($myFile, 'a+') or die("can't open file");
    $stringData = date("F j, Y, g:i a") . " - " . $randnumber;
    fwrite($fh, $stringData.$space);
 return $randnumber;
add_shortcode( 'rand', 'randnumber_func' );

I want to create a random 4 digit number and have it printed to the page. I also want to take that random number, append the date to it, and have that written to a text file. It works in PHP, but not when I call it via a shortcode. Is something it Wordpress stripping it out or do I have it written incorrectly for the shortcode function?

share|improve this question
what part of it is not working? you don't see the number, it doesn't write to the file? enable debugging and check for errors. – Milo Jun 11 '13 at 22:04
up vote 0 down vote accepted

Your code works for me on a development server. As is, it saves to the site root directory. My guess is that you are trying to write to a directory to which the server does not have write access. I would suggest saving to wp-content/uploads or some other directory where you should reasonably have write access.

$upload_dir = wp_upload_dir();
$myFile = $upload_dir['basedir']."/offer_codes.txt";
share|improve this answer
Ah, my mistake then. I didn't have it in the right folder. I moved it like you suggested and it now works as intended. Thanks! – jscrilla Jun 11 '13 at 23:18

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.