如何通过 WordPress 中的自定义分类法获取帖子? [英] How to get posts by custom taxonomy in WordPress?

查看:48
本文介绍了如何通过 WordPress 中的自定义分类法获取帖子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 WordPress 中,我尝试使用以下内容从自定义帖子类型颜色"、自定义分类颜色名称"中获取帖子:

In WordPress, I am trying to get posts from a custom post type 'color', custom taxonomy 'color-name', using the following:

注意:我有一个自定义帖子类型,颜色,带有标题为珊瑚"、牡丹"之类的自定义帖子.我还有一个自定义分类法,颜色名称.通过保存彩色帖子的挂钩,可以创建该自定义分类法中的类别.然后,自定义帖子类型颜色,可以使用其他相关颜色进行标记.

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 );

我在谷歌搜索后尝试了很多变体,但没有任何效果 - 我要么得到所有帖子,要么没有帖子.这是我尝试过的另一种 args 版本:(结果没有帖子):

I've tried many variations of this after Googling, and nothing is working - I either get all posts, or no posts. Here's another version of args I've tried: (results in no posts):

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

我之前曾为此苦恼过,后来放弃了,只是进行了自定义 sql 调用.有谁确切地知道如何通过 WordPress 功能实现这一点?

I've wrestled with this before and gave up and just made a custom sql call. Does anyone know definitively how to get this working through WordPress functions?

推荐答案

我会使用 WP_Query 而不是 query_posts().例如:

I would use WP_Query instead of 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();

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

这篇关于如何通过 WordPress 中的自定义分类法获取帖子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆