2017-05-15 44 views
1

我有一種情況,可以保存帖子,如果已選中「發送警報」複選框,可以在保存帖子時通知用戶。我不希望複選框被保存,因爲只有當您想要發送警報時才需要檢查該複選框。這允許管理員保存,編輯等沒有任何困難。在Wordpress的save_post鉤子中訪問複選框的值

到目前爲止,我已經加入的複選框在發佈框一個帖子:

function createCustomField(){ 
    $post_id = get_the_ID(); 

    if(get_post_type($post_id) != 'jobs'){ 
    return; 
    } 

    $value = get_post_meta($post_id, '_send_alert', true); 
    wp_nonce_field('send_alert_nonce_'.$post_id, 'send_alert_nonce'); 
    ?> 
    <div class="misc-pub-section misc-pub-section-last"> 
     <label><input type="checkbox" value="1" name="_send_alert" /><?php _e('Send alerts', 'pmg'); ?></label> 
    </div> 
    <?php 
} 
add_action('post_submitbox_misc_actions', 'createCustomField'); 

而且具有save_post鉤設置以及其需要,如果進行檢查,檢查的複選框或沒有,然後如果是,發出警報。

function save_job_callback($post_id){ 
    global $post; 

    if($checkbox){ 
    //send out alerts here 
    } 
} 
add_action('save_post','save_job_callback'); 

我的問題是 - 如何訪問save_post鉤子內的複選框的值?

Checkbox in Wordpress publish box

回答

0

傳遞複選框值作爲參數傳遞給函數:

function save_job_callback($post_id,$checkbox=$_POST['checkbox']){ 
    global $post; 

    if($checkbox){ 
    //send out alerts here 
    } 
} 
add_action('save_post','save_job_callback'); 
+0

是啊!這麼簡單 - 該死的過度的大腦:) – PavKR

+0

這隻適用於PHP是瘋狂的語言......正確的參數是**'do_action('save_post',$ post_ID,$ post,$ update);'** – brasofilo

0

一個複選框有checked state,如果它存在的元數據被保存,如果沒有它刪除。

<input type="checkbox" id="coding" name="interest" value="coding" checked> 

nonce用於所以我們save_action不火無處不在,只有當我們的代碼運行。

行動save_post收到三個參數($post_id, $post_object, $update),我們必須在確定我們的代碼在正確的位置運行後檢查發佈的值與$_POST

工作代碼:

add_action('post_submitbox_misc_actions', 'checkbox_so_43970149'); 
add_action('save_post', 'save_so_43970149', 10, 3); 

function checkbox_so_43970149(){ 
    $post_id = get_the_ID(); 

    if(get_post_type($post_id) != 'jobs'){ 
    return; 
    } 

    wp_nonce_field('send_alert_nonce_'.$post_id, 'send_alert_nonce'); 

    $value = get_post_meta($post_id, '_send_alert', true); 
    $checked =checked($value, '_send_alert', false); 
    ?> 
    <div class="misc-pub-section misc-pub-section-last"> 
     <label><input type="checkbox" value="_send_alert" <?php echo $checked; ?> name="_send_alert" /><?php _e('Send alerts', 'pmg'); ?></label> 
    </div> 
    <?php 
} 

function save_so_43970149($post_id, $post_object, $update) { 
     if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) 
      return; 

     if (!wp_verify_nonce($_POST['send_alert_nonce'], 'send_alert_nonce_'.$post_id)) 
      return; 

    if ('revision' == $post_object->post_type) 
     return; 

    if (isset($_POST['_send_alert']) ) 
     update_post_meta($post_id, '_send_alert', $_POST['_send_alert']); 
    else 
     delete_post_meta($post_id, '_send_alert'); 
} 
+0

所以我可以只是省略了update_post_meta和delete_post_meta語句,因爲我不想保存_send_alert複選框的值。 – PavKR

+0

是的,完全... – brasofilo