WordPress/Advanced Custom Fields/ PHP Random Help

Joined
Mar 25, 2021
Messages
28
Reaction score
0
Hey, I have this PHP/ACF code for WP that pulls the latest 2 entries and am wondering how to adjust this so it would just pull random entries instead. Thanks!

PHP:
function getLatestPhotos() {
    if(get_field('photos', 34)) {
        $latestPhotos = '<ul class="photo-list">';
        $paperCounter = 0;

        while(has_sub_field('photos', 34) && $paperCounter < 2) {
            $latestPhotos .= '<a href="/photos/">';
            $latestPhotos .= get_image_with_alt('cover', get_the_ID(), '');
            $latestPhotos .= '<p>'.get_sub_field('title').'</p>';
            $latestPhotos .= '<span class="name">'.get_sub_field('name').'</span>';
            $latestPhotos .= '</a>';

            $paperCounter++;
        }

        $latestPhotos .= '</ul>';
    }
    return $latestPhotos;
}
 
Joined
Mar 25, 2021
Messages
28
Reaction score
0
Took out $paperCounter for now to try and get 1 random one pulled and have it functioning with the exception of the get_image_with_alt line. Any clue how I could pull 2 randoms, and adjust that line? Feel like I am getting close but need a bit of help.

PHP:
function getLatestPhotos() {
    if(get_field('photos', 34)) {
        $rows = get_field('photos', 34);
        $row_count = count($rows);
        $i = rand(0, $row_count - 1);

        echo $rows[$i]['sub_field_name'];

        $latestPhotos .= '<a href="/photos/">';
        $latestPhotos .= get_image_with_alt('cover', get_the_ID(), '');
        $latestPhotos .= '<p>'.$rows[$i]['title'].'</p>';
        $latestPhotos .= '<span>'.$rows[$i]['name'].'</span>';
        $latestPhotos .= '</a>';

    }
    return $latestPhotos;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top