Tag: code

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.

So you want to be a web developer, huh?

I get this question all the time:

Hey man, how can I learn to do what you do?  -Random citizen

And I can probably guess why they are asking it too.

Read more →

The problem with relative time calculations in bash date strings

Today I was writing a bash script that needed to reference a time in the past relative to the current UTC date.

For instance, if today is March 31st, 2015 UTC, what month was it exactly one month ago?

Answer: February

However, I found it was less than trivial to actually get the correct answer using a relative time calculation with date.

Read more →