1

I have a repeater field on a page template to show small snippets with a link that needs to be sorted by date (recent 1st). I'm using the current code, but there isn't any sorting in place.

        <?php if(get_field('in_the_news')): ?>
            <?php while(has_sub_field('in_the_news')): ?>
                        <article id="post-<?php the_ID(); ?>" class="open post type-post  format-standard hentry" role="article">

                            <header class="article-header">

                                <h1 class="h2" style="font-size:16px;"><a href="<?php the_sub_field('link'); ?>" rel="bookmark" target="_blank"><?php the_sub_field('title'); ?></a></h1>
                                <p class="byline vcard"><?php the_sub_field('publisher'); ?> - 
                                <?php 
                                //the_sub_field('published_date');
                                /*if(get_sub_field('published_date'))
                                {
                                    $date = DateTime::createFromFormat('Ymd', get_sub_field('published_date'));
                                    echo 'Published: ';
                                    echo $date->format('F j, Y');

                                }*/
                                ?>
<?php 
 //NO PHP 5.3 support. this instead.
$date = get_sub_field('published_date');
// $date = 19881123 (23/11/1988)

// extract Y,M,D
$y = substr($date, 0, 4);
$m = substr($date, 4, 2);
$d = substr($date, 6, 2);

// create UNIX
$time = strtotime("{$d}-{$m}-{$y}");

// format date (23/11/1988)
echo date('d/m/Y', $time);
?>
2

I think this is not possible with the API functions provided by ACF. I would try to save the values to a temporary array first and then sort the values inside the array with php (using krsort() for example).

Something like this (just to give an idea):

while(has_sub_field('in_the_news')) {

    $date = get_sub_field('published_date');
    // $date = 19881123 (23/11/1988)

    // extract Y,M,D
    $y = substr($date, 0, 4);
    $m = substr($date, 4, 2);
    $d = substr($date, 6, 2);

    // create UNIX
    $time = strtotime("{$d}-{$m}-{$y}");

    $tmp_array[$time] = array(
        'link' => get_sub_field('link'),
        'title' => get_sub_field('title'),
        'publisher' => get_sub_field('publisher'),
        'date' => date('d/m/Y', $time)  
    );
}

krsort($tmp_array);

foreach($tmp_array as $entry ) {
    // your html ...
}

PS: It's always better to save timestamps in a proper format (i.e. unix timestamp) in the first place if somehow possible. 19881123 is a strange date format.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.