0

次のスクリプトを使用して、WordPress ページに 3 つのエントリを出力しています。

ただし、何らかの理由で、そのリストの最初のエントリのみを出力します。配列内で数値を移動しましたが、まだ 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 に答える