Skip to content

Instantly share code, notes, and snippets.

@jack-arturo
Last active December 9, 2024 22:09
Show Gist options
  • Save jack-arturo/59bcbf0bd6c2e077c336d60980122d65 to your computer and use it in GitHub Desktop.
Save jack-arturo/59bcbf0bd6c2e077c336d60980122d65 to your computer and use it in GitHub Desktop.
Applies a tag after a user has visited a post or page more than X times
<?php
/**
* Track visits to a specific post or page and apply a tag with WP Fusion if the visit count exceeds 5.
*/
function wpf_track_post_visits() {
// Replace with the IDs of the posts or pages you want to track
$target_post_ids = array( 123, 456 );
// Replace with the WP Fusion tag name you want to apply
$wp_fusion_tag = 'Example Tag Name';
// Replace with how many visits should apply the tag
$target_visit_count = 5;
//
// Don't edit after here:
//
$wp_fusion_tag = wpf_get_tag_id( $wp_fusion_tag );
// Ensure user is logged in
if ( ! is_user_logged_in() ) {
return;
}
// Ensure we're on either a post or page
if ( ! is_singular( 'post' ) && ! is_singular( 'page' ) ) {
return;
}
// Ensure we're on the right post or page ID
if ( ! in_array( get_the_ID(), $target_post_ids ) ) {
return;
}
$user_id = get_current_user_id();
$meta_key = 'post_visit_count_' . get_the_ID();
$visit_count = (int) get_user_meta( $user_id, $meta_key, true );
// Increment visit count
++$visit_count;
update_user_meta( $user_id, $meta_key, $visit_count );
// Apply WP Fusion tag if visit count exceeds 5 and tag hasn't been applied yet
if ( $visit_count > $target_visit_count ) {
wp_fusion()->user->apply_tags( array( $wp_fusion_tag ), $user_id );
}
}
add_action( 'wp', 'wpf_track_post_visits' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment