Need help? Check out our Support site, then


Adding a PHP function to all wordpress pages

  1. Hi! I've just finished configuring my new wordpress blog but wanted to add some functionality to it. I need to randomly get an image from a directory and display it on a page! Unfortunately I couldn't find a plugin to fit my needs so I found the following PHP script and did a bit of editing to make it work for me. However, I don't know where I can add it so that it is accessible through all of my wordpress pages D:! I tried to add it to the function.php file, but that simply broke my blog, and it didn't display anything. Is there an easy way that I can add this to one of the core or template specific .php files so that I can call the previewImage() function at will in my posts?

    Thanks in advance for any help or advice!

    Heres mah script:
    <?php

    function previewImage($directory){
    $folder = $directory;

    // Space seperated list of extensions, you probably won't have to change this.
    $exts = 'jpg jpeg png gif';

    $files = array(); $i = -1; // Initialize some variables
    if ('' == $folder) $folder = './';

    $handle = opendir($folder);
    $exts = explode(' ', $exts);
    while (false !== ($file = readdir($handle))) {
    foreach($exts as $ext) { // for each extension check the extension
    if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
    $files[] = $file; // it’s good
    ++$i;
    }
    }
    }
    closedir($handle); // We’re not using it anymore
    mt_srand((double)microtime()*1000000); // seed for PHP < 4.2
    $rand = mt_rand(0, $i); // $i was incremented as we went along

    $random_pic = $folder.$files[$rand];
    }
    ?>

  2. You did not specify a blog address or reason for posting when you created this topic.

    This support forum is for WordPress.com hosted blogs only. If you have a self-hosted WordPress blog you need to seek help at the WordPress.org forums, not here.

    If you don't understand the difference, you may find this information helpful.

Topic Closed

This topic has been closed to new replies.

About this Topic