【问题标题】:WordPress "save_post" call only on save post not on updateWordPress“save_post”仅在保存帖子时调用,而不是在更新时调用
【发布时间】:2019-12-30 13:13:36
【问题描述】:

当帖子通过 API 保存时,我正在尝试将帖子数据发送到第三方服务。我正在使用钩子add_action( 'save_post', [$this, 'save_post_callback'], 100, 3);,但这个钩子似乎在更新帖子以及管理面板中的 post-new.php 中被调用。因此,为了摆脱在 post-new.php 中运行这个钩子,我检查了 $_POST 请求,但我无法过滤更新帖子,因为我只想在保存帖子时调用 API,而不是在更新中。

回调函数$update 中似乎有第三个参数,但它也不起作用。下面是我的代码,只需要在保存帖子时调用,但它不起作用。任何帮助将不胜感激。

 function save_post_callback( $post_id, $post, $update ) {
    // (!$update) => this doesnot seems to work
    if(!empty($_POST) && $post->post_type == "post"){
        //run only when save post
    }
}

【问题讨论】:

  • 尝试检查帖子 ID。在第一次保存时,我认为不应该有一个
  • 否则你可以在做 api 的时候设置一个元字段,然后你可以在 enxt 保存时检查这个值。

标签: php wordpress


【解决方案1】:

简单的方法是检查_wp_http_referer最后一部分是否是post-new.php

这是一个简单的代码

function save_post_callback($post_id, $post, $update)
{
    // (!$update) => this doesnot seems to work
    if ( ! empty($_POST) && $post->post_type == "post" ){
        $end = explode('/', $_POST[ '_wp_http_referer' ]);
        $end = end($end);
        if($end == 'post-new.php'){
            //echo 'it is new post';exit();
            //do what you want here.
        }
    }
}

【讨论】:

  • 非常感谢您的推荐逻辑。我会试试这个,让你知道。
【解决方案2】:

来自 StackExchange here。看起来一个聪明的方法是比较 post_date 和 post_modified 以确定它是一个新帖子。

$is_new = $post->post_date === $post->post_modified;

if ( $is_new ) {
    // first publish
}

【讨论】:

    猜你喜欢
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多