Carla Dessi
Carla Dessi

Reputation: 9666

PHP loop for number of posts in wordpress

I need to create a slider navigation which has one li for each post. I currently have this code:

<?php
$args = array( 'post_type' => 'slides', 'orderby' => 'menu_order');
$loop = new WP_Query( $args );
?>

<div id="myCarousel" class="carousel slide">
  <ol class="carousel-indicators">

    <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
    <?php while ( $loop->have_posts() ) : $loop->the_post();  $x = 1 ?>
    <li data-target="#myCarousel" data-slide-to="<?php echo $x ?>"></li>
    <?php $x = $x + 1 ?>
    <?php endwhile; ?>

  </ol>

As I need the first one to stay active.. But this isn't quite working for me

Upvotes: 0

Views: 832

Answers (2)

reikyoushin
reikyoushin

Reputation: 2021

try this:

** take note that the $x variable was moved outside the loop so that your data-slide-to value will not all be equal to 1;

<div id="myCarousel" class="carousel slide">
    <ol class="carousel-indicators">

        <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
        <?php $x = 1; ?>
        <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
            <li data-target="#myCarousel" data-slide-to="<?php echo $x++; ?>"></li>
        <?php endwhile; ?>
    </ol>
</div>

** if you are getting extras, it maybe because you have put a static

<li data-target="#myCarousel" data-slide-to="0" class="active"></li>

inside the loop, so what you might want could be this instead:

<div id="myCarousel" class="carousel slide">
    <ol class="carousel-indicators">
        <?php $x = 0; ?>
        <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
            <li data-target="#myCarousel" data-slide-to="<?php echo $x; ?>" <?php echo ($x++==0)?'class="active"':'';?>></li>
        <?php endwhile; ?>
    </ol>
</div>

Upvotes: 1

Anagio
Anagio

Reputation: 3075

You can get the count like this

$posts = new WP_Query( $postargs );
$postcount = $posts ->post_count;

Now do echo $postcount; and you will have the number of posts.

Upvotes: 0

Related Questions