防止发布状态/日期保存在TRANSITION_POST_STATUS挂接上

时间:2019-01-10 作者:RachieVee

我正在使用transition_post_status 防止基于帖子元字段发布自定义帖子类型。这似乎没有完全奏效,这就是我需要一些帮助的地方。

以下是我所拥有内容的简化版本:

add_action( \'transition_post_status\', [ $this, \'intercept_adherence_publishing\' ], 9, 3 );

function intercept_adherence_publishing( $new_status, $old_status, $post ) {
        $post_id = $post->ID;
        $adherence_status = $_POST[\'_adherence_status\'];

        if ( ( $new_status === \'publish\' ) && ( $post->post_type == \'protocol-adherence\' ) && ( $adherence_status !== \'accepted\' ) ) {
            error_out(\'Published post \' . $post_id . \' intercepted. Post remains unpublished due to adherence not being accepted\');
            wp_die( \'<b>Adherence Error: </b>Cannot publish adherence that is not accepted. Please save status in "Pending Review" instead of the publish button if the adherence is not accepted yet.\', \'Adherence Publishing Error\', [ \'back_link\' => true ]);
        }
    }

What is supposed to happen when post meta is not "accepted":

  • wp_die() 显示管理错误,并带有返回到帖子的链接,帖子仍处于挂起审阅状态,并带有“另存为挂起”选项,发布日期在发布按钮上方仍显示为“立即发布”

    What is actually happening with this code:

    • wp_die() 显示管理错误,并带有返回帖子的链接(正在发生并且很好)
    • 帖子状态从“待定审阅”变为“已发布”,并且“另存为待定”按钮消失。(不好)
    • 发布按钮上面现在保存了一个日期,如“发布于2019年1月10日@14:46”,而不是保留“立即发布”状态(不好)
      • 我是否应该使用另一个钩子,或者我必须在该功能中编写一些附加逻辑,以便帖子真正保持未发布状态?如中所示,我们保持“待审核”状态/选项,并防止保存日期?

        提前感谢!

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

我认为hook会在post状态更新后触发。试试这个

add_action( \'pre_post_update\', \'intercept_adherence_publishing\', 10, 2);

    function intercept_adherence_publishing ($post_ID, $data ) {
        if (get_post_type($post_ID) !== \'protocol-adherence\') {
            return;
        }
        $post = get_post($post_ID);
        $adherence_status = $_POST[\'_adherence_status\'];

        if ( ( $data[\'post_status\'] === \'publish\' ) && ( $post->post_type == \'protocol-adherence\' ) && ( $adherence_status !== \'accepted\' ) ) {
            error_out(\'Published post \' . $post_ID . \' intercepted. Post remains unpublished due to adherence not being accepted\');
            wp_die( \'<b>Adherence Error: </b>Cannot publish adherence that is not accepted. Please save status in "Pending Review" instead of the publish button if the adherence is not accepted yet.\', \'Adherence Publishing Error\', [ \'back_link\' => true ]);
        }
    }