Simple age shortcode for WordPress

·

As I was updating the about page on this blog today, I decided that I wanted to make my age in the following string dynamic: “I am a 31-year-old Texan”. After considering options, creating a shortcode seemed like a simple enough route. Here’s the code that I came up with:

/**
 * A simple shortcode for displaying a person's age within WordPress content. This was
 * created with an "about" in mind, so that I wouldn't have to keep updating my age. :)
 * 
 * Usage: [simple_age birthday="January 1 2020"]
 */
function simple_age_shortcode( $atts ) {
	if ( empty( $atts['birthday'] ) ) {
		return '';
	}
	
	// If the birthday couldn't be parsed, then show some numeric output at least \_(?)_/
	$birthday = strtotime( $atts['birthday'] );
	if ( ! $birthday ) {
		return 0;
	}
	
	$time_diff  = time() - $birthday;
	$years_diff = floor( $time_diff / YEAR_IN_SECONDS );
	
	return intval( $years_diff );
}
add_shortcode( 'simple_age', 'simple_age_shortcode');

Then, in my about page, I modified the content to look like this:

I am a [simple_age birthday="January 1 2020"]-year-old Texan...

To add this code to your site, you can add it as a plugin, in the functions.php file of your theme, or you could use a plugin like Code Snippets (which is my favorite option for small bits of code like this).

If you land here, then hopefully you find this simple age shortcode for WordPress handy. ? If there’s some interest, I may consider adding the plugin to the core repo to make it easier for people to use the shortcode. Feel free to leave a comment below if you’d prefer that.

Comments

4 responses to “Simple age shortcode for WordPress”

  1. Rocco Avatar

    As a 39-year-old person who is scared about turning 40, I’ve made a small modification:

    return min( intval( $years_diff ), 39 );

    Forever 39!

  2. Juanma Avatar

    Your code has worked for me! Can you tell me how I can add year and month to show age? Thank you. I am a noob to PHP.

Leave a Reply to JuanmaCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Eric Binnion

Subscribe now to keep reading and get access to the full archive.

Continue reading

Discover more from Eric Binnion

Subscribe now to keep reading and get access to the full archive.

Continue reading