【问题标题】:Why isn't Wordpress' 'save_post_{$post->post_type}' action hook passing the correct number of arguments?为什么 Wordpress 的 'save_post_{$post->post_type}' 动作钩子没有传递正确数量的参数?
【发布时间】:2018-11-09 12:22:20
【问题描述】:

根据 WordPress codex save_post_{$post->post_type} 应该传递三个参数:

do_action( "save_post_{$post->post_type}", int $post_ID, WP_Post $post, bool $update )

这是我的代码:

add_action( 'save_post_guide', array($this, 'saveGuideMeta') );
function saveGuideMeta(int $post_ID, WP_Post $post, bool $update) {
    if (isset($_POST['guide_keyword'])) {
        update_post_meta($post_ID, 'guide_keyword', sanitize_text_field($_POST['guide_keyword']));
    }
}

我确实复制了函数签名,但是当我保存帖子时它会抛出一个ArgumentCountError(所以我知道函数正在被调用并且钩子正在“工作”)。

例外

Fatal error: Uncaught ArgumentCountError: Too few arguments to function saveGuideMeta(), 1 passed in public_html/wp-includes/class-wp-hook.php on line 288 and exactly 3 expected

好像save_post_guide 钩子没有传递三个参数,只有一个。

我只是在保存帖子时尝试更新帖子元数据。我在这里做错了什么?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    registered callback for the action hooked into 传递默认的$accepted_args;其值为 1。

    add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )
    

    这需要设置为 3 才能获得全部 3。

    【讨论】:

      【解决方案2】:

      如果代码在functions.php 中,那么您可能需要将操作代码编写为:

      add_action( 'save_post_guide', 'saveGuideMeta' );
      

      如果代码在插件类中并且你在类的构造函数中调用action,那么你需要将saveGuideMeta函数设为public,如下所示

      public function saveGuideMeta(int $post_ID, WP_Post $post, bool $update) {
          if (isset($_POST['guide_keyword'])) {
              update_post_meta($post_ID, 'guide_keyword', sanitize_text_field($_POST['guide_keyword']));
          }
      }
      

      【讨论】:

      • 感谢您的快速回复。我实际上只是发现了问题所在。 add_action 还有 2 个参数:优先级和传递的接受参数的数量。所以我不得不将我的 add_action 更改为 add_action( 'save_post_guide', array($this, 'saveGuideMeta'), 10, 3 ); - 3 告诉它传递三个参数。你知道的越多... ;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      相关资源
      最近更新 更多