Wordpress 获取分类法 WordPress 的术语

问题描述 投票:0回答:1

我有两个分类法,我需要根据另一个分类法建立一个分类法的术语列表。

分类 1 - Auto_Brand

分类 2 - 城市

我知道我可以使用

$terms = get_terms("auto_brands"); or $terms = get_terms("city");,
,但是我如何构建代码来仅获取附有 auto_brand 的城市?

php wordpress taxonomy
1个回答
0
投票

分类法不与其他分类法直接交互。它们仅与 Post 对象交互并封装。我能想到的唯一方法是使用 WP_Query 运行分类查询来收集使用这两种分类法的所有帖子,然后循环遍历每个帖子以构建一组独特的术语:

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        'relation' => 'AND',
        array('taxonomy' => 'auto_brand'),
        array('taxonomy' => 'city')
    )
);
$q = new WP_Query($args); //Get the posts

$found_terms = array(); //Initialize Empty Array
$taxonomies = array('auto_brand', 'city'); //Taxonomies we're checking
$args = array('fields'=>'names'); //Get only the names
foreach($q->posts as $t_post) //Begin looping through all found posts
{
    $post_terms = wp_get_post_terms($t_post->ID, $taxonomies, $args);
    $found_terms = array_merge($found_terms, $post_terms); //Build Terms array
}
$unique_terms = array_unique($found_terms); //Filter duplicates

这尚未经过测试,但它应该可以帮助您朝着正确的方向开始。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.