我用了一个函数
/*
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 '<a href="'.$file_link.'" target="_blank" title="'.$random_file.'"><img src="'.$file_link.'" alt="'.$random_file.'"></a>';
}
else{
return "The folder is empty!";
}
}
else{
return "Please enter folder path!";
}
}
?>
要从特定wordpress目录中提取随机图像,请执行以下操作。我可以成功地调用一个随机的图像文件,但它不显示,只显示图像文件名和一个破碎的图像图标。
我从教程中用来显示图像的代码是<?php echo Qassim_Random_File("my-folder-name"); // display random image! ?>
这个星期,我对php是全新的,并且是一个相当初级的程序员(了解一些基本知识),所以我真的很困惑。我已经从堆栈溢出中愚弄了其他可能的解决方案,但是本教程是我能够接近工作的唯一一件事。如果有人能发现问题的话,非常感谢!
这将显示在HTML检查器中:
<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>
发布于 2020-09-18 18:57:48
您只需要替换这一行:
$file_link = $folder_path . "/" . $random_file;
...with这个:
$file_link = get_site_url(null, $folder_path . "/" . $random_file);
出了什么问题?
scandir
正在返回物理文件路径,而不是文件的url -我们可以确认这是我们查看它为$random_file
返回的值之一,例如wp-content/uploads/H-PH-MA-Greyscale
这是一个相对的URL,但是我们需要一个绝对的URL,这样不管它在哪里被调用,它都会工作。我们还需要包含站点URL,以便wp-content
的路径是正确的。(注意:site URL and home URL can be different -网站网址总是指向WP文件的位置)。
另一个问题是站点URL上的尾斜杠(或缺少斜杠)。get_site_url
和get_home_url
不向URL添加尾随斜杠,所以如果它未包含在文件路径中,则需要自己添加。
,那么我们怎么解决这个问题呢?
使用get_site_url
function向WP文件添加了正确的路径,它还允许我们将不使用前面斜杠的文件路径作为参数传递给它,并且只有在需要时,它才会在路径上添加斜杠。
发布于 2020-09-16 15:18:43
代码看起来很简单,如果文件夹存在并且它有超过2个文件(它考虑“”。还有“.”和文件时,当你使用扫描),那么你应该能够看到一些东西。函数调用生成的HTML代码是什么?
请注意,您使用的代码使用phisical路径构建文件url,这是行不通的。你应该修复这个部分:
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 '<a href="'.$file_link.'" target="_blank" title="'.$random_file.'"><img src="'.$file_link.'" alt="'.$random_file.'"></a>';
}
请注意get_home_url()来构建
https://stackoverflow.com/questions/63922593
复制相似问题