简体   繁体   English

如何在WordPress中通过自定义分类获取帖子?

[英]How to get posts by custom taxonomy in WordPress?

In WordPress, I am trying to get posts from a custom post type 'color', custom taxonomy 'color-name', using the following: 在WordPress中,我尝试使用以下方式从自定义帖子类型“颜色”,自定义分类法“颜色名称”获取帖子:

Notes: I have a custom post type, Color, with custom posts that are titled things like, 'Coral', 'Peony'. 注意:我有一个自定义帖子类型,颜色,带有自定义帖子,标题为“珊瑚”,“牡丹”之类的东西。 I also have a custom taxonomy, color-name. 我也有一个自定义分类法,颜色名称。 Through a hook on saving a color post, categories in that custom taxonomy get created. 通过保存颜色帖,可以创建该自定义分类法中的类别。 Then, the custom post type Color, can be tagged with other related colors. 然后,可以将自定义帖子类型“颜色”标记为其他相关颜色。

$slug = str_replace(" ", "_", $page_title);
$slug = strtolower($slug);

//Slug is - 'coral', 'peony', etc.

$args = array( 'post_type' => 'color',
               'posts_per_page' => -1,
               'tax_query' => array( array (
                       'taxonomy' => 'color-name',
                       'field' => 'slug',
                       'terms' => $slug
                                   ) )
);
$myposts = query_posts( $args );

I've tried many variations of this after Googling, and nothing is working - I either get all posts, or no posts. 在Google搜寻后,我尝试了许多变体,但没有任何效果-我要么收到所有帖子,要么没有帖子。 Here's another version of args I've tried: (results in no posts): 这是我尝试过的args的另一个版本:(无帖子结果):

  $args = array('color-name' => $page_title,
                'post_type' => 'color',
                'post_status' => 'publish',
                'posts_per_page' => -1,
                'caller_get_posts'=> 1
               );

I've wrestled with this before and gave up and just made a custom sql call. 我之前为此作过角力,放弃了,只是进行了自定义sql调用。 Does anyone know definitively how to get this working through WordPress functions? 谁能确切地知道如何通过WordPress函数使它正常工作?

I would use WP_Query instead of query_posts() . 我将使用WP_Query而不是query_posts() For example: 例如:

$args = array(
    'post_type' => 'color',
    'tax_query' => array(
        array(
            'taxonomy' => 'color-name',
            'field' => 'slug',
            'terms' => $slug
        )
    )
);
$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // Do something.
    }
} else {
    // No posts found.
}
wp_reset_postdata();

Ref: http://codex.wordpress.org/Class_Reference/WP_Query 参考: http : //codex.wordpress.org/Class_Reference/WP_Query

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM