skip to Main Content

I want to count every time a specific button is pressed. I am using wordpress and the button is created using elementor, I then want to increment the count of a meta field using jetengine.

I have followed a tutorial and successfully been able to count every time a person clicks into a post, using this code:

function increment_post_views() {
    if (is_single()) {
        $post_id = get_the_ID();
        $views = get_post_meta($post_id, 'products_views', true);
        // If the 'post_views' meta field doesn't exist, initialize it to 1
        if (empty($views)) {
            $views = 1;
        } else {
            $views = intval($views) + 1;
        }
        // Update the 'post_views' meta field with the incremented value
        update_post_meta($post_id, 'products_views', $views);
    }
}
add_action('wp', 'increment_post_views');

Could anyone help me write a code snippet to track the button clicks? to my knowledge i will need to add some jquery to handle the click events and send the data to backend and update the meta fields using the same method? i have very little knowledge in coding so any help would be appreciated!

2

Answers


  1. Chosen as BEST ANSWER

    ok this took me all day but i got working. If anyone has any comments to make this code better please do! there is a lot of console messages in code but it helped with troubleshooting.

    The highlighted terms here will need to be changed in the code to suit your application: I created a custom post type using jetengine called industry-jobs. I then created a number meta field in this post type called click_count I then created a button in elementor and assigned the CCS class as track-click-button and a custom attribute:

    data-post-id="<?php echo $post->ID; ?>"
    

    I then created 3 snippets:

    PHP snippet 1

    function update_click_count() {
    if (isset($_POST['post_id'])) {
        $post_id = intval($_POST['post_id']);
    
        // Validate that the post exists and is of the correct post type
        if (get_post_type($post_id) === 'industry-jobs') {
            // Get the current click count
            $current_count = (int) get_post_meta($post_id, 'click_count', true);
    
            // Increment the click count
            $new_count = $current_count + 1;
    
            // Update the meta field
            update_post_meta($post_id, 'click_count', $new_count);
    
            // Send success response
            wp_send_json_success(['new_count' => $new_count]);
        } else {
            wp_send_json_error('Invalid post type.');
        }
    } else {
        wp_send_json_error('Missing post ID.');
    }
    
    wp_die(); // Required to terminate and return a proper response
    }
    add_action('wp_ajax_update_click_count', 'update_click_count');
    add_action('wp_ajax_nopriv_update_click_count', 'update_click_count');
    

    PHP snippet 2

    if (!function_exists('enqueue_combined_click_tracker_script')) {
    function enqueue_combined_click_tracker_script() {
        if (is_singular('industry-jobs')) {
            // Register the JavaScript file that contains the tracking logic
            wp_register_script(
                'click-tracker-script',
                get_stylesheet_directory_uri() . '/js/click-tracker.js', // Adjust 
    the path to your JavaScript file
                ['jquery'], // jQuery dependency
                null,
                true // Load in the footer
            );
    
            // Pass ajaxurl to the script
            wp_localize_script('click-tracker-script', 'clickTrackerData', [
                'ajaxurl' => admin_url('admin-ajax.php')
            ]);
    
            // Enqueue the JavaScript file after localization
            wp_enqueue_script('click-tracker-script');
    
            // Inline JavaScript to set the post ID dynamically
            ?>
            <script type="text/javascript">
                document.addEventListener('DOMContentLoaded', function () {
                    const button = document.querySelector('.track-click-button');
                    if (button) {
                        console.log('Inline JS: Button found');
                        button.setAttribute('data-post-id', '<?php echo 
    get_the_ID(); ?>');
                    } else {
                        console.error('Inline JS: Button not found');
                    }
                });
            </script>
            <?php
        }
    }
    add_action('wp_enqueue_scripts', 'enqueue_combined_click_tracker_script');
    }
    

    javascript snippet - put location to footer

    console.log('click-tracker.js: Script is running');
    
    jQuery(document).ready(function ($) {
    console.log('click-tracker.js: jQuery document ready');
    
    const button = $('.track-click-button');
    
    if (button.length > 0) {
        console.log('click-tracker.js: Button found', button);
    
        button.on('click', function () {
            const postID = $(this).data('post-id');
            console.log('Button Clicked, Post ID:', postID);
    
            if (postID) {
                $.ajax({
                    url: clickTrackerData.ajaxurl, // Use the localized ajaxurl
                    type: 'POST',
                    data: {
                        action: 'update_click_count',
                        post_id: postID,
                    },
                    success: function (response) {
                        if (response.success) {
                            console.log('Click count updated successfully');
                        } else {
                            console.error('Failed to update click count', 
    response);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('AJAX request failed:', status, error);
                    }
                });
            } else {
                console.error('Post ID is missing from the button');
            }
        });
    } else {
        console.error('click-tracker.js: Button not found');
    }
    });
    

  2. You can track button clicks by using Ajax

    Step 1 – function.php

    function enqueue_custom_scripts() {
        wp_enqueue_script('jquery');
        wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom.js', array('jquery'), null, true);
        wp_localize_script('custom-script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
    }
    add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
    
    function increment_button_clicks() {
        if (isset($_POST['post_id'])) {
            $post_id = intval($_POST['post_id']);
            $button_clicks = get_post_meta($post_id, 'button_clicks', true);
            
            if (empty($button_clicks)) {
                $button_clicks = 1;
            } else {
                $button_clicks = intval($button_clicks) + 1;
            }
            update_post_meta($post_id, 'button_clicks', $button_clicks);
            echo $button_clicks;
        }
        wp_die();
    }
    add_action('wp_ajax_increment_button_clicks', 'increment_button_clicks');
    add_action('wp_ajax_nopriv_increment_button_clicks', 'increment_button_clicks');
    

    Step 2: Add data-post-id to your button.

    data-post-id="<?php echo $post->ID; ?>"
    

    Step 3: Create custom.js

    jQuery(document).ready(function ($) {
      $(".your-button-class").on("click", function () {
        var postID = $(this).data("post-id");
        $.ajax({
          type: "POST",
          url: ajax_object.ajax_url,
          data: {
            action: "increment_button_clicks",
            post_id: postID,
          },
          success: function (response) {
            console.log("Button click recorded: " + response);
          },
          error: function (error) {
            console.log("Error recording button click: ", error);
          },
        });
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search