Skip to content

Instantly share code, notes, and snippets.

@nathaningram
Last active December 1, 2025 20:37
Show Gist options
  • Select an option

  • Save nathaningram/34dcf5821c6a6787d42a539ab1c9ebb7 to your computer and use it in GitHub Desktop.

Select an option

Save nathaningram/34dcf5821c6a6787d42a539ab1c9ebb7 to your computer and use it in GitHub Desktop.
Starter Site 2025 - MU Shortcodes
<?php
/*
Plugin Name: Custom Shortcodes
Description: Add Custom Shortcodes
Plugin URI: https://wpnathan.com
Version: 1.0
Author: Nathan Ingram
Author URI: https://wpnathan.com
License: GPL2
*/
// Security Check
if (!defined('ABSPATH')) {
die();
}
//Current Year Shortcode
function ni_year_shortcode() {
$year = date('Y');
return $year;
}
add_shortcode('year', 'ni_year_shortcode');
// Years Since Shortcode
// Usage [years-since y=2012-03-01]
// Note, will also accept just YYYY or YYYY-MM assuming the first day of those time periods
add_shortcode('years-since', 'bww_years_since_shortcode');
function bww_years_since_shortcode($atts) {
if (!isset($atts['y'])) {
return __('Year is required.', 'years-since');
}
$y = $atts['y'];
// Validate and parse the `y` input
if (preg_match('/^\d{4}$/', $y)) {
// Format: YYYY, assume January 1
$date = "$y-01-01";
} elseif (preg_match('/^\d{4}-\d{2}$/', $y)) {
// Format: YYYY-MM, assume the first day of the month
$date = "$y-01";
} elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $y)) {
// Format: YYYY-MM-DD, use as is
$date = $y;
} else {
return __('Invalid date format. Use YYYY, YYYY-MM, or YYYY-MM-DD.', 'years-since');
}
// Ensure the date is valid
if (!strtotime($date)) {
return __('Invalid date.', 'years-since');
}
$difference = date_diff(date_create($date), date_create());
// Return the formatted time difference
if ($difference->y < 1 && $difference->m < 1) {
if ($difference->d / 7 > 1) {
return bww_string_return($difference->d / 7, __('week', 'years-since'), __('weeks', 'years-since'));
}
return bww_string_return($difference->d, __('day', 'years-since'), __('days', 'years-since'));
}
if ($difference->y < 1) {
return bww_string_return($difference->m, __('month', 'years-since'), __('months', 'years-since'));
}
return bww_string_return($difference->y, __('year', 'years-since'), __('years', 'years-since'));
}
function bww_string_return($time, $singular, $plural) {
return sprintf(
_n('%d ' . $singular, '%d ' . $plural, $time, 'years-since'),
number_format_i18n($time)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment