Loop increase number

$args = array(
'post_type' => 'events',
'order' => 'ASC',
);
$wp_query = new WP_Query($args);
?>

<script type="application/ld+json">
    {
      "@context":"http://schema.org",
      "@type":"ItemList",
      "itemListElement":[
      <?php while ( have_posts() ) : the_post(); ?>
        {
          "@type":"ListItem",
          "position":1,
          "url":"<?php the_permalink(); ?>"
        },
      <?php endwhile; ?>
      ]
    }
    </script>

I am putting a schematic to display a Carousels, but it is required to place the "position": 1

I need help for the loop to increase the number 1. “position”: 1

also remove last comma from last post

2

Answers


  1. Juan David
    0 Votes
        $args = array(
          'post_type' => 'events',
          'order' => 'ASC',
          'posts_per_page' => 5,
        );
        $wp_query = new WP_Query($args);
        ?>
    
    <script type="application/ld+json">
        {
          "@context":"http://schema.org",
          "@type":"ItemList",
          "itemListElement":[
          <?php
            $comma = ",";
            $i=0;
            while ( have_posts() ) : the_post();
            $i++;
            ?>
    
            {
              "@type":"ListItem",
              "position":"<?php echo $i; ?>",
              "url":"<?php the_permalink(); ?>"
            }<?php if($i!=5){
              echo $comma;
            }?>
          <?php endwhile; ?>
          ]
        }
        </script>
    
  2. Sneha Agarwal
    0 Votes

    You can add a php variable and increment it every time the while loop runs

    $args = array(
      'post_type' => 'events',
      'order' => 'ASC',
    );
    $wp_query = new WP_Query($args);
    ?>
    
    <script type="application/ld+json">
        {
          "@context":"http://schema.org",
          "@type":"ItemList",
          "itemListElement":[
          <?php 
            $i=0;
            while ( have_posts() ) : the_post();
            $i++; ?>
            {
              "@type":"ListItem",
              "position":"<?php echo $i; ?>",
              "url":"<?php the_permalink(); ?>"
            },
          <?php endwhile; ?>
          ]
        }
    </script>
    
Please signup or login to answer this question.

Signup for an account and start participating in our site today!




Social Signup

You can also login with your Facebook, Twitter or Linkedin account

Log in with Facebook