按产品ID获取产品自定义分类术语



我已经为"product"post-type注册了两个分类法。称之为CCD_ 1&pa_model

我创建了一个前端表单来编辑产品,通过$product_id从URL参数中获取产品数据。

我需要的是得到pa_brand&CCD_ 5和CCD_。

以下仅适用于单个产品页面,这样我就可以获得与产品相关的正确术语。

$models = get_the_terms( $product->get_ID(), 'pa_model' );
echo '<pre>'; print_r( $models ); echo '</pre>';
$brands = get_the_terms( $product->get_ID(), 'pa_brand' );
echo '<pre>'; print_r( $brands ); echo '</pre>';
$cats = get_the_terms( $product->get_ID(), 'product_cat' );
echo '<pre>'; print_r( $cats ); echo '</pre>';
___________________________
RESULTS:
Array
(
[0] => WP_Term Object
(
[term_id] => 28
[name] => FKS
[slug] => fks
[term_group] => 0
[term_taxonomy_id] => 28
[taxonomy] => pa_model
[description] => 
[parent] => 0
[count] => 3
[filter] => raw
)
)
Array
(
[0] => WP_Term Object
(
[term_id] => 36
[name] => MAN
[slug] => man
[term_group] => 0
[term_taxonomy_id] => 36
[taxonomy] => pa_brand
[description] => 
[parent] => 0
[count] => 3
[filter] => raw
)
)
Array
(
[0] => WP_Term Object
(
[term_id] => 39
[name] => Truck
[slug] => truck
[term_group] => 0
[term_taxonomy_id] => 39
[taxonomy] => product_cat
[description] => 
[parent] => 0
[count] => 2
[filter] => raw
)
)

但是,如果页面是而不是单个产品,即http://example.com/?manage_product=206,则我会得到以下两个pa_brand&pa_model

$models = get_the_terms( $product_id, 'pa_model' );
echo '<pre>'; print_r( $models ); echo '</pre>';
$brands = get_the_terms( $product_id, 'pa_brand' );
echo '<pre>'; print_r( $brands ); echo '</pre>';
$cats = get_the_terms( $product_id, 'product_cat' );
echo '<pre>'; print_r( $cats ); echo '</pre>';
___________________________
RESULTS:
WP_Error Object
(
[errors] => Array
(
[invalid_taxonomy] => Array
(
[0] => Invalid taxonomy.
)
)
[error_data] => Array
(
)
[additional_data:protected] => Array
(
)
)
WP_Error Object
(
[errors] => Array
(
[invalid_taxonomy] => Array
(
[0] => Invalid taxonomy.
)
)
[error_data] => Array
(
)
[additional_data:protected] => Array
(
)
)
Array
(
[0] => WP_Term Object
(
[term_id] => 39
[name] => Truck
[slug] => truck
[term_group] => 0
[term_taxonomy_id] => 39
[taxonomy] => product_cat
[description] => 
[parent] => 0
[count] => 2
[filter] => raw
)
)

短路代码

function frontend_add_product_form($product_id){
global $product_id;
$product = new WC_Product( $product_id );
$koostis = get_the_terms( $product_id, 'pa_brand', array( 'fields' => 'names' ) );
echo 'koostis<br><pre>'; print_r( $koostis ); echo '</pre>';
}
add_shortcode('frontend-add-product-form', 'frontend_add_product_form');

我已经被困了好几个小时,不知道如何通过产品ID从自定义分类法中获得相关术语?

我发现了这个问题。我不得不将pa_brand0添加到自定义Taxonomy的init操作中。

add_action( 'init', 'register_product_taxonomy', 0 );
function register_product_taxonomy() {
register_taxonomy(
'pa_brand',
'product',
array(
'label' => __( 'Brand' ),
'rewrite' => array( 'slug' => 'car_brand' ),
'hierarchical' => true,
)
);  
register_taxonomy(
'pa_model',
'product',
array(
'label' => __( 'Model' ),
'rewrite' => array( 'slug' => 'car_model' ),
'hierarchical' => true,
)
);
}

最新更新