开发者

wp_insert_post action causes 503 service unavailable

For a custom post type in WordPress, I want to automatically use the post ID as a slug for the post. For this, I use the following code:

add_action( 'wp_insert_post', 'change_slug', 10, 3 );
function change_slug( $post_id, $post, $update ) {
    if ( $post->post_type != 'custom_post_type' ) {
        return;
    }
    
 开发者_JS百科   wp_update_post(
        array(
            'ID'        => $post_id,
            'post_name' => $post_id, // slug
        )
    );
}

This code is based on a previous answer on so: https://wordpress.stackexchange.com/a/160483/181877

However, using this code I cannot even open the new post page for this CPT in WordPress. instead, I get a 503 Service unavailable message, which I believe is caused by a timeout.

I'm not sure what's wrong with my code. Any pointers?


Ok, I figured it out.

It seems like it resulted in an infinite loop, not sure why. But I included an extra if statement to check for the $update variable, making sure the code is not run during the update of a post and only when a new one is published. This seemed to have resolved it.

Below is my final code:

add_action( 'wp_insert_post', 'change_slug', 10, 3 );
function change_slug( $post_id, $post, $update ) {
    if ( $post->post_type != 'custom_post_type' ) {
        return;
    }

    if ( $update ) { // added this
        return;
    }

    wp_update_post(
        array(
            'ID'        => $post_id,
            'post_name' => $post_id,
        )
    );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜