无限循环使用WordPress save_post动作,为什么?

时间:2019-03-26 07:21:57

标签: wordpress save hook infinite-loop custom-post-type

我编写了这段代码,以使其在创建时处于草稿状态(前端由用户),然后在由后端的自定义角色用户使用自定义元框进行编辑时以私有状态具有自定义帖子类型:

add_action( 'save_post', 'save_response', 10, 3 );
add_filter( 'wp_insert_post_data', 'force_draft', 99, 2 );

public function force_draft( $data , $postarr ) {

    if( empty( $data['post_name'] ) && 'my-cpt' == $postarr['post_type'] )
        $data[ 'post_status' ] = 'draft';

    return $data;

}

public function save_response( $post_id, $post, $update ) {

    // check it's not an auto save routine
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
        return;

    // perform permission checks
    if ( !current_user_can('edit_post', $post_id) )
        return;

    if ( 'my-cpt' === get_post_type( $post_id) ) {
        // unhook this function so it doesn't loop infinitely
        remove_action('save_post', 'save_response', 10 );

        if ( isset( $_POST['request_response_field_nonce'] ) ) {
            if ( wp_verify_nonce( $_POST['request_response_field_nonce'], 'save_request_response' ) ) {
                if ( isset( $_POST['request_response_field'] ) ) {
                    $allowed_tags = '<a><b><br><cite><del><div><em><hr><i><img><li><ol><p><q><small><span><strong><sup><u><ul>';
                    $response_value = htmlspecialchars( strip_tags( $_POST['request_response_field'], $allowed_tags ) );
                    update_post_meta( $post_id, '_request_response_value_key', $response_value );
                }
            }
        }

        if (!wp_is_post_revision( $post_id ) ) {
            // Make the post private if it is edited else make it draft.
            if ( $update ) {
                $postarr = array(
                    'ID' => $post_id,
                    'post_status' => 'private'
                );
            } else {
                $postarr = array(
                    'ID' => $post_id,
                    'post_status' => 'draft'
                );
            }

            // check if in infinite loop... :(
            var_dump($postarr);

            // Update the post.
            wp_update_post( $postarr );
        }

        // re-hook this function.
        add_action( 'save_post', 'save_response', 10, 3);
    }

}

为什么会出现无限循环?

var_dump($ postarr)显示了完整的转储页面...

0 个答案:

没有答案