0

以下示例插件可让您download在管理面板中按下按钮时下载文本文件。问题是我预计文本文件名会是hello_world.txt,但它以某种方式变为options-general.txt.

如果这一行header('Content-Disposition: attachment; filename="' . $file_name . '"');直接设置文件名就好header('Content-Disposition: attachment; filename="hello_world.txt"');了。

/* Plugin Name: Sample Download Button  */

$sample_download_button = new Sample_Download_Button_AdminPage('Sample Download Button');
add_action('init', array($sample_download_button, "download_text"));
add_action('admin_menu', array($sample_download_button , "admin_menu"));

class Sample_Download_Button_AdminPage {
    function __construct($pagetitle, $menutitle='', $privilege='manage_options', $pageslug='') {
        $this->pagetitle = $pagetitle;
        $this->menutitle = !empty($menutitle) ? $menutitle : $pagetitle;
        $this->privilege = $privilege;
        $this->pageslug = !empty($pageslug) ? $pageslug : basename(__FILE__, ".php");
    }
    function admin_menu() {
        add_options_page($this->pagetitle, $this->menutitle, $this->privilege, $this->pageslug, array(&$this, 'admin_page'));
    }
    function admin_page() {     
        ?>
        <div class="wrap">
            <h1>Download Button Sample</h1>
            <form action="" method="post" target="_blank">
            <input type="submit" value="download" name="download">
            </form>
        </div>
        <?php
    }   
    function download_text($file_name='hello_world.txt') {
        if (!isset($_POST['download'])) return;
        $your_text = 'hello world';
        header("Content-type: text/plain");
        header('Content-Disposition: attachment; filename="' . $file_name . '"');
        echo $your_text;
        exit;
    }       
}

为什么?以及如何设置默认参数值?我用普通功能尝试过,它的默认值也没有反映。感谢您的信息。

4

1 回答 1

1

我对此进行了几种测试,包括将您的完整功能复制到我拥有的“沙盒”安装中。

不是所有的钩子都传递参数。据我所知,init钩子没有。它是否接受/传递参数是在定义钩子时确定的。显然,当触发不打算传递参数的钩子时,会将空字符串传递给回调。在您的情况下,这意味着它有效地覆盖了您的默认设置并且没有文件名,这反过来又导致浏览器使用表单提交到的页面的文件名 - options-general.php。

我会将文件名作为表单中的隐藏字段传递并发送$_POST,然后按照您设置的方式设置我的默认值$your_text

function download_text() {
    if (!isset($_POST['download'])) return;
    if (!isset($_POST['filename'])) $file_name = $_POST['filename'];
    else $file_name = 'hello_world.txt';
    $your_text = 'hello world';
    header("Content-type: text/plain");
    header('Content-Disposition: attachment; filename="' . $file_name . '"');
    echo $your_text;
    exit;
}  
于 2012-10-14T14:53:24.243 回答