[email protected]

How To Add Transients To A WooCommerce Query

June 12, 2024

How To Add Transients To A WooCommerce Query

In this video I’ll show you how to add transients to a WooCommerce query to improve performance.

A transient is a way to persist WordPress and WooCommerce data to the database to avoid running heavy queries which can slow down your database and in turn cause performance issues on your WordPress site.

We can create a transient with a lifetime of say 24 hours and out that rather than outputting the contents of a massivce query.

In my previous post I created a code snippet to output number of products purchased this could be a very expensive query to run if there are hundreds of thousands of orders and a lot of products. I’ll expand on that code snippet to add a transient.

Video

Code

function nm_display_product_purchase_count() {
    global $product;

    if ( ! is_a( $product, 'WC_Product' ) ) {
        return;
    }

    $product_id = $product->get_id();
    $transient_key = 'tot_product_purchase_count_' . $product_id;
    $order_count = get_transient( $transient_key );
	
	
	echo "transient _key = ".$transient_key;

	echo "order count = ".$order_count;

    if ( false === $order_count ) {
        $order_count = 0;
		echo "run query";
        // Get all orders
        $args = array(
            'status' => array( 'wc-completed', 'wc-processing', 'wc-on-hold' ),
            'limit' => -1, // Retrieve all orders
        );

        $orders = wc_get_orders( $args );

        // Loop through orders and count product purchases
        foreach ( $orders as $order ) {
            foreach ( $order->get_items() as $item ) {
                if ( $item->get_product_id() == $product_id ) {
                    $order_count += $item->get_quantity();
                }
            }
        }

        // Set transient to cache the result for 20 hours (72000 seconds)
        set_transient( $transient_key, $order_count, 24 * HOUR_IN_SECONDS );
    }

    // Display the purchase count before the Add to Cart button
    echo '<p><strong>Purchased: ' . $order_count . ' times</strong></p>';
}

// Hook the custom function into the single product summary
add_action( 'woocommerce_single_product_summary', 'nm_display_product_purchase_count', 25 );

Wrap Up

If you are having a performance issue on your WooCommerce store, get in touch I can help to speed things up.

Photo by Marc Sendra Martorell on Unsplash

Article by GeneratePress

Lorem ipsum amet elit morbi dolor tortor. Vivamus eget mollis nostra ullam corper pharetra torquent auctor metus. Natoque tellus semper taciti nostra primis lectus donec tortor semper habitant taciti primis tempor montes.