Don’t name form fields “update” or “link”

In WordPress, every form field on the post edit screen results in a hook named pre_post_{$field} on save. Here’s how:

That means a field named “update” results in a variable filter hook named pre_post_update with 1 argument passed.

However, there’s a core action with that name already, and it passes 2 arguments: https://xref.trepmal.com/wp/wp-includes/post.php.source/#l3371

Similarly with link, there’s a core filter by that name already: https://xref.trepmal.com/wp/wp-includes/link-template.php.source/#l163

The problem?

If I have a form field named “update”, and I (or any plugin I’m running) hook into the core action like this:

add_action( 'pre_post_update', 'myplugin_pre_post_update', 10, 2 );
function myplugin_pre_post_update( $post_id, $data ) {
    // do stuff
}

Then the variable hook will call myplugin_pre_post_update but only pass the 1 argument. As of PHP 7.1, this will cause a fatal error

Besides, names as generic as ‘update’ and ‘link’ run the risk of conflict with another plugin.

Possible solution

If changing the field names isn’t feasible, you can adjust your callback:

add_action( 'pre_post_update', 'myplugin_pre_post_update', 10, 2 );
function myplugin_pre_post_update( $post_id, $data = null ) {
    if ( is_null( $data ) ) {
        // null $data means we're on the wrong hook instance, bail!
        return;
    }
    // do stuff
}

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: