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
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:
I then created 3 snippets:
PHP snippet 1
PHP snippet 2
javascript snippet - put location to footer
You can track button clicks by using Ajax
Step 1 – function.php
Step 2: Add
data-post-id
to your button.Step 3: Create custom.js