问题描述
我已经为“产品”帖子类型注册了两个分类法。称他们为pa_brand
& pa_model
我创建了一个前端表单来编辑通过 $product_id
从 URL 参数获取产品数据的产品。
我需要的是通过 pa_brand
获得 pa_model
和 $product_id
的相关术语。
以下操作仅适用于单个产品页面,以便我可以获得与产品相关的正确术语。
$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
的 WP_Error。
$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 从自定义分类法中获取相关术语?
解决方法
我发现了这个问题。我必须将 0
添加到自定义自定义分类法的 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',array(
'label' => __( 'Model' ),'rewrite' => array( 'slug' => 'car_model' ),)
);
}