使用WP_QUERY从自定义分类中获取至少包含一个术语的帖子列表

时间:2015-08-02 作者:Nicola Peluchetti

有可能吗WP_Query, 要获取至少有一个类别或自定义分类术语集的所有帖子?

2 个回复
最合适的回答,由SO网友:Pieter Goosen 整理而成

是的,完全有可能。

场景1如果只需要一个分类法,则只需获取分配给该分类法的所有术语的所有术语ID,然后将该术语ID数组传递给tax_query

需要PHP5.4+)

$term_ids = get_terms( 
    \'TAXONOMY_NAME\', 
    [ // Array of arguments, see get_terms()
        \'fields\' => \'ids\' // Get only term ids to make query lean
    ]
);
if (    $term_ids // Check if we have terms
     && !is_wp_error( $term_ids ) // Check for no WP_Error object
) {
    $args = [
        \'tax_query\' => [
            [
                \'taxonomy\' => \'TAXONOMY_NAME\',
                \'terms\'    => $term_ids,
            ]
        ],
    ];
    $q = new WP_Query( $args );

    // Run your loop as needed. Remeber wp_reset_postdata() after the query
}
如果您需要将术语分配给多个分类法的帖子,您可以在SCENARIO 1

$taxonomies = [\'TAXONOMY_NAME_1\', \'TAXONOMY_NAME_2\']; // Array of taxonomies, can also use get_taxonomies for all
$tax_array = []; // Set the variable to hold our tax query array values
foreach ( $taxonomies as $key=>$taxonomy ) {

    $term_ids = get_terms( 
        $taxonomy, 
        [ // Array of arguments, see get_terms()
            \'fields\' => \'ids\' // Get only term ids to make query lean
        ]
    );
    if (    $term_ids // Check if we have terms
         && !is_wp_error( $term_ids ) // Check for no WP_Error object
    ) {
        $tax_array[$key] = [
            \'taxonomy\' => $taxonomy,
            \'terms\'    => $term_ids,
        ];
    }
}
$relation = \'OR\'; // Set the tax_query relation, we will use OR
if ( $tax_array ) { // Check if we have a valid array 
    if ( count( $tax_array ) == 1 ) {
        $tax_query[] = $tax_array;
    } else {
        $tax_query = [
            \'relation\' => $relation,
            $tax_array
        ];
    }

    $args = [ // Set query arguments
        \'tax_query\' => $tax_query,
        // Any other query arguments that you might want to add
    ]; 
    $q = new WP_Query( $args );

    // Run your loop as needed. Remeber wp_reset_postdata() after the query
}

SO网友:Ahmed El-Atab

UPDATE:

get_terms() 现在采用如下数组:

$terms = get_terms( array(
    \'taxonomy\' => \'post_tag\',
    \'hide_empty\' => false,
) );

https://developer.wordpress.org/reference/functions/get_terms

结束

相关推荐

List Terms by category

我有一个自定义分类法叫做portfolio-type. 这个terms = post_type 是portfolio 类别为portfolio-type我正在尝试获取与当前帖子相同类别的相关帖子<?php global $post; $terms = get_the_terms( $post_id, \'portfolio-type\' ); $terms = $terms[0]->cat_ID; $myposts = get_posts(array(\'num