2012-12-22 42 views
2

我正在創建一個自定義插件並有一個選項頁。當我點擊保存按鈕時,我的變量正在保存,但我想添加第二個按鈕並檢測按下了哪個按鈕。我一直試圖把名字放在按鈕中,並希望通過isset $ _POST ['name'] {}來檢測它們,但是當我點擊保存或其他按鈕時,它只是保存了我的變量,但並沒有POST變量中的任何內容。正如你在代碼中看到的那樣,一個按鈕從另一個按鈕保存變量,另一個按鈕保存並使用這些變量運行一些腳本。問題是,我需要該頁面來了解重新加載後點擊了哪個按鈕,您可以看到我嘗試辨別在底部點擊了哪個按鈕。 我寧願一個PHP解決方案,所以我可以逐步增強。謝謝!WP選項檢測按下哪個按鈕

<div class="wrap"> 
<h2>Config Me Bro</h2> 
<form method="post" action="options.php"> 
    <?php settings_fields('aug_options'); ?> 
    <?php $options = get_option('data_value'); ?> 
    <label for="">Checkbox</label> 
      <input name="data_value[option1]" type="checkbox" value="1" id="" <?php checked('1', $options['option1']); ?> /> 
    <label for="general_title">Title</label> 
      <input type="text" name="data_value[sometext]" id="general_title" value="<?php echo $options['sometext']; ?>" /> 

    <p class="submit"> 
     <?php submit_button('Save Changes', 'primary', 'save_config', false); ?> 
     <?php submit_button('Run Config', 'secondary', 'run_config', false); ?> 
    </p> 
</form> 
</div> 
<pre> <?php print_r($_POST);?></pre> 
<?php 
} 

/* Run Config Settings */ 
if (isset($_POST['run_config'])){ 
    echo '<h1>I am running</h1>'; 
} 
/* Save config Settings */ 
elseif (isset($_POST['save_config'])){ 
    echo '<h1>Saved it</h1>'; 
} 
+0

爲什麼你需要第二個按鈕?這將是它的用途? – eveevans

回答

2

以防萬一你仍在尋找答案。此外,爲了將來的參考,以便我可以找到它,如果有過丟失...這是我所做的,它似乎工作正常。

當您使用register_setting(「組」,「設置」)確保使用第3個參數,並定義一個回調函數。在回調中你可以訪問提交的選項,也可以訪問$ _POST變量。 $ _POST ['submit']是你正在尋找的。

在實踐中....

register_settings('my_plugin_settings_group', 'my_plugin_settings', 'my_plugin_settings_callback'); 

function my_plugin_settings_callback($posted_options) { 
    // $_POST['submit'] contains the value of your submit button 
    if($_POST['submit'] == 'Run Config') { 
     // your code here 
    } 
    // $posted_options is an array with all the values submitted so you have to return it. 
    return $posted_options; 
} 

我希望這可以幫助別人。我一直在尋找一個答案,然後開始嘗試。

  • RK
+0

請注意,在此示例中,$ posting_options未經過清理即可返回,如果處理不當,可能會導致安全漏洞。相反,通過測試'isset($ _POST ['submit'])'來避免不可信的輸入,然後在函數中進行操作。 – svandragt