wordpress - Simple php code to count visitors on one page and display in footer

I'm new, and learning. I only have a single digital product. I want to display the total number of purchases made, in my footer (on all pages). I have not been able to find a lightweight plugin that can do this, nor any code that works. I am using Woocommerce and since I only have a single product, buyers are taken directly to the checkout page once they click on "Buy". Once their payment goes through they are taken to a Thankyou page. I thought that if I can count the number of visitors who visit this Thankyou page and display that, it would give a pretty accurate number of purchases. I am able to do everything except that I do not know how to count the visitors on just that single page. My page is id=376, but how could I call that? Here is the php code that I'm trying. I think I need to swap the fgets($file, 1000) with the actual page id???
$path = 'C:/xampp/apps/wordpress/htdocs/counter.txt';
// Opens counter.txt to read the number of hits.
$file = fopen( $path, 'r' );
$count = fgets( $file, 1000 );
/*$count = fgets( $file, 1000 );*/
fclose( $file );
// Update the count.
if ($page_id == 376) {
$count = abs( intval( $count ) ) + 1;
}
// Output the updated count.
echo "This product has been purchased <strong>0000{$count}</strong> times\n";
// Opens counter.txt to change new hit number.
$file = fopen( $path, 'w' );
fwrite( $file, $count );
fclose( $file );```
Answer
Solution:
wc_orders_count( $status )
will retrieve a count of all orders for a status.
You can use a Woocommerce hook to display the code like this on the product page:
add_action( 'woocommerce_after_add_to_cart_button', 'se_67926603_count' );
function se_67926603_count() {
if (is_page(376)) {
$status = 'completed';
$count = wc_orders_count( $status );
echo "This product has been purchased <strong>{$count}</strong> times";
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: warning: a non-numeric value encountered in
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.