Hello Friends, I was working on a project which was required to show visitors count on website, So I developed code for that and now I am sharing it so that if anyone required, can use it.
This code utilises get_option, add_option and update_option predefined wordpress function which stores key value pair data in options table of wordpress. So here I am going to create visitors key in options table using add_option function and it will be incremented every time user visits the website. To show visitors count use [visitors] shortcode in page, post, sidebar or wherever you want.
You just need to paste this code in functions.php file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function visitors_counter() { $option_name = "visitors"; $option_value = "1"; if (get_option($option_name) !== false) { $option_value = get_option($option_name); // The option already exists, so we just update it. update_option($option_name, ++$option_value); } else { // The option hasn't been added yet. We'll add it with $autoload set to 'no'. add_option($option_name, $option_value, "", "no"); } } add_action('wp_footer', 'visitors_counter'); // [visitors] function visitors_func($atts) { return get_option("visitors"); } add_shortcode('visitors', 'visitors_func'); |
or (if you want counter for specific page i.e contact page)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function visitors_counter() { if (is_page("contact")) { $option_name = "visitors"; $option_value = "1"; if (get_option($option_name) !== false) { $option_value = get_option($option_name); // The option already exists, so we just update it. update_option($option_name, ++$option_value); } else { // The option hasn't been added yet. We'll add it with $autoload set to 'no'. add_option($option_name, $option_value, "", "no"); } } } add_action('wp_footer', 'visitors_counter'); // [visitors] function visitors_func($atts) { return get_option("visitors"); } add_shortcode('visitors', 'visitors_func'); |
Reference
https://codex.wordpress.org/Function_Reference/add_option
https://developer.wordpress.org/reference/functions/get_option/
https://codex.wordpress.org/Function_Reference/update_option
https://developer.wordpress.org/reference/functions/add_shortcode/
Thanks
Please like & share
Comments