wordpress 获取某分类下的文章列表

Auth:admin Date:2022-06-16 19:13:05 Cat:技术笔记


可以直接使用 WP_Query 函数进行查询,代码如下:

<?php
$query = new WP_Query([
    'post_type' => 'product',
    'posts_per_page' => 999,
    'order' => 'ASC',
    'tax_query' => [
        [
            'taxonomy' => 'product_category',
            'field' => 'term_id',
            'terms' => $sub->term_id,
        ]
    ],
]);

if ($query->have_posts()) :
    while ($query->have_posts()) :
        $query->the_post();
?>

        <a href="<?php the_permalink() ?>"><?php the_title() ?></a>

<?php
    endwhile;
endif;
wp_reset_query();
?>

除了使用 WP_Query 方法外,还可以使用 query_posts 函数,如下:

<?php
$paged = 1;
if (get_query_var('page')) {
    $paged = get_query_var('page');
}
query_posts(array(
    'post_type'      => 'case',  // post type
    'paged'          => $paged,  // 当前是第几页
    'posts_per_page' => 9        // 每页几条
));
while (have_posts()) :
    the_post();
?>
    <a href="<?php the_permalink() ?>"> <?php the_title() ?> </a>
<?php endwhile; ?>

查询wordpress自带的默认文章类型(post):

<?php
query_posts(array(
    'category_name' => 'news', // 分类slug
    'posts_per_page' => 6, // 查询几条
));
while (have_posts()) :
    the_post();
?>
    <a href="<?php the_permalink() ?>"> <?php the_title() ?> </a>
<?php endwhile; ?>

该查询默认是按发布时间倒序排序

标签: