1

我有一个简单的查询:$query = new WP_Query('showposts=5');这显然会显示 5 个最新帖子。有什么方法可以在查询中获取帖子的位置?我的意思是... $query 有 5 个帖子,我需要能够在循环中显示帖子的数量。我不太了解 PHP,但我假设 $query 是一个包含这 5 个帖子的数组变量(?)。

它将用于 JavaScript 滑块中,对于每个帖子,我都会显示一个类似的链接,<a href="#1"></a>并且我需要该数字为 2 用于第二个帖子,3 用于第三个等等。

希望这有任何意义,有人能够帮助我。

在此先感谢,贾斯汀

4

3 回答 3

4

对于更多的防弹行为,我将使用每个帖子的 UID(使用the_ID())创建锚链接,而不是通过它们在页面上的位置。

此外,您应该$query使用循环进行迭代,您可以在一个页面中执行多次。(好久没用wordpress了,这段代码可能有点不对,但概念不错)

<?php 

// Create the Query
$query = new WP_Query('showposts=5');

if ($query->have_posts()) :

    // Create the Javascript slider thing
    while ($query->have_posts()) : $query->the_post();
        // Do stuff here
    endwhile; 

    // Display the posts
    while ($query->have_posts()) : $query->the_post();
        // Do stuff here
    endwhile;

endif;

?>
于 2009-09-03T13:00:22.690 回答
2

$query->current_post 将为您提供循环中当前项目的索引。此外, $query->post_count 为您提供循环中项目的总数。这也可能会有所帮助。

于 2009-11-02T02:01:44.173 回答
1

这并不难(我复制了 cpharmston 的 PHP 代码):

<?php 

// Create the Query
$query = new WP_Query('showposts=5');

if ($query->have_posts()) :

    $i = 1; // for counting

    // Create the Javascript slider thing
    while ($query->have_posts()) : $query->the_post();
        // Do stuff here
        $i++; // make sure this is @ the end of the while-loop
    endwhile;


    $i = 1; // reset $i to 1 for counting

    // Display the posts
    while ($query->have_posts()) : $query->the_post();
        // Do stuff here
        $i++; // make sure this is @ the end of the while-loop
    endwhile;

endif;

?>

您可以将 $i 用于#1、#2 等。每次 while 循环结束时,$i++ 都会确保它以 1 递增(因此在第一次之后 $i = 2 等)。

希望这会有所帮助:)(我确实认为 cpharmston 的解决方案会更容易)。

于 2009-09-03T13:17:32.117 回答