問題描述

我正在 WordPress 工作,我有以下代碼在循環內發帖。

        <?php
                $posts = $woo_options['woo_latest_entries'];
                query_posts('post_type=post&category_name=company');
                if ( have_posts() ) : while ( have_posts() ) : the_post(); $count++;

        ?>

        /// Post Content Goes Here //

        <?php endwhile; endif; ?>

哪個輸出帖子裏面的循環這樣的東西…

Post Goes Here ....

Other Post Goes Here ....

Another Post Goes Here ....
.....

我想要的是在循環中打印當前帖子索引號。例

 1. Post Goes Here ....

 2. Other Post Goes Here ....

 3. Another Post Goes Here ....
 .....

我該如何實現?謝謝。

編輯

噢!我可以這樣做..

<?php
echo $wp_query->current_post +1;
?>

有沒有其他/更好的方式?

最佳解決方案

Actually I want to assign ID’s as per post index !

這是您修改的代碼。

<?php

global $wp_query;

$posts = $woo_options['woo_latest_entries'];
query_posts('post_type=post&category_name=company');

if ( have_posts() ) : while ( have_posts() ) : the_post();  $count++;
    $index = $wp_query->current_post + 1;

?>
    <div id="my_post_<?php echo $index; ?>">

        <!-- Post Content Goes Here -->

    </div>

<?php endwhile; endif; ?>

次佳解決方案

如果這只是一件美學的事情,你不需要使用 count 變量來進一步編碼,你可以把你的帖子包裝在一個 ol 標籤中:

<?php if ( have_posts() ) : ?>

    <ol>

        <?php while ( have_posts() ) : the_post(); ?>

            <li> <!-- Post Content Goes Here --> </li>

        <?php endwhile; ?>

    </ol>

<?php endif; ?>

第三種解決方案

由於某種原因,您已經在循環中有一個計數器變量; 如果這不用於其他目的,只需回覆:

<?php echo $count.'.'; ?> /// Post Content Goes Here //

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。