Last active
November 21, 2024 19:47
-
-
Save nathaningram/e55592ef402547d5ce47be78f6dcddd5 to your computer and use it in GitHub Desktop.
Starter Site 2024 Course - MU Shortcodes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /* | |
| Plugin Name: Custom Shortcodes | |
| Description: Add Custom Shortcodes | |
| Plugin URI: https://wpnathan.com | |
| Version: 2024.11 | |
| 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