How to Expire an Advanced Custom Fields Field


Expiring an advanced custom field can come in handy when you have an announcement field or some other set of data that you only want to show for a certain amount of time. In the case we are going to examine below we wanted to create an options field that would expire after a certain amount of time. This is going to be used on a website to make weather closure announcements and such. We want to be able to set an expiration for the field so we can set the announcement and don’t have to worry about coming back to remove it after the event.

Here is how we accomplished this.

First, create your field that you want to contain your content in Advanced Custom Fields.  Next, create a date field using the Date Time Picker field type.  We ,made this field required so you don’t forget to choose a date.  While you are in the date field you need to set the return format for your date.  This part is important and if you don’t get it right your dates will not accurately calculate.

In the date Return Format field select “custom” and then put: YmdHis

It should look like this:

You can set your date display format to be whatever is easiest for you.  We just left it as the default.

Setting up your template

Next, we are going to setup our code to add to our template.  It is important to note that you server may have a different default timezone set on it than you have setup on your WordPress installation or even where you reside.  For that reason we have to tell it what timezone we want to use for this function.  Below is  the entire bit of code we used to retrieve our announcement and wrap it in an expiration:

 

The code has comments to tell you what is what. It is important to you use the same date format for today’ date as we did for the expiration format which is “YmdHis”. Also keep in mind we are using the “options” field in Advanced Custom Fields in the example above. If you are not using the option field then be sure to remove ‘option’ from lines 6 and 6.

You should now be able to control when your field displays based on your expiration date in Advanced Custom Fields.

We put this snippet together with the help of Elliot’s post here: https://support.advancedcustomfields.com/forums/topic/using-date-picker-to-set-post-expiry-date/

Leave a Reply

avatar
  Subscribe  
Notify of