存档/循环页面上的 Woocommerce 产品倒计时
P粉237647645
2023-08-31 21:06:59
<p>我使用元键 <code>_sale_price_to</code> 进行了倒计时以显示销售日期结束。请参阅下面的代码:</p>
<pre class="brush:php;toolbar:false;">add_shortcode( 'woocommerce_timer_two', 'sales_timer_countdown_product_two', 20 );
function sales_timer_countdown_product_two($atts) {
extract( shortcode_atts( array(
'id' => get_the_ID(),
), $atts, 'woocommerce_timer_two' ) );
global $product;
// If the product object is not defined, we get it from the product ID
if ( ! is_a($product, 'WC_Product') && get_post_type($id) === 'product' ) {
$product = wc_get_product($id);
}
if ( is_a($product, 'WC_Product') ) {
$sale_date = get_post_meta( $product->get_id(), '_sale_price_dates_to', true );
if ( ! empty( $sale_date ) ) {
?>
<script>
jQuery(function($){
"use strict";
$('.countdown-counter').each( function() {
var to = $(this).attr("countdown");
var thisis = $(this);
var parent = $(this).parent();
var countDownDate = <?php echo $sale_date; ?> * 1000;
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="sale-end"
var html = days + hours + " : " + minutes + " : " + seconds;
thisis.html(html);
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
parent.css("display", "none");
}
}, 1000);
thisis.removeAttr("countdown");
});
});
</script>
<!-- this is where the countdown is displayed -->
<div class="product-countdown">
<span class="countdown-counter" countdown="'. $html .'"></span>
</div>;
<?php
}
}
}</pre>
<p>该代码适用于产品单页面,但我需要它在存档和循环页面上。在存档页面上,所有产品都具有相同的倒计时值。我想这是因为我无法为每个存档项目提供属性。</p>
<p>可能有帮助的相关帖子:</p>
<ul>
<li>Link 1</li>
<li>Link 2</li>
</ul></p>
如果此代码在产品单页面上运行,那么您可以使用 WooCommerce 挂钩在存档/循环页面中添加操作挂钩。
示例:-
已编辑
您可以使用添加的产品 ID 来替换该类。
同时替换 html 部分。