Problem with unwanted db-insertion on 'wp' hook
-
Can’t get my head around this…
I’m writing a plugin that’s gonna show the most recently viewed posts by current visitor. The plugin creates a table in the database with columns uid (user id), pid (post id) and v_time (time when viewed). So I thought it would be an easy task to just hook a function that inserts a row in this table to anything that just runs once during a single post display.
But strange things are happening. When I inspect the result in db I see TWO new rows for each time I visit a post, like this:
uid pid v_time
1 12618 2012-12-03 00:44:27
1 12674 2012-12-03 00:44:28The first row is the record that i expected, the second row comes from seemingly nowhere. I’ve tried to hook my function to ‘wp_head’, ‘wp_footer’, ‘the_content’ and ‘wp’, all with the same result.
I use
echo $wpdb->last_query
to see what’s happening, but all that is displayed is the correct insertion. And I always see in db another row inserted around 1 second after.If I empty the table and visit a post, the correct post is displayed in my widget. When reloading, the second one appears, which makes it seem like the second row is inserted AFTER visiting the post!
The unwanted post-id is for the post appearing in the next-post link. I tried to remove that link, but same result.
Here’s my code for the insertion so far:
function record_view($post){ global $wpdb, $rec_table; if(did_action( 'wp' ) === 1){ $query = new WP_Query( $post->query_string ); //if current page is not a single post just leave if($query->post_count != 1){ return; } //get the user id $p_id = $query->post->ID; //get the user id $cu = wp_get_current_user(); $uid = $cu->ID; //insert new post-id as viewed $wpdb->insert( $rec_table, array( 'pid' => $p_id, 'uid' => $uid, 'v_time' => current_time('mysql', 1) ) ); print_r($wpdb->last_query); print_r($wpdb->last_error); } } add_action('wp', 'record_view');
Does anybody have an idea of what’s going on here? Might be worth mentioning it’s a Buddypress installation.
[ Moderator note: duplicate thread deleted, please don’t start multiple threads on the same topic. ]
- The topic ‘Problem with unwanted db-insertion on 'wp' hook’ is closed to new replies.