Reputation: 119
I created a custom field in the category creation/edition page using this code:
// 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', 10, 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, 'product_cat_singular', $productCatSingular);
}
add_action('edited_product_cat', 'wh_save_taxonomy_custom_meta', 10, 1);
add_action('create_product_cat', 'wh_save_taxonomy_custom_meta', 10, 1);
I used this topic to achieve this: Adding custom field to product category
I am using this code to display the default category name in product loop:
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>';
}
How can I arrange it to show the singular name (my new field) rather than the default name?
Thanks!
Upvotes: 2
Views: 845
Reputation: 29650
To display your new field rather than the default category name in the product loop, you can use:
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 );
Note: Since WooCommerce 3 use $product->get_id()
instead of $product->id
Upvotes: 1