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 mychild_sections() {
     return 6;
add_filter( 'twentyseventeen_front_page_sections', 'mychild_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:


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.



 * This class is designed to return a basic value by parsing the dynamic
 * static method name you call to determine its type and value.
 * It's useful for filtering values in WordPress quickly without having
 * to create a callback function. Think of this as a continuation of the
 * callback helpers already in WordPress: __return_true(), et al.
 * add_filter( 'twentyseventeen_front_page_sections', 'Returner::int__4' );
 * add_filter( 'site_icon_sizes', 'Returner::array__256__128__64' );
 * add_filter( 'post_class', 'Returner::featured' );
 * @author  Frankie Jarrett
 * @license https://www.gnu.org/licenses/gpl-2.0.html GPL-2.0
class Returner {

	 * Magic value returner method.
	 * @access public
	 * @static
	 * @param  string $name
	 * @param  array  $args (unused)
	 * @return mixed
	public static function __callStatic( $name, $args ) {

		 * Return an integer.
		 * Returner::int__6() ==> 6
		if ( 0 === strpos( $name, 'int__' ) ) {

			return (int) self::value( $name );


		 * Return a negative integer.
		 * Returner::nint__6() ==> -6
		if ( 0 === strpos( $name, 'nint__' ) ) {

			return (int) self::value( $name ) * -1;


		 * Return a floating point number.
		 * Returner::float__1_234() ==> 1.234
		if ( 0 === strpos( $name, 'float__' ) ) {

			return (float) str_replace( '_', '.', self::value( $name ) );


		 * Return a negative floating point number.
		 * Returner::nfloat__1_234() ==> -1.234
		if ( 0 === strpos( $name, 'nfloat__' ) ) {

			return (float) str_replace( '_', '.', self::value( $name ) ) * -1;


		 * Return a one-dimensional indexed array.
		 * Returner::array__foo__bar_baz() ==> [ 'foo', 'bar baz' ]
		 * Returner::array__1__foo__3() ==> [ 1, 'foo', 3 ]
		 * Returner::array__foo__FALSE__bar ==> [ 'foo', false, 'baz' ]
		if ( 0 === strpos( $name, 'array__' ) ) {

			$array = [];

			foreach ( explode( '__', self::value( $name ) ) as $value ) {

				if ( 'TRUE' === $value ) {

					$array[] = true;



				if ( 'FALSE' === $value ) {

					$array[] = false;



				$value = trim( str_replace( '_', ' ', $value ) );

				$array[] = is_numeric( $value ) ? (int) $value : $value;


			return $array;


		 * Return a string.
		 * Returner::foo_bar_baz() ==> 'foo bar baz'
		return trim( str_replace( '_', ' ', $name ) );


	 * Return the value portion of a method name.
	 * @access public
	 * @static
	 * @param  string $name
	 * @return string
	public static function value( $name ) {

		return preg_replace( '/^[a-z]+__/', '', $name );



Link to Gist

Introducing the Strong Password Generator plugin for WordPress

Today I released the Strong Password Generator plugin for WordPress.

Last week I released a plugin called Expire Passwords which is meant to harden site security by requiring certain users to change their passwords on a regular basis.

The plugin got some early users straight away, one of whom suggested that it might also be nice to give users a way to generate a strong password, making it even easier to reset it when prompted.

What a great idea! So great, in fact, that I thought it could really be a standalone feature and plugin in it’s own right.

Introducing the Expire Passwords plugin for WordPress

Today I released a new plugin for WordPress called Expire Passwords.

This latest product is a continuation on my streak of other plugin releases that also deal with the topic of user session security.

The idea here is pretty simple.

If you have registrations open on your WordPress site, chances are there is a decently-sized group of users that have simply gone MIA. They have accounts, and they might come back later, but you’re just not sure when that will be.

The fact of the matter is, the more active login accounts you have on your site, the more potential opportunities there are for break-ins. And once a hacker is authenticated inside WordPress with the right kind of capabilities, the more opportunities there are to do some real damage.

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.

How to connect Apple TV to a hotel Wi-Fi network

Whenever I take an extended vacation I always bring along the Apple TV.

At the end of a long day filled with adventure and fun it’s nice to unwind with your favorite show on Netflix or rent a new release comedy.

I’ve found that hotel television is still so primitive and annoying. The on-demand movie rentals are limited and very pricey, the regular programming is usually in standard definition, and you’re forced to channel surf without a guide. Ain’t nobody got time for that!

When I book a hotel I always make sure there is free Wi-Fi and that they say there are “flat screens” in every room, this tells me that there must be an HDMI input on it somewhere.

Ah, but my Apple TV doesn’t have a browser! So when the hotel Wi-Fi splash screen pops up asking for confirmation that I “Agree to their terms of use” or to enter some sort of special login, I can’t.

It seems we’re left with no choice but to do some friendly hacking to circumvent this annoying speed bump! 🙂

WordPress challenge: Building a web app from scratch

For the past 7 years I’ve been building websites, themes and plugins for WordPress. It’s really fun, and I love it.

But there are some avenues that I have yet to explore. The biggest one is building a web application using WordPress.

I’m happily employed over at X-Team working full-time on Stream, so I’m really just looking to create another passive income stream for my family. This is not urgent in any way, and if I’m being totally honest with myself, I’m probably just looking to scratch the proverbial entrepreneurial itch I have after selling a business I was running on the side last month.

If I’m going to start a new project, and there is not a strict time table, why not try something new? It will give me a chance to learn some new technologies I’ve not used before, like Backbone.js, and build something that I think is cool.

Parting ways with ChurchThemes.net and looking ahead toward a brighter future

New ChurchThemes.net

Three years ago, in July 2011, I started a theme shop. It was an era where many people in smaller niches were yet to be discovered by developers as a force to be reckoned with. The “The Long Tail” principal hadn’t yet sunk in, at least not enough for churches to have viable WordPress theme options available to them.

Churches were being grossly under-served in every WordPress theme marketplace. The most common option for them was to customize their favorite “photography” or “design agency” theme, somehow seeing past page after page of irrelevant stock imagery and the thousands of “shortcodes” they wouldn’t be using. Sprinkle in a few plugins, and say a prayer – maybe, just maybe, this would work.

WordCamp KC: Version Control Using Git

Version control is a must for any professional web developer, frontend or backend. I had the privelege of speaking this year at WordCamp KC on the topic of Version Control Using Git.

There are many ways to setup Git, but in my talk, the aim was to cover the simplest approach possible so folks could get set up quickly.

This tutorial-style post is meant to provide more detail on how to start using Git on your local environment.

The slides used for this presentation can be seen at: http://www.slideshare.net/fjarrett/wordcamp-kc-2014-version-control-using-git

Get an attachment ID by URL in WordPress

We all know you can use wp_get_attachment_url() to return an attachment’s URL by passing in the ID, but what about the reverse scenario?

There are a lot of long-winded examples of how to get an attachment ID by URL floating around the interwebs. Most of them limit results to only returning images or use expensive DB queries. Really, there should be a function for this in core, but there isn’t.

Needless to say, I wasn’t really happy with any of the solutions I found people using, so I decided to take a stab at it.

Below is the most lightweight method I’ve come up with (so far) to get an attachment ID by passing through an attachment URL.

 * Return an ID of an attachment by searching the database with the file URL.
 * First checks to see if the $url is pointing to a file that exists in
 * the wp-content directory. If so, then we search the database for a
 * partial match consisting of the remaining path AFTER the wp-content
 * directory. Finally, if a match is found the attachment ID will be
 * returned.
 * @param string $url The URL of the image (ex: http://mysite.com/wp-content/uploads/2013/05/test-image.jpg)
 * @return int|null $attachment Returns an attachment ID, or null if no attachment is found
function fjarrett_get_attachment_id_by_url( $url ) {
	// Split the $url into two parts with the wp-content directory as the separator
	$parsed_url  = explode( parse_url( WP_CONTENT_URL, PHP_URL_PATH ), $url );

	// Get the host of the current site and the host of the $url, ignoring www
	$this_host = str_ireplace( 'www.', '', parse_url( home_url(), PHP_URL_HOST ) );
	$file_host = str_ireplace( 'www.', '', parse_url( $url, PHP_URL_HOST ) );

	// Return nothing if there aren't any $url parts or if the current host and $url host do not match
	if ( ! isset( $parsed_url[1] ) || empty( $parsed_url[1] ) || ( $this_host != $file_host ) ) {

	// Now we're going to quickly search the DB for any attachment GUID with a partial path match
	// Example: /uploads/2013/05/test-image.jpg
	global $wpdb;

	$attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->prefix}posts WHERE guid RLIKE %s;", $parsed_url[1] ) );

	// Returns null if no attachment is found
	return $attachment[0];

Example usage

Just as an example, this would echo the attachment ID integer of test-image.jpg onto the page:

echo fjarrett_get_attachment_id_by_url( 'https://frankiejarrett.com/wp-content/uploads/2013/05/test-image.jpg' );

This would echo the same result as above because we are ignoring www usage in the URL being passed through:

echo fjarrett_get_attachment_id_by_url( 'https://frankiejarrett.com/wp-content/uploads/2013/05/test-image.jpg' );

This would echo nothing, because the image doesn’t exist in the WordPress uploads directory:

echo fjarrett_get_attachment_id_by_url( 'https://frankiejarrett.com/foo/test-image.jpg' );

And finally, this would also echo nothing because the URL of the file is pointing to an external domain:

echo fjarrett_get_attachment_id_by_url( 'http://www.anotherdomain.com/wp-content/uploads/2013/05/test-image.jpg' );


We managed to fetch an attachment ID in just a few lines of code with no expensive DB queries! Awesome 😎

Now you can do cool things like turn a URL into an absolute path:

$url = 'https://frankiejarrett.com/wp-content/uploads/2013/05/test-image.jpg';

$attachment_id = fjarrett_get_attachment_id_by_url( $url );

$path = ( $attachment_id ) ? get_attached_file( $attachment_id ) : null;

echo $path;

For more information about what was used in this function, please see:

Was this code helpful to you? Let me know in the comments!