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.
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.
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.