在Woocommerce商店页面上显示每种产品的发布时间

时间:2019-03-22 20:24:32

标签: php wordpress time woocommerce product

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

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的所有商店和档案页面上发布了多少时间。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

以下将在产品按钮之后的Woocommerce产品和归档页面上显示发布时间,以天,小时和分钟为单位((可选为秒)”:

add_action('woocommerce_after_shop_loop_item','dislay_product_published_time', 20 );
function dislay_product_published_time() {
    global $product;

    $product_datetime = $product->get_date_created();
    $product_timestamp = $product_datetime->getTimestamp();

    $timezone = $product_datetime->getTimezone();

    $now_time = new WC_DateTime();

    $now_time->setTimezone($timezone);

    $now_timestamp  = $now_time->getTimestamp();
    $timestamp_diff = $now_timestamp - $product_timestamp;

    $data = timestamp_to_array( $timestamp_diff );

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

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

代码在您的活动子主题(或活动主题)的function.php文件上。经过测试,可以正常工作。