Skip to content

Instantly share code, notes, and snippets.

@wpmark
Created January 14, 2013 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wpmark/4534269 to your computer and use it in GitHub Desktop.
Save wpmark/4534269 to your computer and use it in GitHub Desktop.
Add data to a Custom WordPress table
<?php
/* create a function to get the values from this page load */
function wpct_track_content() {
/* call the global post variable to gain access to post data */
global $post;
/* setup an array to store all our values */
$wpct_post_values = array();
/* collect the information we need, starting with post id */
$wpct_post_id = $post->ID;
/* get the current logged in user */
$wpct_current_user = wp_get_current_user();
/* get the logged in user ID */
$wpct_current_user_id = $wpct_current_user->ID;
/* get the logged in users username */
$wpct_current_user_name = $wpct_current_user->user_login;
/* get the current date and time */
$wcpt_date = date( 'Y-m-d H:i:s' );
/* get the users ip address */
$wpct_ip = $_SERVER[ 'REMOTE_ADDR' ];
/* add all collected values to the array */
$wpct_post_values[ 'wpct_post_id' ] = $wpct_post_id;
$wpct_post_values[ 'wpct_user_id' ] = $wpct_current_user_id;
$wpct_post_values[ 'wpct_username' ] = $wpct_current_user_name;
$wpct_post_values[ 'wpct_date' ] = $wcpt_date;
$wpct_post_values[ 'wpct_ip' ] = $wpct_ip;
/* lets check this is a singular page view, we are not tracking other page views */
if( is_singular() ) {
/* record a page load in the table writing entry to database */
global $wpdb;
/* get the table name */
$wpct_tablename = $wpdb->prefix . "wpct";
/* insert the values into a row in the custom table */
$wpdb->insert(
$wpct_tablename, // name of our custom table
$wpct_post_values // array of values to write
);
}
}
/* hook our content values function into wordpress */
add_action( 'wp', 'wpct_track_content' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment