Support

Account

Home Forums General Issues Extract year and Month from date picker custom field

Solving

Extract year and Month from date picker custom field

  • I am using date custom fields, and I am automatically populating the custom field values to the categories of the post type

    I also want to group the posts based on the date custom field.
    From date picker I get only date
    I want to store the month and year in separate variable so that I can add them to the categories of respective month and year

    For example: right now my date picker gives me date 07/07/2013
    so I cannot store this date as category as this will be of no use
    I want to extract month as July and year as 2013 from the same date picker custom field in some other variable like $month and $year.

    At the same time I want the date to be displayed

    How to do it?

  • Hi @biomedikal

    Perhaps you could use the update_value filter to run a custom save function.

    The update_value filter is run on every value you save with ACF. It’s native functionality is to save the value to the database, however, you can hook in and do what ever you want.

    Jump over to the docs and check out the filter. You will be able to look at the value saving, and extract the month / year (with an explode function) and then use the native update_postmeta function to save the value to the post!

    Good luck

  • Can you explain with an example Please

  • ACF uses a filter called acf/update_value to save the value into the database. I have set it up as a filter so you can hook in and modify the value before save, or use the value in another way.

    Please read the docs about this filter to understand it with more clarity.

    You would hook in using the field name or key, then use the value that was posted to do what ever you want.

    in your case, you would explode the string to get the day, month and year in an array. Then save the month and array to the database using WP save functions

    Is there anything in particular you don’t understand?

  • In addition to Elliot’s suggested method, if you didn’t want to change the value saved to the database, you could use the DateTime ‘format’ method:

    
    $date = get_field("my_date_field");
    
    // assuming your return format is "Ymd"
    $dateTime = DateTime::createFromFormat("Ymd", $date);
    
    if ( is_object($dateTime) ) {
      $month = $dateTime->format('F');
      $year = $dateTime->format('Y');
      //...
    }
    
Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Extract year and Month from date picker custom field’ is closed to new replies.