WordPress如何监控文章状态变化

追格官方小助手/ 2022年12月15日/ WordPress/ 浏览 1246

WordPress系统中,用户投稿的文章,审核通过后,想给用户发一个通知。


这个需求怎么解决呢?如果能监控文章状态的变化,不是就解决了吗?


对此,WordPress一共提供了两批钩子:{$old_status}_to_{$new_status} 和 {$new_status}_{$post->post_type}


为什么说是两批钩子,而不是两个钩子?


$old_status 和 $new_status 可以是:draft、pending、publish、trash等


也就是说 {$old_status}_to_{$new_status} 包括以下:


draft_to_publish、publish_to_trash、pending_to_draft……


类似的,{$new_status}_{$post->post_type} 包括:


publish_post、trash_post……


利用这两批钩子,可以实现监控文章状态变化的需求。


代码示例:


do_action( "{$old_status}_to_{$new_status}", $post );


用上面的那一堆钩子,就能够监控文章所有状态的变化了。但是,感觉有点麻烦。有没有用一个钩子,就能监控文章所有状态的变化的方法呢?


监控所有状态的变化,那就使用:transition_post_status


do_action( 'transition_post_status', string $new_status, string $old_status, WP_Post $post )


只要文章的状态有变化,就会触发 transition_post_status 钩子。


发表评论

暂无评论,抢个沙发...

客服 工单