首页 > 解决方案 > 如何在 WordPress 中使 HTML 元素不在循环内循环

问题描述

这有可能在WordPress中制作这样的帖子列表吗?

<div class="large-image">
  <img src="http://example.com">
  <h1>Title</h1>
</div>
<div class="post-row"><!-- this is not a loop -->
  <div class="post-item"><!-- this is a loop -->
    <img src="http://example.com">
    <h1>Title</h1>
  </div>
  <div class="post-item"><!-- this is a loop -->
    <img src="http://example.com">
    <h1>Title</h1>
  </div>
</div>

我尝试使用下面的代码,但<div class="post-row">始终包含在循环中。

<?php 

if ( have_posts() ) : $post_count = 0;
  while ( have_posts() ) : the_post();
    if ( $post_count = 0 ) { ?>

      <div class="large-image">
        <img src="http://example.com">
        <h1>Title</h1>
      </div>

<?php } ?>

<div class"post-row">

<?php if ( $post_count > 0 ) { ?>

  <div class="post-item"><!-- this is a loop -->
    <img src="http://example.com">
    <h1>Title</h1>
  </div>

<?php } ?>

</div><!-- /post-row -->

<?php
  endwhile
endif; 
?>

我想要的<div class="post-row">不是循环。

我在stackoverflow中尝试了一些答案,但post-row总是循环。

希望我得到最好的答案。

标签: phpwordpress

解决方案


您必须将后行 div 移动到 while 循环上方,您只是错过了放置它而已


<?php if ( have_posts() ) : $post_count = 0; 

if ( $post_count == 0 ) { ?>

      <div class="large-image">
        <img src="http://example.com">
        <h1>Title</h1>
      </div>

<?php } ?>

<div class"post-row">

<?php

  while ( have_posts() ) : the_post();


  if ( $post_count > 0 ) { ?>

  <div class="post-item"><!-- this is a loop -->
    <img src="http://example.com">
    <h1>Title</h1>
  </div>

<?php } 

$post_count ++;

 endwhile; ?>

</div><!-- /post-row -->

<?php endif; ?>

推荐阅读