WordPress主题插件开发save_post hook 钩子 修改文章发表状态 图文教程



Avoiding infinite loops

If you are calling a function such as wp_update_post that includes the save_post hook, your hooked function will create an infinite loop. To avoid this, unhook your function before calling the function you need, then re-hook it afterward.

// this function makes all posts in the default category private
function set_private_categories($post_id) {
    // If this is a revision, get real post ID
    if ( $parent_id = wp_is_post_revision( $post_id ) ) 
        $post_id = $parent_id;
    // Get default category ID from options
    $defaultcat = get_option( 'default_category' );
    // Check if this post is in default category
    if ( in_category( $defaultcat, $post_id ) ) {
        // unhook this function so it doesn't loop infinitely
        remove_action( 'save_post', 'set_private_categories' );
        // update the post, which calls save_post again
        wp_update_post( array( 'ID' => $post_id, 'post_status' => 'draft' ) );
        // re-hook this function
        add_action( 'save_post', 'set_private_categories' );
add_action( 'save_post', 'set_private_categories' );




您的电子邮箱地址不会被公开。 必填项已用 * 标注