[英]insert item into wordpress the_posts() while loop
我在 Wordpress 中有一个项目,正在输出主页上的帖子(布局有点复杂,因此有一些 if 语句来确定要使用哪些模板部分)。
但是,我有一个功能是在某个位置显示 1 个特定的帖子(在管理区域中切换) - 基本上是将帖子固定为始终显示在第一个阵列位置。
我目前的编程方式有两个问题;
1 - 固定文章正在替换数组中当前位置的帖子,因此位置一的帖子永远不会显示
2 - 固定的文章很可能出现在 the_posts() 中,所以我不希望它显示两次。
处理这些问题的最佳方法是什么? 我觉得一定有更好的方法
$count = 0;
$rows = 10;
echo '<div class="grid-container grid-rows-' . $rows . '"">';
while ( have_posts() ) : the_post();
if($count === 0 || $count === 9 || $count === 10 || $count === 19){
echo ' <div class="grid-container-item '.$count.'">';
get_template_part( 'template-parts/content', get_post_format() );
echo ' </div>';
}
else{
if($count === 1) {
//display pinned_featurette content
if ( $wpb_pinned_content_query->have_posts() ) :
while ( $wpb_pinned_content_query->have_posts() ) : $wpb_pinned_content_query->the_post();
echo '<div class="grid-container-item pinned_ad">';
get_template_part( 'template-parts/content-min-ad', get_post_format() );
echo '</div>';
endwhile;
wp_reset_postdata();
//if none - place normal content
else :
echo '<div class="grid-container-item '.$count.'">';
get_template_part( 'template-parts/content-min', get_post_format() );
echo '</div>';
endif;
}
else {
echo '<div class="grid-container-item '.$count.'">';
get_template_part( 'template-parts/content-min', get_post_format() );
echo '</div>';
}
}
$count ++;
endwhile;
echo '</div>';
从主页查询中排除固定的帖子 ID
add_action( 'pre_get_posts', function( $query ) { if ( $query->is_main_query() && $query->is_home() ) { $query->set( 'post__not_in', array( 1, 2, 3, '# IDs of the pinned posts' ) ); } }, 100, 1 );
避免在主循环中更换相同位置的柱子
$count = 0; $rows = 10; echo '<div class="grid-container grid-rows-' . $rows . '"">'; while ( have_posts() ) : the_post(); if( $count === 1 ) { //display pinned_featurette content if ( $wpb_pinned_content_query->have_posts() ) : while ( $wpb_pinned_content_query->have_posts() ) : $wpb_pinned_content_query->the_post(); echo '<div class="grid-container-item pinned_ad">'; get_template_part( 'template-parts/content-min-ad', get_post_format() ); echo '</div>'; endwhile; wp_reset_postdata(); endif; } if( $count === 0 || $count === 9 || $count === 10 || $count === 19 ) { echo ' <div class="grid-container-item '.$count.'">'; get_template_part( 'template-parts/content', get_post_format() ); echo ' </div>'; } else { echo '<div class="grid-container-item '.$count.'">'; get_template_part( 'template-parts/content-min', get_post_format() ); echo '</div>'; } $count ++; endwhile; echo '</div>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.