问题描述
// Product Cat Create Page
function product_cat_new_field_create_page() {
?>
<div class="form-field">
<label for="product_cat_singular"><?PHP _e('Singular Name','wh'); ?></label>
<input type="text" name="product_cat_singular" id="product_cat_singular">
</div>
<?PHP
}
// Product Cat Edit Page
function product_cat_new_field_edit_page($term) {
// Getting term ID
$term_id = $term->term_id;
// Retrieve the existing value(s) for this Meta field.
$productCatSingular = get_term_Meta($term_id,'product_cat_singular',true);
?>
<tr class="form-field">
<th scope="row" valign="top"><label for="product_cat_singular"><?PHP _e('Singular Title','wh'); ?></label></th>
<td>
<input type="text" name="product_cat_singular" id="product_cat_singular" value="<?PHP echo esc_attr($productCatSingular) ? esc_attr($productCatSingular) : ''; ?>">
</td>
</tr>
<?PHP
}
add_action('product_cat_add_form_fields','product_cat_new_field_create_page',10,1);
add_action('product_cat_edit_form_fields','product_cat_new_field_edit_page',1);
// Save extra taxonomy fields callback function.
function wh_save_taxonomy_custom_Meta($term_id) {
$productCatSingular = filter_input(INPUT_POST,'product_cat_singular');
update_term_Meta($term_id,$productCatSingular);
}
add_action('edited_product_cat','wh_save_taxonomy_custom_Meta',1);
add_action('create_product_cat',1);
我使用这个主题来实现这一目标: Adding custom field to product category
add_action( 'woocommerce_shop_loop_item_title','add_product_cat',15);
function add_product_cat() {
global $product;
$product_cats = wp_get_post_terms($product->id,'product_cat');
$count = count($product_cats);
echo '<div class="categories">';
foreach($product_cats as $key => $cat) {
echo '<span class="category">' . $cat->name . '</span>';
}
echo '</div>';
}
谢谢!
解决方法
要在产品循环中显示您的新字段而不是默认类别名称,您可以使用:
function action_woocommerce_shop_loop_item_title() {
global $product;
// Is a WC product
if ( is_a( $product,'WC_Product' ) ) {
// Retrieves product term ids for a taxonomy
$product_cats_ids = wc_get_product_term_ids( $product->get_id(),'product_cat' );
echo '<div class="categories">';
// Iterate over
foreach( $product_cats_ids as $product_cats_id ) {
echo '<span class="category">' . get_term_meta( $product_cats_id,'product_cat_singular',true ) . '</span>';
}
echo '</div>';
}
}
add_action( 'woocommerce_shop_loop_item_title','action_woocommerce_shop_loop_item_title',15 );
注意:由于 WooCommerce 3 使用 $product->get_id()
而不是 $product->id