Currently reading: Holly by Stephen King

Attach a callback to multiple hooks at once

I originally had this stuff as a "bonus tip" in the other post about getting drafts and private pages into the parent-choosing drop-downs, but it ended up longer than the main content!

If you don't like having random named functions hanging around, like __dropdown_pages_args() in the post above, you can instead wrap add_filter() with your own version that accepts an array (or comma-separated string) of hook names. The callable passed to it will be attached to all of them.

function add_filters($names, $callback, $priority = 10, $args = 1) {
    if (! is_array($names)) {
        $names = explode(',', $names);
        $names = array_map('trim', $names);
    }

    foreach ($names as $name) {
        add_filter($name, $callback, $priority, $args);
    }
}

This way you can still use an anonymous function if you so desire.

add_filters('page_attributes_dropdown_pages_args, quick_edit_dropdown_pages_args, rest_page_query', function () {
    return array_merge($args, ['post_status' => ['publish', 'draft', 'private']]);
});

I suppose this ain't a great use case for it, and maybe there isn't much of a use case regardless. Still, it's perhaps uglier now than it was before, but you could always set the names beforehand and unset them afterward.

$filters = [
    'page_attributes_dropdown_pages_args',
    'quick_edit_dropdown_pages_args',
    'rest_page_query'
];

add_filters($filters, function () {
    return array_merge($args, ['post_status' => ['publish', 'draft', 'private']]);
});

unset($filters);

It perhaps looks superfluous here as well, but I do have one good example of its use I'll post soon.

Leave a comment

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