使用wp_update_post时,提示页面已经保存成功,但是编辑器右上角一直是正在保存的状态。

通过对wp-config.php中添加:

define('WP_DEBUG', true); 
define( 'WP_DEBUG_LOG', true ); //追加
define( 'WP_DEBUG_DISPLAY', true ); //追加

可在wp-content/得到debug文件。

报错信息如下:

[10-Aug-2020 08:36:54 UTC] PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 524288 bytes) in …/wp-includes/class-wp-term-query.php on line 307[10-Aug-2020 08:36:54 UTC] PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 524288 bytes) in …/wp-includes/class-wp-recovery-mode.php on line 172

提示内存溢出。

那么,通常就是死循环或者是无限循环导致的。

我绕了一大圈…

最终仔细去阅读了官方文档:

wp_update_post 帮助文档:
https://developer.wordpress.org/reference/functions/wp_update_post/

其中有一段写到:

Caution – Infinite loop
When executed by an action hooked into save_post (e.g. a custom metabox), wp_update_post() has the potential to create an infinite loop…

并提供了解决方法:

<?php
function my_function( $post_id ){
    if ( ! wp_is_post_revision( $post_id ) ){
     
        // unhook this function so it doesn't loop infinitely
        remove_action('save_post', 'my_function');
     
        // update the post, which calls save_post again
        wp_update_post( $my_args );
 
        // re-hook this function
        add_action('save_post', 'my_function');
    }
}
add_action('save_post', 'my_function');
?>

这个写法就是插入更新内容时,先避开保存步骤。插入更新的内容之后再把相关函数勾到save_post钩子上。

延伸:

另外,如果是在自定义的class中写的,那么需要指定函数的域。就拿上面的示例代码来讲,调整成:

<?php
function my_function( $post_id ){
    if ( ! wp_is_post_revision( $post_id ) ){     
        remove_action('save_post', array($this, 'my_function'));     
        wp_update_post( $my_args ); 
        add_action('save_post', array($this, 'my_function')); 
    }
}
add_action('save_post', 'my_function');
?>