获取特定属性分类术语slug

时间:2017-11-08 02:18:45

标签: php wordpress woocommerce taxonomy product

我正试图从特定的属性分类中获取术语slug,但我什么都没得到。

$attr_langs = 'pa_languages';
$attr_langs_meta = get_post_meta('id', 'attribute_'.$attr_langs, true);
$term = get_term_by('slug', $attr_langs_meta, $attr_langs);

提前非常感谢你!

1 个答案:

答案 0 :(得分:0)

它是不正常的,因为get_post_meta()第一个函数参数需要是数值,但是 文字字符串'id'(帖子ID)...
因此,您无法获得$attr_langs_meta变量的任何值。

  

您可以通过不同方式获取产品ID:

     

1)来自WP_Post对象:

global $post; 
$product_id = $post->ID; 
     

2)来自WC_Product对象:

$product_id = $product->get_id(); 

现在正确的方法是:

// The defined product attribute taxonomy
$taxonomy = 'pa_languages';

// Get an instance of the WC_Product Object (necessary if you don't have it)  
// from a dynamic $product_id (or defined $product_id)
$product = wc_get_product($product_id);

// Iterating through the product attributes
foreach($product->get_attributes( ) as $attribute){
    // Targeting the defined attribute
    if( $attribute->get_name() == $taxonomy){
        // Iterating through term IDs for this attribute (set for this product)
        foreach($attribute->get_options() as $term_id){
            // Get the term slug
            $term_slug = get_term( $term_id, $taxonomy )->slug;

            // Testing an output
            echo 'Term Slug: '. $term_slug .'<br>';
        }
    }
}

或者也专门针对可变产品(类似的东西):

// The defined product attribute taxonomy
$taxonomy = 'pa_languages';

// Get an instance of the WC_Product Object (necessary if you don't have it)  
// from a dynamic $product_id (or defined $product_id)
$product = wc_get_product($product_id);

// Iterating through the variable product variations attributes
foreach ( $product->get_variation_attributes() as $attribute => $terms ) {
    // Targeting the defined attribute
    if( $attribute == $taxonomy ){
        // Iterating through term slugs for this attribute (set for this product)
        foreach( $terms as $term_slug ){
            // Testing an output
            echo 'Term Slug: ' . $term_slug . '<br>';
        }
    }
}

这对你有用......