wordpress调用分类文章列表
时间 : 2024-01-08 22:35:02 声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性

最佳答案

在WordPress中调用分类文章列表非常简单。只需要使用WordPress提供的`WP_Query`类来查询指定分类的文章,然后通过循环来输出文章列表即可。

以下是一个简单的例子,展示如何在WordPress中调用分类文章列表:

```php

<?php

// 获取当前分类的ID

$category_id = get_queried_object_id();

// 创建一个新的WP_Query对象,查询当前分类的文章

$query = new WP_Query(array(

'cat' => $category_id,

'posts_per_page' => 10, // 每页显示的文章数量

));

// 如果有文章

if ($query->have_posts()) {

while ($query->have_posts()) {

$query->the_post();

?>

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

<p><?php the_excerpt(); ?>

<?php

}

wp_reset_postdata(); // 重置查询

} else {

echo '没有相关文章。';

}

这段代码首先使用`get_queried_object_id()`函数获取当前分类的ID,然后使用`WP_Query`类创建一个新的查询对象来获取该分类下的文章。在循环中,使用`the_post()`函数获取每篇文章,并使用`the_title()`和`the_excerpt()`函数来输出文章的标题和摘要。最后,使用`wp_reset_postdata()`函数来重置查询。

将以上代码放置在你想要显示分类文章列表的地方,就可以在页面上展示该分类下的文章列表了。记得根据自己的需要进行修改,比如调整每页显示的文章数量、输出的格式等。

希望对你有帮助!

其他答案

在WordPress中调用分类文章列表是非常简单的。你可以通过使用WP_Query或者使用专用的函数来实现。

使用WP_Query:

$args = array(

'post_type' => 'post',

'tax_query' => array(

array(

'taxonomy' => 'category',

'field' => 'slug',

'terms' => 'your-category-slug',

),

),

);

$query = new WP_Query($args);

if ($query->have_posts()) {

while ($query->have_posts()) {

$query->the_post();

// 在此处显示文章内容

the_title();

the_content();

}

}

wp_reset_postdata();

请记得将 "your-category-slug" 替换为你想要调用的分类的实际别名。

使用专用函数:

另一种方法是使用专用函数来调用分类文章列表。以下是一个示例:

$args = array(

'category_name' => 'your-category-slug',

'posts_per_page' => -1,

);

$posts = get_posts($args);

foreach ($posts as $post) {

setup_postdata($post);

// 在此处显示文章内容

the_title();

the_content();

}

wp_reset_postdata();

同样,请将 "your-category-slug" 替换为你想要调用的分类的实际别名。

无论你选择使用哪种方法,都可以将这段代码放置在WordPress模板文件(例如category.php)中,以在分类页面上显示特定分类的文章列表。