[英]Limiting posts in loop
Hi I have a loop with testimonials using advanced custom fields. 嗨,我有一个使用高级自定义字段的推荐函循环。 I need the loop to only loop one post at a time randomly i have tried query_posts but its doest work.
我需要循环一次只能随机循环一个帖子,我已经尝试过query_posts,但是它不起作用。
<?php
query_posts( 'posts_per_page=1&orderby=rand' );
if(get_field('testimonials', 'options')): ?>
<?php while(has_sub_field('testimonials', 'options')): ?>
<ul>
<li class="title"><?php the_sub_field('name'); ?></li>
<li class="site"><a href="<?php the_sub_field('website'); ?>" target="_blank"><?php the_sub_field('website'); ?></a></li>
<li class="desc"><?php the_sub_field('message'); ?></li>
</ul>
<?php endwhile; ?>
<?php endif; ?>
There's a problem with the while loop, you should do it like this: while循环存在问题,您应该这样做:
<?php
$posts = new WP_Query();
$posts->query('posts_per_page=1&orderby=rand');
if (have_posts()) :
while (posts->have_posts()) : $posts->the_post();
if(get_field('testimonials', 'options')): //Ain't no sure what does this ?>
<ul>
<li class="title"><?php the_sub_field('title'); ?></li>
<li class="site"><a href="<?php the_sub_field('website'); ?>" target="_blank">
<?php the_sub_field('website'); ?></a></li>
<li class="desc"><?php the_sub_field('message'); ?></li>
</ul>
<?php
endif;
break; // Exit loop after first post
endwhile;
endif;
?>
Look how i'm using the while loop. 看看我如何使用while循环。 I don't understand what
get_field
does, you should pass the post ID as second parameter. 我不明白
get_field
作用,您应该将帖子ID作为第二个参数传递。
Try this for looping out one post per page: 尝试使用此方法在每页中循环发布一篇文章:
$args = array(
'posts_per_page' => 1,
'orderby' => 'rand'
);
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) :
$the_query->the_post();
echo '<ul>';
echo '<li>' . get_the_title() . '</li>';
echo '</ul>';
echo '<li class="title">'.the_sub_field('name'). '</li>';
echo '<li class="site"><a href="'.the_sub_field('website').'" target="_blank">'.the_sub_field('website').'</a></li>';
echo '<li class="desc">'.the_sub_field('message').'</li>';
endwhile;
wp_reset_postdata();
I found the solution here :) http://www.advancedcustomfields.com/resources/how-to/how-to-query-posts-filtered-by-custom-field-values/ 我在这里找到了解决方案:) http://www.advancedcustomfields.com/resources/how-to/how-to-query-posts-filtered-by-custom-field-values/
<?php
// args
$args = array(
'numberposts' => -1,
'post_type' => 'event',
'meta_key' => 'location',
'meta_value' => 'Melbourne'
);
// get results
$the_query = new WP_Query( $args );
// The Loop
?>
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.