Jump to content

I need someone with basic PHP to help with 1 line code


spanakorizo

Recommended Posts

for timthumb in my wordpress i use this code to

function first_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];

  if(empty($first_img)){ //Defines a default image
    $first_img = "images/default.gif";
  }
  return $first_img;
}

 

it works really well, then i thought why not to make it show random images if timthumb dont find any image?

 

so the 1st googling i did came up with this function:

<?php 
function getRandomFromArray($ar) { 
    mt_srand( (double)microtime() * 1000000 ); 
    $num = array_rand($ar); 
    return $ar[$num]; 
} 

function getImagesFromDir($path) { 
    $images = array(); 
    if ( $img_dir = @opendir($path) ) { 
        while ( false !== ($img_file = readdir($img_dir)) ) { 
            // checks for gif, jpg, png 
            if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) { 
                $images[] = $img_file; 
            } 
        } 
        closedir($img_dir); 
    } 
    return $images; 
} 

$root = ''; 
// If images not in sub directory of current directory specify root  
//$root = $_SERVER['DOCUMENT_ROOT']; 

$path = 'images/'; 

// Obtain list of images from directory  
$imgList = getImagesFromDir($root . $path); 

$img = getRandomFromArray($imgList); 

?>

 

and to show random image i Place the following where i wish the random image to appear:

 

<img src="<?php echo $path . $img ?>" alt="" />

 

my question is how to place this code in my function first_image??

i need to do something like this, but it doesnt make any sense:

if(empty($first_img)){ //Defines a default image

    $first_img = " <img src="<?php echo $path . $img ?>" alt="" />

this was my thought, if i can mix those 2 normally it should work, right?

 

or maybe there is another way to show random image in the

[i] if(empty($first_img)){ //Defines a default image[/i]
  [b]  $first_img =

?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.