【发布时间】:2020-04-05 15:23:27
【问题描述】:
我知道以前有人问过这个问题。我检查了这个网站上的多个答案, 例如:
Wordpress loop with different bootstrap columns
...但我不知道如何将答案与我的代码集成(假设这是可能的)。
我想在页面上显示类别列表及其相关帖子。
我使用的代码工作正常,但在页面下方的单列中显示结果:
如果可能,我想将显示分成 2 列,如下图所示:
我正在使用的代码(目前放在新的页面模板中)如下:
<?php
/*
* Template Name: Alphabetical List
*/
get_header();
// Grab all the categories from the database that have posts.
$categories = get_terms( 'category', 'orderby=name&order=ASC');
// Loop through categories
foreach ( $categories as $category ) {
// Display category name
echo '<h2 class="post-title">' . $category->name . '</h2>';
echo '<div class="post-list">';
// WP_Query arguments
$args = array(
'cat' => $category->term_id,
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
?>
<p><a href="<?php the_permalink();?>"><?php the_title(); ?></a></p>
<?php
} // End while
} // End if
echo '</div>';
// Restore original Post Data
wp_reset_postdata();
} // End foreach
get_footer();
?>
想知道是否有人可以帮助我获取此代码以在 2 列中显示循环结果。
非常感谢。
问题更新
卡尔,谢谢你的回答。您的脚本有效,但有一个小问题:
类别/相关帖子显示在 2 列中,但“间隙/空格”出现在数据显示的中间(见下图):
我稍微添加到您的代码中,以便显示我插入到每个帖子中的自定义字段。我不确定这是否导致了问题。
更改的代码(更改紧跟在 $query->the_post(); 之后):
<?php
/*
* Template Name: Alphabetical List
*/
get_header();
?>
<div style="height:100px"></div>
<?php
// Grab all the categories from the database that have posts.
$categories = get_terms( 'category', 'orderby=name&order=ASC');
// Loop through categories
echo "<div class='new-column'>";
$counter = 0;
foreach ( $categories as $category ) {
if($counter % 4 == 0 && $counter !=0){
echo "<div class='new-column'>";
}
// Display category name
echo '<h2 class="post-title">' . $category->name . '</h2>';
echo '<div class="post-list">';
// WP_Query arguments
$args = array(
'cat' => $category->term_id,
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$customfieldvalue = get_post_meta($post->ID, "PDF", true);
?>
<p><a href="<?php echo $customfieldvalue; ?>" target="_blank"><?php
the_title(); ?></a></p>
<?php
} // End while
} // End if
echo '</div>';
// Restore original Post Data
wp_reset_postdata();
$counter++;
if($counter % 4 == 0){
echo "</div>";
}
} // End foreach
if($counter % 4 != 0){
echo "</div>";
}
get_footer();
?>
【问题讨论】: