在 WooCommerce 循环产品标题后显示来自产品类别的自定义字段

时间:2021-07-14 15:51:59

标签: php wordpress woocommerce categories custom-fields

我使用以下代码在类别创建/编辑页面中创建了一个自定义字段:

// 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);

我使用这个主题来实现这一目标: 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>';
}

如何安排它显示单数名称(我的新字段)而不是默认名称?

谢谢!

1 个答案:

答案 0 :(得分:1)

要在产品循环中显示您的新字段而不是默认类别名称,您可以使用:

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