您好我有一个使用高级自定义字段的推荐信循环。我需要循环只能随机循环一个帖子我已经尝试过query_posts但它的doest工作。
<?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; ?>
答案 0 :(得分:1)
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;
?>
看看我是如何使用while循环的。我不明白get_field
的作用,你应该将帖子ID作为第二个参数传递。
答案 1 :(得分:0)
尝试使用此功能每页循环播放一个帖子:
$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();
答案 2 :(得分:0)
我在这里找到了解决方案:) 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(). ?>