1
votes

The following code mentioned below but it displays a date on Woocommerce single product pages:

add_action('woocommerce_single_product_summary','displaying_product_date', 25);

function displaying_product_date() {

    if ( is_product() ) {
        echo the_date('', '<span class="date_published">Published on: ', '</span>', false);
    }
}

I would like instead to show how many time ago a product was published on all Woocommerce shop and archives pages.

Any help is appreciated.

1

1 Answers

0
votes

The following will display the published time in days, hours and minutes on Woocommerce products:

// Custom function to get the published time of a product
function get_product_published_time( $product ) {
    $datetime = $product->get_date_created();
    $timezone = $datetime->getTimezone();
    $now_time = new WC_DateTime();

    $now_time->setTimezone($timezone);

    $timestamp_diff = $now_time->getTimestamp() - $datetime->getTimestamp();

    $data = timestamp_to_array( $timestamp_diff );

    return sprintf( '<div class="published-time"><small>' . __('Published %s and %s ago', 'woocommerce') . '</small></div>',
        $data['d'] . ' ' . _n( 'day', 'days', $data['d'], 'woocommerce' ) ,
        $data['h'] . ' ' . _n( 'hour', 'hours', $data['h'], 'woocommerce' )
    );
}

function timestamp_to_array( $timestamp ) {
    $d = floor($timestamp/86400);
    $_d = ($d < 10 ? '0' : '').$d;

    $h = floor(($timestamp-$d*86400)/3600);
    $_h = ($h < 10 ? '0' : '').$h;

    $m = floor(($timestamp-($d*86400+$h*3600))/60);
    $_m = ($m < 10 ? '0' : '').$m;

    $s = $timestamp-($d*86400+$h*3600+$m*60);
    $_s = ($s < 10 ? '0' : '').$s;

    return array('d' => $_d, 'h' => $_h, 'm' => $_m, 's' => $_s);
}

// On woocommerce loop (shop, archives…)
add_action('woocommerce_after_shop_loop_item','dislay_product_loop_published_time', 20 );
function dislay_product_loop_published_time() {
    global $product;

    echo get_product_published_time( $product );
}

// On single product pages
add_action( 'woocommerce_single_product_summary', 'dislay_single_product_published_time', 25 );
function dislay_single_product_published_time() {
    global $product;

    echo get_product_published_time( $product );
}

Code goes on function.php file of your active child theme (or active theme). Tested and works.