按自定义术语元和分类获取术语

时间:2016-07-01 作者:Sevi

如何通过自定义术语元和分类法获取术语或如何筛选tax_query 改为按术语metaslug/id?

function custom_pre_get_posts($query)
{
    global $wp_query;

    if ( !is_admin() && is_shop() && $query->is_main_query()  && is_post_type_archive( "product" )) 
    {
        $term = ???get_term_by_meta_and_taxonomy???(\'custom_meta_term\',\'my_taxonomy\');
        $t_id = $term[\'term_id\'];
        $tax_query = array
        (
            array
            (
                \'taxonomy\' => \'my_taxoomy\',
                \'field\' => \'id\',
                \'terms\' => $t_id
            )
        );
        $query->set( \'tax_query\', $tax_query );
    }
}
add_action( \'pre_get_posts\', \'custom_pre_get_posts\' );

3 个回复
SO网友:Ahmed Ali

Try This:

$args = array(
\'hide_empty\' => false, // also retrieve terms which are not used yet
\'meta_query\' => array(
    array(
       \'key\'       => \'feature-group\',
       \'value\'     => \'kitchen\',
       \'compare\'   => \'LIKE\'
    )
),
\'taxonomy\'  => \'category\',
);
$terms = get_terms( $args );
SO网友:Steven Ryan

基于来自的答案ilgıt-yıldırım 上面,两个get_term_meta 声明和$key == \'meta_value\' 报表需要包含$term>term_id.

下面是一个完整的示例,包括自定义$wp_query 请求:

$term_args = array( \'taxonomy\' => \'your-taxonomy\' );
$terms = get_terms( $term_args );

$term_ids = array();

foreach( $terms as $term ) {
    $key = get_term_meta( $term->term_id, \'term-meta-key\', true );

    if( $key == \'term-meta-value\' ) {
        // push the ID into the array
        $term_ids[] = $term->term_id;
    }
}

// Loop Args
$args = array(
\'post_type\' => \'posts\',
\'tax_query\' => array(
    array(
        \'taxonomy\' => \'your-taxonomy\',
        \'terms\'    => $term_ids,
         ),
    ),
);

// The Query
$featured = new WP_Query( $args );

SO网友:edwardr

您需要遍历主查询条件中的每个术语。假设自定义数据中可能有多个术语,那么您需要将一个ID数组传递到税务查询中。

例如,循环检查每个术语以检查自定义元:

$term_args = array(
    \'taxonomy\' => $taxonomy_name,
    );


$terms = get_terms( $term_args );

$term_ids = array();

foreach( $terms as $term ) {
    $key = get_term_meta( $term->ID, \'meta_key\', true );
    if( $key == \'meta_value\' ) {
        // push the ID into the array
        $term_ids[] = $term->ID;
    }
}
然后,您将得到变量$term\\u id,其中包含您要查找的术语id数组。您可以将其传递到税务查询。