Loop increase number

时间:2017-10-16 作者:Juan David

$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>
我正在放置示意图以显示旋转木马,但需要放置"position": 1

我需要帮助循环增加数字1。“位置”:1

同时从最后一篇文章中删除最后一个逗号

2 个回复
SO网友:Sneha Agarwal

您可以添加一个php变量,并在每次while循环运行时递增它

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

SO网友:Juan David
    $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>
结束