douti9253 2016-11-10 15:35
浏览 9
已采纳

在while循环中查找位置

I have created a while loop in WordPress where by it outputs some custom field and post data. What I want to do is look inside the loop and check to find if a field matches to highlight the field and also output its position from the iteration.

My users have a field in their profile called 'schoolname' which I wan to reference against.

$user_info = get_userdata(1);

echo $user_info->schoolname; 

$i= 1;

$loop = new WP_Query( 
array( 'post_type' => 'schools', 
       'posts_per_page' => -1, 
       'orderby' => 'signups',
       'order'   => 'ASC', ) 
); 

while ( $loop->have_posts() ) : $loop->the_post(); 

echo '<tr>
      <td>' . $i++ . '</td>
      <td>' . get_the_title() . '</td>
      <td>' . $signups = get_field( "signups") . ' Signups</td>
      </tr>';

 endwhile; wp_reset_query();
  • 写回答

1条回答 默认 最新

  • dsf323233323332 2016-11-10 15:46
    关注

    To get the state of your loop you could also use a foreach

    <?php global $post; // required
    
    $posts = get_posts();
    foreach($posts as $state => $post) : setup_postdata($post);
    ...
    endforeach;
    ?>
    

    You can replace the while part with the foreach part. To know the iteration number just use$state`.

    Update

    <?php
    $posts = get_posts(array( 'post_type' => 'schools', 
           'posts_per_page' => -1,
           'orderby' => 'signups',
           'order'   => 'ASC',
    ));
    ?>
    
    <?php if ($posts): ?>
        <?php foreach ($posts as $key => $post): ?>
            <?php setup_postdata($post); ?>
            <tr>
                <td><?= $key; ?></td>
                <td><?= get_the_title(); ?></td>
                <td><?= get_field( "signups"); ?> Signups</td>
            </tr>
        <?php endforeach; ?>
        <?php wp_reset_postdata(); ?>
    <?php endif; ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi