我有一个函数,可以将给定目录中的文件列表显示为链接。然后我有一个短代码来显示函数,但我无法弄清楚如何在不使用内联 php 调用函数的情况下使短代码工作。简码现在只有效,因为我有另一个第三方插件,允许在 WordPress 文本编辑器中进行内联 php。
函数如下:
function showFiles($path){
if ($handle = opendir($path))
{
$up = substr($path, 0, (strrpos(dirname($path."/."),"/")));
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$fName = $file;
$file = $path.'/'.$file;
if(is_file($file)) {
echo "<li><a href='/".$file."' target=_blank>".$fName."</a></li>";
}
}
}
closedir($handle);
}
}
这是我正在使用的简码函数的精简版本:
function sc_showfiles( $atts, $content = null ) {
extract( shortcode_atts( array(
'type' => '',
), $atts ) );
$showfiles = '<ul><?php showFiles(''files/'.$type.'files/'.do_shortcode($content).'''); ?></ul>';
return $showfiles;
}
add_shortcode('showfiles', 'sc_showfiles');
内容区域允许用户输入带有用户生成的元的简码,以便它从中提取的目录将与登录用户匹配。
我已经尝试了大约六种不同的东西,如果不使用内联 php 调用 showFiles 函数,我就无法实现这一目标。我曾经使用过一次:
$files = showFiles('files/'.$type.'files/'.do_shortcode($content).);
和
$showfiles = '<ul>'.$files.'</ul>';
return $showfiles;
但这把文件列表扔在了页面顶部,我认为是因为原始的 showFiles 函数正在回显 html 输出。但是如果我将 echo 更改为在顶部函数中返回,我什么也得不到。
///
感谢FaddishWorm的帮助。
function showFiles($path){
if ($handle = opendir($path))
{
$up = substr($path, 0, (strrpos(dirname($path."/."),"/")));
$thefiles .= '<span class="checkmarks"><ul>';
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file !== "index.html")
{
$fName = $file;
$file = $path.'/'.$file;
if(is_file($file)) {
$thefiles .= "<li><a href='/".$file."' target=_blank>".$fName."</a></li>";
}
}
}
closedir($handle);
$thefiles .= '</ul></span>';
return $thefiles;
}
}
function sc_showfiles( $atts, $content = null ) {
extract( shortcode_atts( array(
'type' => '',
), $atts ) );
$thefiles = showFiles('files/'.$type.'files/'.do_shortcode($content));
return $thefiles;
}
add_shortcode('showfiles', 'sc_showfiles');
从函数返回某些内容不会将其回显到页面。当你调用你的函数时,你可以尝试echo showFile(blah);
如果你返回的是php,那么请记住php是服务器端的。您要将其退还给客户吗?如果是这样,那么它将无法正常工作,您应该重新调查这一点。客户端不会运行 PHP。
你为什么不使用ajax或其他东西?
编辑:
print showFiles('files/'.$type.'files/'.do_shortcode($content));
现在在你的 showFiles 函数中,把<ul>
放在返回字符串周围。这应该使事情不那么混乱。
-编辑:
function showFiles($path){
if ($handle = opendir($path))
{
$up = substr($path, 0, (strrpos(dirname($path."/."),"/")));
$returnString = "<ul>"; //ADDED THIS
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$fName = $file;
$file = $path.'/'.$file;
if(is_file($file)) {
returnString .= "<li><a href='/".$file."' target=_blank>".$fName."</a></li>";
}
}
}
closedir($handle);
$returnString .= "</ul>";
return $returnString;
}
}