col-sm-offset-2
,如果列为1,则为col-sm-offset-4
。
$category = get_post_category();
$relatedArticles = get_posts( [
'exclude' => $post->ID,
'category' => $category->term_id,
'posts_per_page' => 3
] );
?>
<?php if ( count( $relatedArticles ) > 0 ): ?>
<section class="related-articles">
<div class="container">
<div class="row">
<h2 class="text-center"><?php echo __( 'Related Articles' ) ?></h2>
<?php foreach ( $relatedArticles as $relatedArticle ): ?>
<div class="col-sm-4">
<article id="" class="post">
<div class="post-image">
<a href="<?php echo get_permalink( $relatedArticle ) ?>">
<?php echo get_the_post_thumbnail( $relatedArticle, 'post-category' ) ?>
</a>
</div>
<h3 class="post-title">
<a href="<?php echo get_permalink( $relatedArticle ); ?>">
<?php echo get_post_title($relatedArticle) ?>
</a>
</h3>
<div class="post-summary">
<p><?php echo get_summery($relatedArticle);?></p>
</div>
</article>
</div>
<?php endforeach; ?>
</div>
</div>
</section>
<?php endif ?>
答案 0 :(得分:2)
您可以为包含该文章的div
的开始标记添加if / else子句,在不同版本中添加所需的类(仅适用于第一篇文章 - 我为其添加了一个计数器) :
$category = get_post_category(); $relatedArticles = get_posts( [ 'exclude' => $post->ID, 'category' => $category->term_id, 'posts_per_page' => 3 ] ); ?>
<?php if ( count( $relatedArticles ) > 0 ): ?>
<section class="related-articles">
<div class="container">
<div class="row">
<h2 class="text-center">
<?php echo __( 'Related Articles' ) ?>
</h2>
<?php $counter = 1; ?>
<?php foreach ( $relatedArticles as $relatedArticle ): ?>
<?php if ( count( $relatedArticles ) >= 3 ) { ?>
<div class="col-sm-4">
<?php } elseif (( count( $relatedArticles ) == 2) && ($counter == 1)) { ?>
<div class="col-sm-4 col-sm-offset-2">
<?php } elseif (( count( $relatedArticles ) == 1) && ($counter == 1)) { ?>
<div class="col-sm-4 col-sm-offset-4">
<?php } ?>
<article id="" class="post">
<div class="post-image">
<a href="<?php echo get_permalink( $relatedArticle ) ?>">
<?php echo get_the_post_thumbnail( $relatedArticle, 'post-category' ) ?>
</a>
</div>
<h3 class="post-title">
<a href="<?php echo get_permalink( $relatedArticle ); ?>">
<?php echo get_post_title($relatedArticle) ?>
</a>
</h3>
<div class="post-summary">
<p>
<?php echo get_summery($relatedArticle);?>
</p>
</div>
</article>
</div>
<?php $counter++; ?>
<?php endforeach; ?>
</div>
</div>
</section>
<?php endif ?>