Woocommerce product countdown on archive/cycle page
<p>I made a countdown using the meta key <code>_sale_price_to</code> to show the end of sale date.请参阅下面的代码:</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>The code works on the product single page, but I need it on the archive and loop pages. On the archive page, all products have the same countdown value. I guess this is because I can't provide properties for each archive item. </p>
<p>Related posts that may be helpful:</p>
<ul>
<li>Link 1</li>
<li>Link 2</li>
</ul></p>