問題描述
是否可以在 save_post 操作中確定是否正在創建新職位或更新現有職位?
最佳解決方案
自 WordPress 版本 3.7 起。 – IIRC – save_post 鈎子 – 有關鈎子及其在代碼參考中的使用的更多信息:save_post 和 Codex:save_post – 具有可用於確定的第三個參數 $update 。
@param int $post_ID Post ID.
@param WP_Post $post Post object.
@param bool $update Whether this is an existing post being updated or not.
次佳解決方案
執行此檢查 (在掛鈎函數中) 的方式是比較發佈日期和修改日期 (以 GMT 格式進行標準化)
function check_new_vs_update( $post_id ){
$myPost = get_post($post_id);
if( $myPost->post_modified_gmt == $myPost->post_date_gmt ){
//New Post
}else{
//Updated Post
}
}
add_action('save_post', 'check_new_vs_update' );
這是因為即使在創建時,該帖子也附有一個’modified’ 日期,與’created’ 日期完全相同。
第三種解決方案
我最終只是在設置之前檢查自定義值的存在。這樣,如果它是一個新創建的帖子,則自定義值將不存在。
function attributes_save_postdata($post_id) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (!wp_verify_nonce($_POST['_attributes_noncename'], plugin_basename(__FILE__))) return;
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id)) return;
} else {
if (!current_user_can('edit_post', $post_id)) return;
}
$termid = get_post_meta($post_id, '_termid', true);
if ($termid != '') {
// it's a new record
$termid = 'update';
} else {
// it's an existing record
}
update_post_meta($post_id, '_termid', $termid);
}
add_action('save_post', 'attributes_save_postdata');
第四種方案
ialocin 答案示例用”update” 測光儀:
function save_func($ID, $post,$update) {
if($update == false) {
// do something if its first time publish
} else {
// Do something if its update
}
}
add_action( 'save_post', 'save_func', 10, 3 );
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。