2012-10-13 28 views
0

下面的示例插件允許您在管理面板中按下download按鈕時下載文本文件。問題是我預計文本文件名將是hello_world.txt,但它不知何故變成options-general.txt方法/功能的默認參數值未設置爲正確通過WordPress的add_action()回調

如果這行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; 
    }  
} 

爲什麼?我怎樣才能設置一個默認參數值?我用普通函數試了一下,它的默認值也沒有反映出來。感謝您的信息。

回答

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; 
} 
+0

'不是所有的鉤子都傳遞參數。從我所知道的情況來看,init鉤子沒有。「 - 我在哪裏可以找到這些信息?我知道你通過自己的測試和研究發現了它。我很感激。我想知道它是否記錄在哪個鉤子允許默認參數,哪個不。 – Teno

+1

你是對的。我確實通過我自己的設備解決了這個問題。你可以通過查看源代碼來判斷。鉤子不傳遞參數在'do_action(...)'調用中只有一個參數。傳遞參數的鉤子不止一個。例如,'do_action('admin_notices');'''do_action('delete_user',$ id);'還有一些'固定'參數,比如'do_action('add_meta_boxes','link',$ link );'。我不知道一個權威的名單,或真的任何名單。通常,我只是掛鉤一個函數並運行var_dump(get_defined_vars());'看看我有什麼工作。 –

+0

我明白了。謝謝。 – Teno

相關問題