php WP - 按类别获取帖子?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11909304/
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
WP -- Get posts by category?
提问by jordan
I'm using this in my page template to get posts by their category:
我在我的页面模板中使用它来按类别获取帖子:
<?php
if (is_page(19)){
?>
<ul>
<?php
global $post;
$args = array( 'category' => 'Testimonial' );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<li class="testimonial"><?php the_content(); ?></li><br/>
<?php endforeach; ?>
</ul>
<?php } ?>
but it's retrieving all posts instead. Not just the ones labeled Testimonial. Any idea what I'm doing wrong?
但它正在检索所有帖子。不仅仅是那些标记为推荐的。知道我做错了什么吗?
采纳答案by Eray
Check here : http://codex.wordpress.org/Template_Tags/get_posts
在这里查看:http: //codex.wordpress.org/Template_Tags/get_posts
Note: The category parameter needs to be the ID of the category, and not the category name.
注意: category 参数需要是类别的 ID,而不是类别名称。
回答by tim
'category_name'=>'this cat' also works but isn't printed in the WP docs
'category_name'=>'this cat' 也可以使用,但未打印在 WP 文档中
回答by KregHEk
You can use 'category_name' in parameters. http://codex.wordpress.org/Template_Tags/get_posts
您可以在参数中使用“category_name”。 http://codex.wordpress.org/Template_Tags/get_posts
Note: The category_name parameter needs to be a string, in this case, the category name.
注意:category_name 参数需要是一个字符串,在本例中是类别名称。
回答by Christian Kengen
add_shortcode( 'seriesposts', 'series_posts' );
function series_posts( $atts )
{ ob_start();
$myseriesoption = get_option( '_myseries', null );
$type = $myseriesoption;
$args=array( 'post_type' => $type, 'post_status' => 'publish', 'posts_per_page' => 5, 'caller_get_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul>';
while ($my_query->have_posts()) : $my_query->the_post();
echo '<li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>';
endwhile;
echo '</ul>';
}
wp_reset_query();
return ob_get_clean(); }
//this will generate a shortcode function to be used on your site [seriesposts]
//这将生成一个在您的网站上使用的短代码函数 [seriesposts]
回答by Raunaque Zamir
Create a taxonomy field category (field name = post_category) and import it in your template as shown below:
创建一个分类字段类别(字段名称 = post_category)并将其导入到您的模板中,如下所示:
<?php
$categ = get_field('post_category');
$args = array( 'posts_per_page' => 6,
'category_name' => $categ->slug );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
//your code here
<?php endforeach;
wp_reset_postdata();?>

