How to add incremental date in PHP

Hello,

If you’re using WordPress and wonder how to set the 4 or 2 digits of the year to auto increment each year, here is a piece of code that can help you do just that. We will use in this case the add Shortcode function from WP core to give the instruction to our code, and add that shortcode wherever needed on a page.

So we will use the Incrementing/Decrementing Operators

For your information:

++$aPre-incrementIncrements $a by one, then returns $a.
$a++Post-incrementReturns $a, then increments $a by one.
–$aPre-decrementDecrements $a by one, then returns $a.
$a–Post-decrementReturns $a, then decrements $a by one.

Our first Shortcode will look like this (you can copy and paste it using CODE SNIPPET).
If you need help in adding snippets to your site, please CLICK HERE to view this tutorial.

				
					// We'll write the shortcode "walup-school-year"  to be used  
add_shortcode( 'walup-school-year', function () {

// Define our Dates Base
$month = date('m');
$year = date('Y');
$sept = '9';

// Use OPERATORS to display the proper school year before or after September
if ($sept > $month) {
return "Current School Year: ".--$year.'-'.++$year;
}
elseif ($month == $sept)
{ return "School Year: ".$year.'-'.($year + '1');
}
else
{ return "School Year: ".$year.'-'.++$year;
}
}
);
				
			

The output of this code will be:  [walup-school-year]

Notice that in php the “++” signs PRIOR the variable $year tells to our code to increment the value of  $year by 1. This will be similar to write ($year + ‘1’).

However if we want to display an upcoming year from the year, then we should do:

				
					// We'll write the shortcode "walup-up-school-year" to be used
add_shortcode( 'walup-up-school-year', function () {

// Define our Dates Base
$month = date('m');
$year = date('Y');
$sept = '9';

// Use OPERATORS to display the proper school year before or after September
if ($sept > $month) {
return "upcoming School Year: ".$year.'-'.++$year;
}
elseif ($month == $sept)
{ return "upcoming School Year: ".($year + '1').'-'.($year + '2');
}
else
{ return "upcoming School Year: ".$year.'-'.++$year;
}
}
);
				
			

and the Output will be:  [walup-up-school-year]

On both code, we have set “$setp” to be the change year trigger. Each time that the month is either equal or less than “$sept” the output adjust and display properly.

To adapt to your need, change the $sept value anywhere between 1 – 12.

Leave a Reply