将徽章添加到Wooccommerce产品图像中



我正在添加一个"NEW";带有此代码的Woommerce产品徽章

add_action( 'woocommerce_before_shop_loop_item_title', 'new_badge_shop_page', 3 );

function new_badge_shop_page() {
global $product;
$newness_days = 270;
$created = strtotime( $product->get_date_created() );
if ( ( time() - ( 60 * 60 * 24 * $newness_days ) ) < $created ) {
echo '<span class="itsnew">' . esc_html__( 'N E W', 'woocommerce' ) . '</span>';
}
}

我的问题是:我怎么能把它添加到单个产品页面上?当然,我可以使用相同的功能和不同的挂钩,但有办法把它组合起来吗?第二,如果产品属于特定类别,我如何添加徽章?我试着添加

if ( ( time() - ( 60 * 60 * 24 * $newness_days ) ) < $created AND !has_term ('sale') )  {

但它没有起作用。

您可以使用这样的代码在产品块上显示一个新徽章,并使用相同的功能显示单个产品页面:

function new_badge_shop_page() {
global $product;

$newness_days = 270;
$created      = strtotime( $product->get_date_created() );
if ( ( time() - ( 60 * 60 * 24 * $newness_days ) ) < $created ) {
echo '<span class="itsnew">' . esc_html__( 'N E W', 'woocommerce' ) . '</span>';
}
}
add_action( 'woocommerce_before_shop_loop_item_title', 'new_badge_shop_page', 3 );
add_action( 'woocommerce_single_product_summary', 'new_badge_shop_page', 9 );

要检查类别,您可以使用以下代码:

if ( has_term( array( 'sale', 'cat-1', 'cat-2' ), 'product_cat', $product->get_id() ) ) {
return;
}

你的最终代码是这样的:

function new_badge_shop_page() {
global $product;
if ( has_term( array( 'sale', 'cat-1', 'cat-2' ), 'product_cat', $product->get_id() ) ) {
return;
}
$newness_days = 270;
$created      = strtotime( $product->get_date_created() );
if ( ( time() - ( 60 * 60 * 24 * $newness_days ) ) < $created ) {
echo '<span class="itsnew">' . esc_html__( 'N E W', 'woocommerce' ) . '</span>';
}
}
add_action( 'woocommerce_before_shop_loop_item_title', 'new_badge_shop_page', 3 );
add_action( 'woocommerce_single_product_summary', 'new_badge_shop_page', 9 );

最新更新