wordpress 如何使用 slug 从类别中获取帖子?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13202245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get posts from category using the slug?
提问by Nips
I have my own theme and I'd like to display posts on my home page from a specific category.
我有自己的主题,我想在我的主页上显示来自特定类别的帖子。
So far I've achieved it like this:
到目前为止,我已经实现了这样的目标:
<?php
global $post;
$args = array( 'numberposts' => 10, 'category' => 6 );
$posts = get_posts( $args );
foreach( $posts as $post ): setup_postdata($post);
?>
<divs with the_title() the_excerpt() etc ></div>
<?php
endforeach;
?>
But what if I want to get the category by a its slug? Or is it possible to simply make a category selection box in from within the admin panel?
但是如果我想通过它的 slug 来获取类别呢?或者是否可以简单地从管理面板中创建一个类别选择框?
回答by loQ
Replace your category
parameter with category_name
将您的category
参数替换为category_name
<?php
global $post;
$args = array( 'numberposts' => 10, 'category_name' => 'cat-slug' );
$posts = get_posts( $args );
foreach( $posts as $post ): setup_postdata($post);
?>
<divs with the_title() the_excerpt() etc ></div>
<?php endforeach; ?>
For more info: http://codex.wordpress.org/Class_Reference/WP_Query#Parameters
更多信息:http: //codex.wordpress.org/Class_Reference/WP_Query#Parameters
回答by Raunaque Zamir
suppose you have category name 'ice cakes' and category slug as 'ice-cakes', then our code to retrieve post under category 'ice cakes' is as follows:
假设您的类别名称为“ice cakes”,类别 slug 为“ice-cakes”,那么我们在“ice cakes”类别下检索帖子的代码如下:
<?php
$args = array( 'posts_per_page' => 3,
'category_name' => 'ice-cakes' );
$icecakes = get_posts( $args );
foreach ( $icecakes as $post ) : setup_postdata( $post ); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endforeach;
wp_reset_postdata(); ?>
回答by Amit Kumar
You can simply pass slug in the get_posts
method of WordPress
suppose your category slug is ice-cake
您可以简单地在get_posts
WordPress的方法中传递 slug假设您的类别 slug 是ice-cake
$args = array('numberposts' => 10, 'category' => 'ice-cake');
$posts = get_posts($args);
For more info : https://developer.wordpress.org/reference/functions/get_posts/
欲了解更多信息:https: //developer.wordpress.org/reference/functions/get_posts/