dongzong2017 2015-08-17 21:30
浏览 141
已采纳

WordPress查询先显示多个标题然后再显示内容然后重复循环

I want to have 2 columns of titles followed 2 rows of content and then repeat until query is done.

Example:

<div><?php the_title(); ?></div>
<div><?php the_title(); ?></div>

<div><?php the_content(); ?></div>
<div><?php the_content(); ?></div>


<div><?php the_title(); ?></div>
<div><?php the_title(); ?></div>

<div><?php the_content(); ?></div>
<div><?php the_content(); ?></div>

Here is my current code

<?php  
$teams = new WP_Query(array(  
'post_type' =>  'team-post'
)  
);  
if ($teams->have_posts()) : while  ($teams->have_posts()) : $teams->the_post();?>

<?php if( $teams->current_post%2 == 0 ) echo "
".'<div class="row">'."
"; ?>

<div class="col-md-6"><?php the_title(); ?></div>

<?php if( $teams->current_post%2 == 1 || $teams->current_post == $teams->post_count-1 ) echo '</div> <!--/.row-->'."
"; ?>

<div class="col-md-12"><?php the_content(); ?></div>

<?php endwhile; endif; wp_reset_query();?>

The problem with the query is that it runs through each entry and outputs first TITLE then CONTENT which is the norm. Id like to be able to have 2 TITLES first then the CONTENT for those 2 entries, then repeat.

  • 写回答

1条回答 默认 最新

  • duangu6588 2015-08-18 14:38
    关注

    You can't do what you want to do by looping through the posts that way. You'd need to write a for loop and use an incrementing number to get the two posts at a time.

    If it were me I'd take a look at the HTML/CSS structure and see if there's a better way to achieve the desired effect but if you're pretty set on a PHP solution something like this will work:

    $teams = new WP_Query( array( 'post_type' => 'team-post' ) );
    
    $total_posts = count( $teams->posts );
    
    for ( $i = 0; $i < $total_posts; $i += 2 ) {
    
        $left_post = $teams->posts[ $i ];
    
        $right_post = ( isset( $teams->posts[ $i + 1 ] ) ) ? $teams->posts[ $i + 1 ] : false;
        ?>
        <div class="row">
            <div class="col-md-6"><?php echo get_the_title( $left_post->ID ); ?></div>
            <?php if ( $right_post ) { ?>
                <div class="col-md-6"><?php echo get_the_title( $right_post->ID ); ?></div>
            <?php } ?>
    
            <div class="col-md-12"><?php echo apply_filters( 'the_content', $left_post->post_content ); ?></div>
            <?php if ( $right_post ) { ?>
                <div class="col-md-12"><?php echo apply_filters( 'the_content', $right_post->post_content ); ?></div>
            <?php } ?>
        </div>
        <?php
    }
    

    This also takes into account the possibility of an odd number of posts.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度