0
$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

1

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>
  • it does not generate anything, if I delete, $i=0 and $i++; .. yes, but no working increase the number – Juan David Oct 16 '17 at 13:44
  • It needs to be <?php echo $i; ?>, the rest of the answer is correct – kero Oct 16 '17 at 14:03
  • @kero still no work :/ – Juan David Oct 16 '17 at 14:07
  • add for ($n = 0; $n <= 7; $n++) and <?php echo ($n + 1) ?> and work – Juan David Oct 16 '17 at 14:38
  • This will fail if you have more than 7 items returned. You could store $wp_query->post_count in a variable and run the loop accordingly – Sneha Agarwal Oct 16 '17 at 14:48
1
    $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>
  • why repeat number ..now show 1, 1, 1, 2, 2, 2 :/ @sneha-agarwal – Juan David Oct 16 '17 at 15:13
  • ready! working perfect! – Juan David Oct 16 '17 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.