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?

  • 1
    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, 2013 at 22:04

1 Answer 1


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";
  • 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, 2013 at 23:18

Your Answer

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

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