WordPress Advanced Custom Fields - Random Query Repeater by SubField value

我的未来我决定 提交于 2019-12-11 19:53:57

问题


I'm trying to fetch ONE random row of testimonials, however that row must contain a "true" value for sitewide_display subfield.

I can't for the life of me get this to work, this just gives me whatever result it feels like upon refresh.

Is there some sort of conflict with using the conditional for the sub-field value (sitewide_display) within the while loop like this?

<?php $rows = get_field('testimonials' ); // get all the rows ?>
    <?php if( $rows ) : // if there are rows, continue ?>  
         <?php while( has_sub_field('testimonials') ) : ?>   
            <?php if( get_sub_field('sitewide_display')): ?> 
                <?php $rand_row = $rows[ array_rand( $rows ) ]; // get the first row ?>
                <?php  $rand_row_testimonial_name = $rand_row['testimonial_name' ]; // get the sub field value  ?>
                <?php echo $rand_row_testimonial_name; ?>            
            <?php endif; ?> 
    <?php endwhile; ?>
<?php endif; ?>

回答1:


I have solved the issue with the following, if there is a more efficient way go ahead and comment!

<?php

$lists = get_field( 'testimonials' );
shuffle($lists);
if( $lists ){

    $i=0;
    foreach( $lists as $list ){
        if( $list['site-wide_display'] &&  $i < 1){
            echo $list['testimonial_name'];
            $i +=1;
        }


    }
}


?>


来源:https://stackoverflow.com/questions/22011261/wordpress-advanced-custom-fields-random-query-repeater-by-subfield-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!