代码之家  ›  专栏  ›  技术社区  ›  Chaddeus

为什么Wordpress的save\u post{$post->post\u type}操作钩子没有传递正确数量的参数?

  •  2
  • Chaddeus  · 技术社区  · 6 年前

    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 当我保存post时(因此我知道函数正在被调用,钩子正在“工作”)。

    例外

    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 hook不传递三个参数,只传递一个。

    我只是试图更新后元后,一个职位被保存。我做错什么了?

    2 回复  |  直到 6 年前
        1
  •  4
  •   Oluwafemi Sule    6 年前

    这个 registered callback for the action hooked into 传递默认值 $accepted_args

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

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

        2
  •  1
  •   Ahmed Hassan    6 年前

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

    add_action( 'save_post_guide', 'saveGuideMeta' );
    

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