Get the count of newly published product (today) i

2019-08-22 13:11发布

问题:

I have a WooCommerce site where products are considered as trade/deal. Therefore, when someone take a trade (buy a product), it become out of stock.

How to display the number of products that has been published today (the new ones)?

ex: 4 New Trades (products) Published Today

回答1:

The custom function below will return with a SQL query the newly published products count (maid in the 24 hours):

function get_new_products_count(){
    global $wpdb;

    // 24 hours ago
    $is_24h_ago = date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s")." -1day"));

    // The SQL query
    $result = $wpdb->get_col( "
        SELECT COUNT(p.ID)
        FROM {$wpdb->prefix}posts as p
        WHERE p.post_type LIKE '%product%'
        AND p.post_status LIKE 'publish'
        AND p.post_date > '$is_24h_ago'
    " );

    return reset($result);
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and working


Usage example (in any php file):

$count = get_new_products_count();
$message = sprintf( __( '%s new trades have been published…' ), $count );
echo '<div class="woocommerce-message">'.$message.'</div>';

will display something like: