开放的编程资料库

当前位置:我爱分享网 > PHP教程 > 正文

WordPress 发布帖子挂钩

WordPress 最好的部分之一是它的钩子/动作系统;这个特殊的挂钩系统是 WordPress 在某些事件发生时分配回调的方式。一个似乎有很多困惑的事件是使用哪个钩子来检测帖子最初发布的时间。有 publish_post 挂钩,但当您在帖子已发布后单击“更新”按钮时会触发它;这并不理想。

搜索 WordPress 文档和论坛,您肯定会看到许多其他解决方案,但没有一个能像 transition_post_status 挂钩一样有效:

// Add the hook action
add_action('transition_post_status', 'send_new_post', 10, 3);

// Listen for publishing of a new post
function send_new_post($new_status, $old_status, $post) {
  if('publish' === $new_status && 'publish' !== $old_status && $post->post_type === 'post') {
    // Do something!
  }
}

transition_post_status 发生在帖子从一种状态变为另一种状态时;您可以查看帖子状态列表以查看其他可能的值。我还添加了一个 post_type 检查以确保帖子是博客帖子而不是页面。

哇,我花了一些时间才在这里找到我需要的东西——希望这能为你省去很多搜索和痛苦!

未经允许不得转载:我爱分享网 » WordPress 发布帖子挂钩

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏