我在 Wordpress 中有一個自定義帖子型別,我想在發布帖子時運行自定義代碼。不是在自動保存或更新期間。
function send_notification($post_id, $post){
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
if ( $is_autosave || $is_revision ) {
return;
}
if (get_post_type( $post_id ) == 'vip_post') {
send_message($post->post_content);
}
}
add_action('save_post', 'send_notification', 10, 2);
但是,我發現該功能send_message在我在帖子編輯器中撰寫內容時以及在單擊發布按鈕之前被多次觸發。
uj5u.com熱心網友回復:
你可以did_action用來檢查已經呼叫的動作嗎?試試下面的代碼。
function send_notification($post_id, $post){
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return;
}
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
if ( $is_autosave || $is_revision ) {
return;
}
$times = did_action('save_post');
if( $times === 1 ){
if (get_post_type( $post_id ) == 'vip_post') {
send_message($post->post_content);
}
}
}
add_action( 'save_post', 'send_notification', 10, 2 );
上述代碼的替代版本,提前回傳。
function send_notification($post_id, $post){
if ( did_action( 'save_post' ) > 1 ){
return;
}
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return;
}
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
if ( $is_autosave || $is_revision ) {
return;
}
if (get_post_type( $post_id ) == 'vip_post') {
send_message($post->post_content);
}
}
add_action( 'save_post', 'send_notification', 10, 2 );
此外,您可以使用remove_action鉤子洗掉您的操作。一旦你的函式被呼叫。
function send_notification($post_id, $post){
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return;
}
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
if ( $is_autosave || $is_revision ) {
return;
}
if (get_post_type( $post_id ) == 'vip_post') {
send_message($post->post_content);
}
remove_action('post_save', 'send_notification');
}
add_action( 'save_post', 'send_notification', 10, 2 );
或者
您可以通過使用 取消注冊腳本來完全禁用它wp_deregister_script。試試下面的代碼。
add_action( 'admin_init', 'disable_autosave' );
function disable_autosave() {
wp_deregister_script( 'autosave' );
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/342797.html
標籤:WordPress的
