【发布时间】:2022-01-23 01:00:36
【问题描述】:
我在 wordpress 中有一个自定义帖子类型,可以将新代理添加到一行。如何创建一个条件语句来检查行中的帖子数量,如果超过 4 个帖子创建一个新 div 并将新帖子附加到新行?
<?php get_header(); ?>
<div class="agent-wrap">
<?php
$args = array(
'post_type' => 'agents',
'post_status' => 'publish',
'posts_per_page' => '12'
);
$agents_loop = new WP_Query( $args );
if ( $agents_loop->have_posts() ) : ?>
<div class="agent-row">
<?php
while ( $agents_loop->have_posts() ) : $agents_loop->the_post();
// variables
$name = get_field( 'agent_name' );
$position = get_field( 'agent_position' );
$phone = get_field( 'agent_phone' );
$email = get_field( 'agent_email' );
$image = get_field( 'agent_image' );
$link = get_the_permalink();
?>
<a href="<?php echo $link; ?>">
<div class="agent">
<div class="agent-bg"></div>
<div class="agent-content">
<h3><?php echo $name; ?></h3>
<h5><?php echo $position; ?></h5>
<hr class="divider" />
<a href="tel:<?php echo $phone; ?>"><?php echo $phone; ?> <i class="fa fa-phone"></i></a>
<a href="mailto:<?php echo $email; ?>"><?php echo $email; ?> <i class="fa fa-envelope"></i></a>
</div>
<img src="<?php echo $image; ?>">
</div>
</a>
<?php
endwhile;
wp_reset_postdata();
endif;
?>
</div>
</div>
<?php get_footer(); ?>
所需的 HTML 结构
<div class="agent-row">
<!-- only 4 agents post types per row -->
<div class="agent"></div>
<div class="agent"></div>
<div class="agent"></div>
<div class="agent"></div>
</div>
<!-- New Row After first row reaches 4 agent posts -->
<div class="agent-row">
</div>
【问题讨论】:
-
你能解释一下“如果大于 4 创建一个新 div 并将新帖子附加到新行”是什么意思吗?我的意思是你可以在你的问题中包含
html结构吗? -
我的解释可能不是正确的思考方法。基本上代理是自定义帖子,而“agent-row”类的 div 是父级,我只想要每个代理 4 个帖子-行,如果在 4 之后有更多代理帖子,我想创建一个带有“agent-row”类的新 div,并将其他帖子附加到新行中。如果添加了更多代理帖子类型,则此循环需要继续。没有其他 html 结构...我将编辑帖子以希望更容易理解我的要求
标签: php wordpress conditional-statements