How to Create a Website Visitor Counter with Wix Velo
With Wix Velo, you can create a custom visitor counter that updates whenever someone visits your site. This tutorial will guide you through implementing a visitor counter using Wix Velo.
Step 1: Set Up Your Database Collection
First, we need a place to store our visitor count. Wix provides a built-in Content Manager where you can create and manage database collections.
Go to your site's Content Manager.
Click on Add New Collection and name it VisitorCount.
Add a field named count with type Number.
To initialize the counter, manually add a row in the VisitorCount collection with the count value set to 0. This sets up the starting point for our counter.
Step 2: Add the Visitor Counter Code
Next, we need to write the code to update the visitor count each time the page is loaded.
Open the page where you want to display the visitor counter.
Click on the Code icon at the top of the editor to open the page’s code section.
Add the Following Code:
import wixData from 'wix-data';
// Function to increment the visitor count
function incrementVisitorCount() {
wixData.query('VisitorCount')
.find()
.then((results) => {
if (results.items.length > 0) {
let item = results.items[0];
item.count += 1;
wixData.update('VisitorCount', item)
.then(() => {
$w('#visitorCountText').text = item.count.toString();
})
.catch((err) => {
console.error('Error updating visitor count: ', err);
});
}
})
.catch((err) => {
console.error('Error querying visitor count: ', err);
});
}
// Call the function when the page is loaded
$w.onReady(() => {
incrementVisitorCount();
});
Step 3: Add a Text Element to Display the Count
Now, we need to display the updated visitor count on the page.
Add a Text Element:
Drag and drop a text element onto your page.
Set the ID of this text element to visitorCountText. This ID is used in our code to update the displayed count.
Step 4: Publish Your Site
Finally, publish your site to see the visitor counter in action.
Publish Your Site:
Click on the Publish button in the top right corner of the Wix editor.
Visit your site to verify that the counter increments each time the page is loaded.
Conclusion
With these simple steps, you now have a functional visitor counter on your Wix website. This counter increments every time someone visits your page, giving you a basic way to track visitor engagement. Wix Velo provides powerful tools to customize and extend the functionality of your website, allowing you to create unique and interactive features like this visitor counter.
Happy coding!
Comments