Experimenting with magic return methods on WordPress filters

I was catching up on some of the specifics of the new default theme that shipped with WordPress 4.7, Twenty Seventeen.

When I saw this:

function childtheme_front_page_sections() {
    return 6;
}
add_filter( 'twentyseventeen_front_page_sections', 'childtheme_front_page_sections' );

We’ve all seen it a thousand times. There’s a filter that just needs a basic value, but since add_filter requires a callback function, we have to go out of our way to define one.

Annoying. Especially when you want to just return something basic, like an integer.

Have you ever done this before?

add_filter( 'twentyseventeen_front_page_sections', 6 );

No? Liar.

We’ve all done this by accident. Why? Because it’s intuitive! It’s a developer API that makes total sense when passing through simple values. Well, like it or not, WordPress wants a callback function – always.

Alright, so I thought I’d experiment a little with the callStatic magic method in PHP and see if I could create a pattern to expand on the helper functions that are already in WordPress for the sole purpose of  being used as filter callbacks.

And if you didn’t know about those yet, well, you’re welcome:

__return_true()
__return_false()
__return_null()
__return_zero()
__return_empty_string()
__return_empty_array()

So, I created a class called Returner where you can define the type and value you want to return directly in the method name itself:

add_filter( 'twentyseventeen_front_page_sections', 'Returner::int__6' );

Pretty cool!

Alright, time for the caveats.

You can’t use Returner unless you have PHP 5.3+, and if you have 5.3 then you might as well be using a closure, and if you’re using a closure… well, it’s only like 6 additional characters:

add_filter( 'twentyseventeen_front_page_sections', function() { return 6; } );

In the end, I don’t think my magical class is very practical, but it was still a fun experiment. I especially think the method for doing indexed array output was clever, though real-world application for that is probably pretty rare. Ha! Go figure.

Enjoy.

2 Comments

Add yours →

  1. Another option would be to make use of create_function(): https://gist.github.com/westonruter/35105d1e3d29a9964d9063894add3b40

    But yeah, +1 closures ASAP! 🙂

  2. Interesting – definitely could use something like this.

    My own (rough) experiment (PHP 5.2 supported):

    https://gist.github.com/mzalewski/4038b5d350a192624de8d2e01be563eb

Leave a Reply

%d bloggers like this: