显示 Woocommerce 上每个产品的发布时间 [英] Display the published time ago of every product on Woocommerce

查看:50
本文介绍了显示 Woocommerce 上每个产品的发布时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面提到的以下代码,但它在 Woocommerce 单个产品页面上显示日期:

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);
    }
}

相反,我想显示产品在所有 Woocommerce 商店和档案页面上发布的时间.

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

感谢任何帮助.

推荐答案

以下将显示 Woocommerce 产品的发布时间(以天、小时和分钟为单位):

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 );
}

代码位于活动子主题(或活动主题)的 function.php 文件中.经测试有效.

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

这篇关于显示 Woocommerce 上每个产品的发布时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆