Dau
Dau

Reputation: 27

Display the published date of every product on Woocommerce shop page

I'm looking for solution to display products published date on shop page.

I tried the following code, but it show only for first product

Any help will be greatful

add_action( 'woocommerce_after_shop_loop_item', 'wc_shop_page_product_date', 100 );
function wc_shop_page_product_date() {
    echo the_date('', '<span class="date_published">Published on: ', '</span>', false);
}

Upvotes: 0

Views: 5203

Answers (2)

Sam
Sam

Reputation: 591

add_action( 'woocommerce_after_shop_loop_item', 'wc_shop_page_product_date', 100 );
function wc_shop_page_product_date() {
  
    echo '<span class="date_published">Published on: ' . get_the_date('Y-m-d', get_the_ID()) . '</span>';
}

This is more efficient than using global $product;

Upvotes: 0

Saqib Amin
Saqib Amin

Reputation: 1171

the_date function assumes you are inside a loop that is properly setting up the post data, which in your case seems not to be done. You could manually provide the product id using $product object and use get_the_date() function instead.

Below is the solution that should do for you:

add_action( 'woocommerce_after_shop_loop_item', 'wc_shop_page_product_date', 100 );
function wc_shop_page_product_date() {
    global $product;
    echo '<span class="date_published">Published on: ' . get_the_date('Y-m-d', $product->get_id()) . '</span>';
}

Here is a guide on customizing the date format: codex.wordpress.org/Formatting_Date_and_Time

Upvotes: 1

Related Questions