1

I want to log when a visitor to a post reads to the bottom. I figure the code would work similar to an infinite scroll (measuring window and the location of an element in that window) but I don't know where to start.

1 Answer 1

3

Places to start:

  1. Detecting Bottom of the page
  2. Once you have detected you're at the bottom, you'll need to make an AJAX request using WP AJAX (tutorial) to save that data.

You'll probably want to store "read_whole_post" as a postmeta value. Something along the lines of this:

add_action( 'wp_ajax_read_whole_post', 'se200479_read_whole_post' );
add_action( 'wp_ajax_nopriv_read_whole_post', 'se200479_read_whole_post' );

function se200479_read_whole_post() {
    // Passed through jQueryAjax in the settings.data argument
    $post_id = filter_input( INPUT_POST, 'post_id' );

    // Will return the existing count - ie 0
    $current_count = absint(get_post_meta( $post_id, 'read_whole_post', true ));

    // increment your count
    $current_count++;

    // Update the database value
    update_post_meta( $post_id, 'read_whole_post', $current_count );

    // Terminate the AJAX request
    wp_send_json_success();
}

You'll also want to consider storing something on the page in your JS, like updated = true to make sure you don't increase your count value multiple times if someone scrolls up and down the page a bunch!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.