[英]Replace product title by the SKU in WooCommerce shop, cart and checkout pages
Using Woocommerce, I would like to add the SKU instead of the product title in the following pages: Shop page, Cart page and Checkout page.使用 Woocommerce,我想在以下页面中添加 SKU 而不是产品标题:商店页面、购物车页面和结帐页面。
For example in shop page, I am able to add the SKU above the product title using the code below.例如,在商店页面中,我可以使用以下代码在产品标题上方添加 SKU。 However, the problem is that the SKU added doesn't have the link to the single product page.
但是,问题是添加的 SKU 没有指向单个产品页面的链接。
add_action( 'woocommerce_shop_loop_item_title', 'sku_before_title', 9 );
function sku_before_title() {
global $product;
$sku = $product->get_sku();
echo '<p class="name product-title">Product ' . $sku . '</p>';
}
What is the correct code to have SKU instead of product title and keeping the same link and CSS as the product title?使用 SKU 而不是产品标题并保持与产品标题相同的链接和 CSS 的正确代码是什么? Code for Shop page and Cart page and Checkout page.
商店页面和购物车页面和结帐页面的代码。
To replace the product title by the sku on WooCommerce archive pages you will use:要在 WooCommerce 存档页面上用 sku 替换产品标题,您将使用:
// Frontend: On shop and archives pages
add_action( 'woocommerce_shop_loop_item_title', 'sku_replace_title_on_loop', 9 );
function sku_replace_title_on_loop() {
global $product;
// Remove the product title
remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );
$sku = $product->get_sku();
// Replace the title by the Sku if is not empty
$title = empty($sku) ? get_the_title() : $sku;
// Output
echo '<h2 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '">' . $title . '</h2>';
}
For cart and checkout pages, you will use:对于购物车和结帐页面,您将使用:
// Frontend: on cart, minicart and checkout
add_filter( 'woocommerce_cart_item_name', 'sku_replace_title_on_cart_checkout', 10, 3 );
function sku_replace_title_on_cart_checkout( $item_name, $cart_item, $cart_item_key ) {
if( $sku = $cart_item['data']->get_sku() ) {
if( is_cart() ) {
$item_name = sprintf( '<a href="%s">%s</a>', esc_url( $cart_item['data']->get_permalink( $cart_item ) ), $sku );
} else {
$item_name = $sku;
}
}
return $item_name;
}
Code goes in function.php file of your active child theme (or active theme).代码位于活动子主题(或活动主题)的 function.php 文件中。 Tested and works.
测试和工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.