skip to Main Content

I use ACF pro for my wordpress.
My datepicker field is a repeater field.

I need to return only the day.

my code :

<?php   
if( have_rows('dates') ):
while ( have_rows('dates') ) : the_row();
echo get_sub_field('date')."</br>";
endwhile;
else :
echo __( 'No dates available.','mywebsite' );
endif;
?>

3

Answers


  1. The get_sub_field() function would typically return a string depending on the field type. This instance it will return a timestamp as as string eg ‘2021-06-28 10:28:00’

    If you want to return the day only you could use PHP’s strtotime function which will then return you a datetime epoch integer – this can then be used in conjunction with php’s date function to print as the day. Here is a list of the formats you can use for the date function : PHP DateTime::format

    Example :

    <?php   
    if (have_rows('dates')):
      while (have_rows('dates')) : the_row();
        $dateTime = strtotime(get_sub_field('date'));
        echo("Day : " . date('l', $dateTime) . "</br>");
      endwhile;
    else :
      echo __('No dates available.', 'mywebsite');
    endif;
    ?>
    
    Login or Signup to reply.
  2. As another solution which is within your setup rather than your code – change the ‘Return Format’ of the actual field.

    See : ACF Date Time Picker Docs

    Examples would be :

    • ‘d’ – Day of the month, 2 digits with leading zeros
    • ‘j’ – Day of the month without leading zeros
    • ‘D’ – A textual representation of a day, three letters
    • ‘l’ – A full textual representation of the day of the week

    Then your original code will output the correct format :

    <?php   
    if( have_rows('dates') ):
      while ( have_rows('dates') ) : 
        the_row();
        echo('Day: ' .  get_sub_field('date') . "</br>"); //This will now output your 'Return Format' in ACF setup
      endwhile;
    else :
      echo __( 'No dates available.','mywebsite' );
    endif;
    ?>
    
    Login or Signup to reply.
  3. You can set the return value of the date field.

    enter image description here

    EDIT

    Ok, so if you want to display two dates, one full and one is only day, you first need the return value to be the full date, for this example lets day it d/m/Y

    $full_date = get_sub_field('date'); // the full date (format d/m/Y);
    $day_from_date = DateTime::createFromFormat('d/m/Y', $full_date)->format('d'); // will get the day from the $full_date
    

    This will get you the result you need.

    See DateTime::createFromFormat for more information about the method

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search