php - 将项目插入wordpress the_posts()while循环
问题描述
我在 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>';
推荐阅读
- json - 如何在 UserInterface Online 中集成 JSON 响应值
- java - 从其图形表示中获取一个字母 (AZ)
- python - 用于添加索引的 SQLAlchemy / Alembic 原始 SQL
- jquery - jquery选择器删除某些元素
- vba - 使用 VBA 向表中添加记录
- python - 如何用正确的 unicode 字符替换转义的 unicode 字符?
- javascript - 如何将对象转换为对象数组?并按 obj.value 排序?
- php - PHP是否等待mysql查询结果?
- javascript - VBA 网络爬虫从 JavaScript 表单访问搜索结果
- java - 如何将 getChildFragmentManager 与扩展对话框片段的类一起使用