Why isn't Wordpress' 'save_post_{$post->post_type}' action hook passing the correct number of arguments?

Viewed 1531

According to the WordPress codex save_post_{$post->post_type} should pass three arguments:

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

Here is my code:

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

I literally copied the function signature to be sure, but it throws an ArgumentCountError when I save the post (so I know the function is being called and the hook is "working").

The Exception

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

It's as if the save_post_guide hook is not passing the three arguments, only one.

I am simply attempting to update post meta when a post is saved. What am I doing wrong here?

2 Answers

The registered callback for the action hooked into is passed the default $accepted_args; the value for that is 1.

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

This needs to be set to 3 to get all 3.

If the code is in functions.php, then you might need to write action code as:

add_action( 'save_post_guide', 'saveGuideMeta' );

and if code is in plugin Class and you are calling action in the constructor of Class, then you need to make saveGuideMeta function as public as follows

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