显示WP目录中的随机图像



我使用了一个函数


/*
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>

您只需要替换这一行:

$file_link = $folder_path . "/" . $random_file;

这个:

$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的路径是正确的。(注意:站点URL和主页URL可能不同-站点URL总是指向WP文件的位置(。

另一个问题是网站URL上的尾部斜杠(或缺少斜杠(。get_site_urlget_home_url不会在URL中添加尾部斜杠,因此如果未包含在文件路径中,则需要自己添加

那么我们该如何解决这个问题呢

使用get_site_url函数为WP文件添加了正确的路径,它还允许我们将文件路径作为参数传递给它,而不使用前面的斜杠,并且只有在需要时才会在路径上添加斜杠。

代码看起来很简单,如果文件夹存在,并且它有2个以上的文件(当您使用scandir时,它会考虑"."one_answers".."以及文件(,那么您应该能够看到一些东西。为该函数调用生成的HTML代码是什么?

请注意,您正在使用的代码使用物理路径构建文件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((来构建<img标签src

最新更新