为什么PUBLISH_{CUSTOM-POST-TYPE}在更新时触发?

时间:2013-02-25 作者:developdaly

我正在尝试对发布和更新启动两个不同的操作。两者都不应同时开火。

问题是publish_pm_task 正在更新时被解雇,并且save_post 永远不会被解雇吗?看到这个有什么问题吗?

<?php
// Updated task notification
add_action( \'save_post\', \'pm_updated_task_notification\' );

// New task notification
add_action( \'publish_pm_task\', \'pm_new_task_notification\' );

function pm_new_task_notification() {

    error_log(\'definitely a task\');

}

function pm_updated_task_notification( $post_id ) {

    $slug = \'pm_task\';

    /* check whether anything should be done */
    $_POST += array("{$slug}_edit_nonce" => \'\');
    if ($slug != $_POST[\'post_type\']) {
        return;
    }
    if (!current_user_can(\'edit_post\', $post_id)) {
        return;
    }
    if (!wp_verify_nonce($_POST["{$slug}_edit_nonce"], plugin_basename(__FILE__))) {
        return;
    }

    error_log(\'updated a task\');

}

1 个回复
最合适的回答,由SO网友:Eugene Manuilov 整理而成

首先,你必须明白,当我们更新帖子时,wp_update_post 函数被调用。但由于WP核心的优化设计有点不理想,实际节省由wp_insert_post 作用在trac on中查看line 3006.

好的,接下来让我们看看里面是什么wp_insert_post 作用正如你所看到的,在line 2950, save_post 每次调用函数时,无论是直接调用还是由wp_update_post 作用这意味着不适合确定帖子是否已插入/发布或更新。

为了找到更好的行动,让我们看看wp_transition_post_status 几乎在之前调用的函数save_post 行动,请查看line 2942. 此函数执行三个操作transition_post_status, {$old_status}_to_{$new_status}{$new_status}_{$post->post_type}, 在上查看line 3273. 我们有精彩的表演transition_post_status, 它传递旧的和新的post状态。这就是我们需要的。因此,如果新状态为publish 旧状态不是publish, 然后发布帖子。如果新状态为publish 旧状态为new, 然后,该帖子已插入。最后,如果新状态等于旧状态,那么帖子刚刚更新。

以下是您的代码片段:

add_action( \'transition_post_status\', \'wpse_transition_post_status\', 10, 3 );  

function wpse_transition_post_status( $new_status, $old_status, $post ) {
    if ( $new_status == \'publish\' && $old_status == \'new\' ) {
        // the post is inserted
    } else if ( $new_status == \'publish\' && $old_status != \'publish\' ) {
        // the post is published
    } else {
        // the post is updated
    }
}
附言:阅读WordPress核心代码,每次当你有疑问时,它都会对你有很大帮助!

结束