DEV Community


Posted on

3-Letter Months with ACF and PHP

I only have a few months of experience working with Wordpress, so there are a lot of small victories, and I'm learning more each day. I have at least one AH-HA! moment each week from solving something with code, which is so rewarding.

This week my moment came from learning how to truncate dates in PHP for a Wordpress site. The design called for showing event dates, but only including the first three letters of the month. That way the month would always fit within its container. One way to do this could be having the client just manually type the first three letters into a text field for the event date. Though a more elegant solution is to offer them a calendar for picking the date, and adding a function to reduce the month name to three letters, so there's less room for error on the client's end, and it all happens behind the scenes. Here's how I did it:

First I built custom fields for the event date and event time using Advanced Custom Fields.

Advanced Custom Fields for Event Date Example

I use a custom option to return just the month and the day (F j). We will refer to the F for formatting it before karate chopping it into its first three letters later on.

Advanced Custom Field for Event custom date return

I also made a custom post type for Events which is why you will see $posts = get_field('events'); in the complete code below.

After creating a few events and relating them to the Events page, I loop through all of the event posts, getting the date with DateTime and setting it to a variable in the events page. Then I use PHP's substr function to only display the first three letters of the month, and format to return the day. The substr function takes three arguments: a string, an integer for the start location, and an integer for the the end of the desired truncated string. Since I want to display 3 letters, the start is 0 and the end is 3. That's it! Here is the whole loop.

Top comments (3)

nickyoung profile image
Nick Young

I love that you were able to create a solution to your problem, that's so awesome and really what programming is all about!

I just also want to share with you that instead of doing format( 'F' ); you could instead use format( 'M' ); and it will automatically return you the first three letters of the month. You can learn more about all of the PHP date functions here if you have not seen this:

Again, I share this to help and not to take away from anything you worked so hard on. Keep doing amazing things!


aellon profile image
Aellon • Edited

Wow thank you so much! I'm new to PHP so now I know for the future. I love that there are alternative ways of solving the problem. It was fun to figure it out!

nickyoung profile image
Nick Young

That's my favorite thing about can sit 5 people down to solve the same problem and at the end have 5 totally different answers. It's like the most amazing evolving puzzle ever lol.