0

嗨,我有一个使用高级自定义字段的推荐循环。我需要循环一次只随机循环一个帖子我已经尝试过 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; ?> 
4

3 回答 3

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 作为第二个参数传递。

于 2013-03-10T13:51:10.587 回答
1

试试这个循环出每页一个帖子:

    $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();
于 2013-03-10T16:54:19.183 回答
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(). ?>
于 2013-03-13T10:53:02.843 回答