If you are looking forward to print a date on the web page of your WordPress website, this article is for you. The Date function is built-in and used to format the timestamp. Here, it’s worth to mention that the computer stores date and time in UNIX timestamp. This time is measured as a number of seconds since Jan 1, 1970. Since this is impractical for humans to read, PHP converts timestamp to a format that is readable and more understandable to humans. In this article, we’ll see how to get current year on WordPress using PHP code?
To print current year value, you can use WordPress or PHP date functions. So you’ve three ways to scale this. All of the three ways are mentioned below. You can try them as per your convenience and requirement.
How to get current year on WordPress using PHP code?
On WordPress, you’ve two date functions:
1. Using the_date function
First function is the_date and you can use it like this:
the_date( string $format = '', string $before = '', string $after = '', bool $echo = true )
A common example of this code is as follows:
<?php the_date( 'Y-m-d', '<h2>', '</h2>' ); ?>
This will print 2021-06-03 inside <h2> tags.
To print only year value, you can use this code:
<?php the_date( 'Y', '<h2>', '</h2>' ); ?>
2. Using get_the_date function
You can also use get_the_date function to print year. General syntax for get_the_date is:
get_the_date( string $format = '', int|WP_Post $post = null )
An example to use this code:
<?php echo get_the_date('dS M Y'); ?>
This will print a date as 1st Jun 2021.
To print only year with this code:
<?php echo get_the_date('Y'); ?>
3. Using date function of PHP
The date function can be used as date( format, timestamp )
.
To print year with date function, use following PHP code:
<?php echo date("Y"); ?>
You can use following format options with above codes:
- d – To print the day of the month. It uses two digits with leading zeros (01 or 31).
- D – To print day of the week in the text (Mon to Sun).
- m – To print month in numbers with leading zeros (01 or 12).
- M – To print month in text, abbreviated (Jan to Dec).
- y – To print year in two digits (08 or 14).
- Y – To print year in four digits (2020 or 1998)
So this is how are you can print a current to your value on your webpage.