Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

PHP WordPress/Advanced Custom Fields/ PHP Rand

wyclef

Active Coder
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;
}
 
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;
}
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom