0

我正在使用以下脚本将 3 个条目输出到我的 WordPress 页面上。

但是,由于某种原因,它只输出该列表中的第一个条目。我在数组中移动了数字,它仍然只输出 1 <div> 尽管肯定有 ID 为 1、4 和 31 的帖子。

任何想法如何解决这一问题?

        <?php $thePostIdArray = array("1","4","31"); ?>
        <?php $limit = 3; ?>
        <?php if (have_posts()) : ?>
            <?php while (have_posts()) : the_post(); $counter++; ?>
                <?php if ( $counter < $limit + 1 ): ?>
                    <div class="post" id="post-<?php the_ID(); ?>">
                    <?php $post_id = $thePostIdArray[$counter-1]; ?>
                    <?php $queried_post = get_post($post_id); ?>
                    <h2><?php echo $queried_post->post_title; ?></h2>
                    </div>
                <?php endif; ?>
            <?php endwhile; ?>
        <?php endif; ?>

非常感谢您的任何指点。

4

3 回答 3

1

我会这样做:

<?php 
$thePostIdArray = array(1, 4, 31);
$limit = 3; 
$counter = 0;

foreach( $thePostIdArray as $post_id ){
        $counter++;

        if ( $counter > $limit )
            break;

        $queried_post = get_post($post_id);
        echo '<div class="post" id="post-'.$post_id.'">
                <h2>'.$queried_post->post_title.'</h2>
              </div>';    

} // endforeach
?>
于 2012-05-21T14:16:46.550 回答
1

您使用计数器和 get_post 有什么特别的原因吗?如果不是,那么执行以下操作会简单得多:

<?php 
$post_ids = array(1, 4, 31);

//Use post__in to grab the posts that you're interested in (stored in the variable above) and posts_per_page to specify that you want to show all posts.  You can use other parameters for ordering etc if you want

query_posts(array('post__in' => $post_ids 'posts_per_page' => -1)); 

if (have_posts()) : while (have_posts()) : the_post(); ?>

<?php the_title();?>
    //Use regular wordpress template tags here - no real need to use get_post

<?php endwhile; ?>
<?php endif; ?>
于 2012-05-21T14:27:27.333 回答
0

have_posts()是 Wordpress 如此亲切地称呼它的“循环”的一部分。您的代码不会修改此循环。将帖子默认设置为根据您正在查看的页面设置帖子数据。对于静态编码的东西,试试这个:

<?php $PostIdArray = array(1, 4, 31);
foreach($PostIdArray as $ID) {
    $my_post = get_posts($ID); ?>
    <div class="post" id="post-<?php echo $ID; ?>">
    <h2><?php echo $my_post->post_title; ?></h2>
    </div>
<?php
}
?>
于 2012-05-21T14:21:49.863 回答