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

可以直接使用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; ?>

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

本文为“技术点滴”的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注