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

老季最近在开发一个插件,需要在保存文章的hook钩子中修改文章的状态,这里记录一下具体的方法。

这里要先移除保存文章的钩子然后再更新文章状态(不然会造成服务器500错误),然后再把钩子重新启用。官方说明文档如下:

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' );

WordPress官方手册:https://developer.wordpress.org/reference/hooks/save_post/

腾讯云限时秒杀【点击购买】

搬瓦工,CN2高速线路,1GB带宽,电信联通优化KVM,延迟低,速度快,建站稳定,搬瓦工BandwagonHost VPS优惠码BWH26FXH3HIQ,支持<支付宝> 【点击购买】!

Vultr$3.5日本节点,512M内存/500G流量/1G带宽,电信联通优化,延迟低,速度快【点击购买】!

阿里云香港、新加坡VPS/1核/1G/25G SSD/1T流量/30M带宽/年付¥288【点击购买】

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

`微信`扫码 加好友

链接到文章: https://gkxyz.com/wordpresszhutichajiankaifasave_post-hook-gouzi-xiugaiwenzhangfabiaozhuangtai-tuwenjiaocheng.html

推荐站点

评论已关闭