Hi Folks,
I'm looking to see if anyone can help me with a quirky little issue I have with "update_post_meta"?
I'm writing a basic sidebar widget which shows the current most viewed postings for the month. I have most of it working, apart from the fact that my update_post_meta instruction is updating two records instead of the one requested.
I am using the wp_postmeta table to add in (and update) a custom key called "_pageview". Here is my function code which is called in the header and sidebar:
function bbd_create_pageview () {
global $wpdb, $post; // call global for use in function
// get the current dat info
$today=array();
$today = getdate();
$curdate = $today['mday'];
$curhour = $today['hours'];
//check if it's the morning of the 1st and reset posts
if ($curdate == 1 && $curhour < 10)
$wpdb->query("UPDATE wp_postmeta SET meta_value = 0 WHERE meta_key = '_pageview'");
$data = get_post_meta($post->ID, '_pageview', true); // get the data using the post ID
if (is_null($data)) // check to make sure data exists and not null
{
add_post_meta($post->ID, '_pageview', 1, true); // if it is null create a new entry
}
else
{
$newcount = $data + 1; // incriment the count by one
update_post_meta($post->ID, '_pageview', $newcount, $data); //update the meta-data with new count number
}
} // end function
add_action('wp_head','bbd_create_pageview'); // attach ppbv_page_viewed to the wp_head hook
function bbd_show_popular () {
global $wpdb; // call global for use in function
echo "<div id='popular_by_views'>"; // create a container
echo "<h2>This Month's Popular Articles</h2>"; // write the title
echo "<ol id='popular_by_views_list'>"; // create an ordered list
$popular = $wpdb->get_results("SELECT * FROM wp_postmeta WHERE meta_key = '_pageview' ORDER BY meta_value+0 DESC LIMIT 0,10",ARRAY_N);
foreach($popular as $post){ // loop through the returned array of popular posts
$ID = $post[1]; // store the data in a variable to save a few characters and keep the code cleaner
$num = (int)$post[3];
$views = number_format($num); // number_format adds the commas in the right spots for numbers (ex: 12543 to 12,543)
$post_url = get_permalink($ID); // get the URL of the current post in the loop
$title = get_the_title($ID); // get the title of the current post in the loop
echo "<li><a href='{$post_url}'>{$title}</a> - {$views} views</li>"; // echo out the information in a list-item
} // end the loop
echo "</ol>"; // close the ordered list
echo "</div>"; // close the container
} // end function
I have tried even using a new table but it still wants to update the current posts custom field and also the last post visited.
If anyone could help shed some light on this would be greatly appreciated.
Many thanks
Angus