$args = array(
'type' => 'post',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'category',
'pad_counts' => false
);
$categories = get_categories($args);
// print_r($categories);
foreach ($categories as $cat) { ?>
<section id="<?php echo $cat->slug ?>-section"><?php
$args2 = array(
'post_type' => 'post',
'category_name' => $cat->slug
);
$query = new WP_Query( $args2 );
if($query->have_posts()) :
while($query->have_posts()) : $query->the_post();?>
<h2 class="<?php echo $cat->slug ?>-heading">
<a href="<?php echo get_permalink() ?>"><?php echo get_the_title() ?></a>
</h2>
<div class="post-date">
<?php the_time('d. m. Y') ?>
</div>
<div class="post-content">
<?php the_content(); ?>
</div><?php
endwhile;
endif;
wp_reset_postdata(); ?>
</section> <?php
}
获取section
标记内每个类别的所有帖子,帖子类别为id
。
然而,如果不使用new Wp_Query
,这也会得到相同的结果。
$args = array(
'type' => 'post',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'category',
'pad_counts' => false
);
$categories = get_categories($args);
// print_r($categories);
foreach ($categories as $cat) { ?>
<section id="<?php echo $cat->slug ?>-section">
<?php
// Get posts from each category
$args2= array("orderby"=>'name', "category" => $cat->cat_ID);
$posts_in_category = get_posts($args2);
foreach( $posts_in_category as $current_post ) { ?>
<h2 class="<?php echo $cat->slug ?>-heading">
<a href="<?php echo $current_post->guid; ?>"><?php echo $current_post->post_title; ?></a>
</h2>
<div class="post-date">
<?php the_time('d. m. Y') ?>
<?php echo $current_post->post_date; ?>
<!-- <?php // echo $current_post->the_time('d. m. Y') ?> -->
</div>
<div class="post-content">
<?php the_content(); ?>
<?php echo $current_post->post_content; ?>
</div> <?php
}
?>
</section> <?php
}
在第二种方法中,我无法使用echo $current_post->the_time('d. m. Y')
设置日期,但必须格式post_date
kind of tricky。
不熟悉不使用new WP_Query
但使用$args2= array("orderby"=>'name', "category" => $cat->cat_ID);
而使用get_posts
并不适合我。
两种方法都会在数据库中查询每个类别,一个使用new WP_Query
,另一个使用get_posts
。
查询数据库的最佳做法和执行方式是什么,以便每个类别中的所有帖子都显示在section
标记内,其类别为id
?