Question

I just discovered this wonderful message board :-) Hopefully someone can help me with a Wordpress issue I can't figure out..

I added a hook to my plugin file to insert the post id of the immediate posts I publish, in a table named "post_votes" - used to keep track of up & down votes for posts.

function post_votes($post_ID)  { 
 $wpdb->insert( $wpdb->prefix . 'post_votes', array( 'post_id' => $post_ID ) );
    return $post_ID;
}

add_action ( 'publish_post', 'post_votes' );

so the code above should add a post id in the post_id row (in post_votes table).. however I get,

Fatal error: Call to a member function insert() on a non-object

for

$wpdb->insert( $wpdb->prefix . 'post_votes', array( 'post_id' => $post_ID ) );
Was it helpful?

Solution

This is more or less a programming question. $wpdb is not available everywhere. It's a global variable. If you want to use it inside your own functions, just add global $wpdb; at the first line of the function.

For general programming questions, this might be another discovery for you: stackoverflow.com,it is about programming in specific. Regardless being PHP (as with wordpress plugins) or javascript stuff.

But for your wordpress problem, here is the code in full:

function post_votes($post_ID)  { 
 global $wpdb;
 $wpdb->insert( $wpdb->prefix . 'post_votes', array( 'post_id' => $post_ID ) );
    return $post_ID;
}

add_action ( 'publish_post', 'post_votes' );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top