I have used a function
/*
Random File Function
Written By: Qassim Hassan
Website: wp-time.com
Twitter: #QQQHZ
*/
function Qassim_Random_File($folder_path = null){
if( !empty($folder_path) ){ // if the folder path is not empty
$files_array = scandir($folder_path);
$count = count($files_array);
if( $count > 2 ){ // if has files in the folder
$minus = $count - 1;
$random = rand(2, $minus);
$random_file = $files_array[$random]; // random file, result will be for example: image.png
$file_link = $folder_path . "/" . $random_file; // file link, result will be for example: your-folder-path/image.png
return '<img src="'.$file_link.'" alt="'.$random_file.'">';
}
else{
return "The folder is empty!";
}
}
else{
return "Please enter folder path!";
}
}
?>
to pull a random image from a specific wordpress directory. I can successfully call up a random image file however it does not display, just displays the image filename and a broken image icon.
The code I am using from the tutorial to display the image is <?php echo Qassim_Random_File("my-folder-name"); // display random image! ?>
I am brand new to php as of this week, and a fairly novice coder in general (know some basics) so I really am stumped. I've fooled with other possible solutions from stack overflow already but this tutorial is the only thing I've been able to get close to working. Many thanks if anyone can spot the problem!
This is showing up in the HTML inspector:
<div class="elementor-widget-container">
<h5>call</h5>
<a href="wp-content/uploads/H-PH-MA-Greyscale/image_2.jpg" target="_blank" title="image_2.jpg">
<img src="wp-content/uploads/H-PH-MA-Greyscale/image_2.jpg" alt="image_2.jpg">
</a>
</div>
You just need to replace this line:
$file_link = $folder_path . "/" . $random_file;
...with this one:
$file_link = get_site_url(null, $folder_path . "/" . $random_file);
What was the problem?
scandir is returning the physical file path, not the url to the file - we can confirm this is we look at one of the values it returns for $random_file, e.g. wp-content/uploads/H-PH-MA-Greyscale
This is a relative URL, but we need an absolute URL so that it will work no matter where it is called. We also need to include the site URL so that the path to wp-content is correct. (Note: site URL and home URL can be different - the site URL is the one that always point to the location of the WP files).
Another problem is the trailing slash (or lack of one) on the site URL. get_site_url and get_home_url do not add the trailing slash to the URL, so you need to add it yourself if it isn't included in the file path.
So how do we solve this?
Using the get_site_url function added the correct path to the WP files, and it also lets us pass it the file path with our without a preceding slash as a parameter, and it will add the slash on the path only if it is needed.
The code looks simple, if the folder exist and it has more then 2 file (it considers the "." and ".." and files when you use scandir) then you should be able to see something. What's the generated HTML code for that function call?
Be aware that the code you are using builds the file url using the phisical path, that isn't going to work. You should fix this part:
if( $count > 2 ){ // if has files in the folder
$minus = $count - 1;
$random = rand(2, $minus);
$random_file = $files_array[$random]; // random file, result will be for example: image.png
$file_link = get_home_url().$folder_path . "/" . $random_file; // file link, result will be for example: your-folder-path/image.png
return '<img src="'.$file_link.'" alt="'.$random_file.'">';
}
Notice the get_home_url() to build the real URL which is needed for your <img tag src
Related
How can i display all images from an ftp server in website using php?
It should also sort automatically so i could just add more images to the ftp server and it would work.
I'm trying to make a gallery type thing
I've already looked through google and found nothing that worked.
I'm still learning php and dont know too much about it.
Any help would be much appreciated. Thanks!
As already commented, scandir does the trick. The below code gets all the images and output them as <img> elements.
index.php:
// Here enter the base url of the images folder
$base_images_url = "http://example.com/images/";
$dir = dirname (__FILE__) . "/images/";
// Get the files in the folder. Sort in ascending order - this is the default
$images = scandir($dir);
// Or is you need to sort in descending order
//$images = scandir($dir,1);
// Output an img tag for every image.
foreach($images as $image){
// skip the . and .. that starts the folder listing
if($image === '.' || $image === '..'){
continue;
}
$image_url = $base_images_url . $image;
echo '<img src="' . $image_url . '">';
}
This works with the following folder setup:
-index.php
-images
-image1.png
-anotherimage.jpg
I have the following code for a gallery. When the thumbnail is clicked, I would like to open the big image in another window (which it does) and then be able to navigate to the next image in the new window, but in order to do this, I need to strip the .jpg off the filenames so that I can just '+1' to the filename, as they are sequentially numbered.
For example, files are numbered 001.jpg, 002.jpg, 003.jpg etc.
I currently have:
echo '<p>basename=' . basename($i) . '</p>';
Which give the name of the file with .jpg extension, for example basename=001.jpg.
Then I have :
$image = basename($i); // to give the variable $image
$img = str_replace('.jpg',$image, ''); //to take off the .jpg extension
but the output I expect, 001, doesn't echo. It just has nothing... img=
echo '<p>img=' . $img . '</p>';
What am I doing wrong? Can anyone point me in the right direction?
Many thanks, Kirsty
Try this
$YourPicture = 'cat.jpg';
$without_extension = pathinfo($YourPicture, PATHINFO_FILENAME);
result will be
cat
Using the code below with the Sphider search engine, Sphider will display an image in search results - if the html page and jpg share the same name (i.e) page14.html, and page14.jpg.
1) Without knowing the name of the image, how could the code be modified so that the first of 2-3 jpg's is displayed from the html page returned in search results ?
<?PHP
$url_path = "http://www.webpage.com/"; // The url to indexed pages.
$url_ext = ".html"; // The file ext. of indexed pages.
$image_path = "../"; // Path to image folder.
$image_ext = ".jpg"; // The file extension of images.
$image = str_replace("$url_path", "$image_path", $url);
$image = str_replace("$url_ext", "$image_ext", $image);
if (file_exists($image)) { // Do nothing
} else { $image = $image_path . "ICS" . $image_ext; } ?>
<img src="<?PHP print $image ?>" align="left" style="margin-right:10px;" />
Or,
2) How would I modify the above php code to display the images below in search results - without renaming all the images ?
I have many gallery pages with hundreds of the following html image links;
<img SRC="chair_0.jpg">
<img SRC="table_0.jpg">
<img SRC="bed_0.jpg">
In my case, all our webpage images have the same ID as the end of each page.
Following is an example of how our pages look like: www.mywebsite.com/category/sub-category/etc/details.php?category=6&subcategory=s&sc=180&productid=98
The pictures are located in another path, and share the same last digits (i.e 98) as web page.
Following is an example of picture folder: www.mywebsite.com/admin/picures/
In addition, all pictures have an extra "p" at the front and "_full" at end of the digits, as following example "p98_full.jpg", p109_full.jpg" or "p3_full.jpg".
Following method worked for me. You will need to past this on sphider/templates/standard/search_results.html line # 76, modify it a bit to match your setting and see if it works... (You do not need to add a url link to your site to this code, this should work as is)
<?PHP
$url_ext = ".php"; // The file extension of indexed pages.
$image_path = "../admin/pictures/"; // Path to image folder.
$pic_name = "p"; // Alphabet before image, if any.
$page_end = Substr ($url2, strrpos($url2, "=")+1); // Isolate digits or alphabets starting from end of page.
$image_ext = "_full.jpg"; // The file extension of images.
$image = $image_path . "$pic_name$page_end" . $image_ext; // Select isolated digits or alphabes.
if (file_exists($image)) { // Do nothing
} else { $image = $image_path . "ICS" . $image_ext; } ?>
<img src="<?PHP print $image ?>" alt="" align="left" style="margin-right:10px; border:0;" />
Alright, this will need a long explanation. Sorry if it's too long:
/////////////// INTRODUCTION ///////////////
There doesn't seem to be much information around about using opendir() within Wordpress and the way it should be implemented. However, after a couple hours of research, trial and error, I got it working on a custom page template.
I need it to fetch game thumbnail images from folders and output them as a grid, divided by categories (each folder is a category).
/////////////// MY APPROACH ///////////////
I created a function in functions.php that opens and reads a folder using the following relative path:
"wp-content/games/".$category."/"
Where $category is the argument of the function (defined by the user).
This is how my function looks like now:
function fetch_game_images($category){
//$category = 'featured';
$imageFiles = array();
$extensions = array('.JPG','.PNG');
$directory = "wp-content/games/".$category."/";
$openDir = opendir($directory);
while ($imgFile = readdir($openDir))
{
if ($imgFile <> '.' and $imgFile <> '..')
{
$extension = strtoupper(substr($imgFile, strrpos($imgFile, '.')));
if (in_array($extension, $extensions))
{
$imageFiles[] = $imgFile;
}
}
}
closedir($openDir);
foreach ($imageFiles as $k => $v)
{
$withoutExt = preg_replace("/\\.[^.\\s]{3,4}$/", "", $v);
$hyphenlessName = str_replace("-"," ",$withoutExt);
$formattedName = strlen($hyphenlessName) > 24 ? substr($hyphenlessName,0,24)."..." : $hyphenlessName;
if ($category == 'featured'){
if (strpos($formattedName,'netent') !== false) {$finalName = trim($formattedName, 'netent');}
else if (strpos($formattedName,'mg') !== false) {$finalName = trim($formattedName, 'mg');}
else { $finalName = $formattedName;}
}
else { $finalName = $formattedName;}
echo '<div class="games-list-item"><div class="game-container">';
echo '<a href=""><img src="'.get_bloginfo('url').'/'.$directory.'/'.$v.'" alt=""/>';
echo '<h3>'.$finalName.'</h3></a>';
echo '<div class="game-hover">';
echo '<img src="'.get_bloginfo('url').'/'.$directory.'/'.$v.'" alt=""/>';
echo '<div class="game-buttons-holder"><a class="play_now_btns" href="">Play Now</a><a class="free_play_btns" href="">Free Play</a></div></div><!--.game-hover-->';
echo '</div><!--.game-container--></div><!--.games-list-item-->';
}
}
/////////////// MY APPROACH RESULTS ///////////////
When I load the Wordpress Page using the Page Template that calls this function, it loads the images flawlessly.
But then, I have to change the games category dynamically using jQuery, I take the category/folder name, save it in a JavaScript variable and send it to a php that grabs it and passes it to the fetch_game_images(); function.
My jQuery GET looks like this:
$('#sidebar-list-menu li a').live('click', function(){
event.preventDefault();
var category = $(this).data('category');
//alert(cat);
//$('div.games-grid').html('<span class="loadingNotification">LOADING</span>');
$.get("<?php bloginfo('template_directory'); ?>/games-list-loader.php?category="+category,
function(data){
//alert(data);
//$('span.loadingNotification').remove();
$('div.games-grid').html(data);
});
});
And the PHP File (located in the same theme directory) looks like this:
<?php $parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
$cat = $_REQUEST['category'];
fetch_game_images($cat);
?>
<div class="clear"></div>
/////////////// THE ISSUE ///////////////
The issue is that when I click on the sidebar link that triggers the GET call and tries to fetch the data from the PHP, it outputs the following error:
Warning: opendir(wp-content/games/featured/) [function.opendir]: failed to open dir: No such file or directory in [...]
Which shouldn't happen at all, since both my Page Template and my custom PHP file are in the same directory and load Wordpress core to use functions.php.
/////////////// THE QUESTION ///////////////
Does anybody know what could be the reason behind this behaviour? I read most of the google results I could find about this opendir() error, but most of them seem to point at a wrong path, but mine seem to be correct.
Others say that it might be a permissions issue. But I got my folders set to 755 and the files to 644.
So, any help would be great!
Thank you.
<======== /////////// EDIT ///////// =========>
Thanks to the help by #CBroe, I figured it out:
Instead of using a loose path like
"wp-content/games/".$category."/"
I changed it to a server-relative one
ABSPATH . "/wp-content/games/".$category."/"
And then I just changed the output to match the changes:
echo '<img src="'.get_bloginfo('url').'/wp-content/games/'.$category.'/'.$v.'" alt=""/>';
This works from both locations and solved the GET issue.
Most likely your relative path is not the correct one – usually happens when scripts are run from two different physical locations.
Making a debug output of getcwd() directly before calling opendir will show you what directory the scripts are actually running in in both cases – and that location is the one used to “complete” the relative path, so if those don’t match it’s only natural one of them will fail.
Relative paths are always tricky that way. It’s usually preferable to use a path relative to the server root (starting with a /) to avoid such issues.
Currently I have a script running to grab all the images in a directory based on ending with "154x154.jpg". Basically what I'm doing is going through a gallery directory and looking for all the thumbnails of images, which I will then output in a sliding gallery on the main page of a website.
<?php
// loop through the images
$count = 0;
$images = array();
foreach (glob("../../uploads/2012/05/*154x154.jpg") as $filename) {
$images[$count] = $filename;
$count++;
}
for ($i = 0; $i < 7; $i++) {
$random = mt_rand(1, $count - 1);
echo '<li><a class="gal_img" href="#">';
echo '<span class="roll"></span>';
echo '<img class="image" src="'.$images[$random].'" height="154" width="154" alt="" />';
echo '</a></li>';
}
?>
This works perfectly fine as it is, but what I need to do is be able to grab the files from within a directory above the current one. To be more specific:
image folder: http://root/wp-content/uploads/2012/05/
theme folder: http://root/wp-content/themes/theme_folder/
** EDIT **
Everything works now with the above code it executes fine, when I go directly to the file. However using it within the theme generates everything except for the filepaths in the code. Using wordpress 3.3.2
Try:
foreach (glob("../images/*154x154.jpg") as $filename) {
Update:
Of course, this is a relative path and only works if the file you need to include is one level up from your script's current working directory. Solution: use an absolute path, ie. one that begins with /. Also, keep in mind that the absolute path is a path on the disk, not the root folder of your website.