questions

Show how old a product is on WooCommerce single product page

Rate this post

By using the action hook woocommerce_before_add_to_cart_form, I am trying to check how old the product is by checking if the publish date is older than three months.

If, and only if, the product was published three months ago or more, show a message using a DIV-tag on the product page.

The general idea here is to encourage visitors and registered customers to purchase the product before it goes out of availability, whereof availability means no longer available in the product catalog – as in removing the product for good.

This is the code I’m working with:

add_action( 'woocommerce_before_add_to_cart_form', 'encourage_product_purchase' );
function encourage_product_purchase() {
    
    $product_published = 'Availabe since ' . human_time_diff(get_the_time('U'),current_time('timestamp'));
    
    $three_months = '3';

        if ( $product_published >= get_the_time( $three_months ) ) {

            ?>
            <div class="three-month-product">This product has been available for three months and will soon be removed from our catalog. You have 10 days left to purchase.</div>
            <?php

        }
}

 

✔️Solution:

You can use $product->get_date_created();

So you get:

function action_woocommerce_before_add_to_cart_form() {
    // Get the global product object
    global $product;

    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get product date created
        $product_date_created  = $product->get_date_created()->date( 'Y-m-d' );

        // Get now datetime (from Woocommerce datetime object)
        $datetime_now = new WC_DateTime();
        
        // Three months ago from today
        $three_months_ago = date( 'Y-m-d', strtotime( '-3 months', strtotime( $datetime_now ) ) );
        
        // Compare
        if ( strtotime( $product_date_created ) < strtotime( $three_months_ago ) ) {
            echo '<div class="three-month-product">' . __('This product has been available for three months and will soon be removed from our catalog. You have 10 days left to purchase.', 'woocommerce' ) . '</div>';
        }
    }
}
add_action( 'woocommerce_before_add_to_cart_form', 'action_woocommerce_before_add_to_cart_form', 10, 0 );

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button