WordPress Action Hooks and Post ID?

I’m creating a very basic WordPress plugin whose purpose is to display a numerical value beside each post.

My Logic for the plugin function (plugin.php) is this:

function foo($post_id){
$somevalue=1 //Some random value
add_post_meta($post_id, 'posts_numericalvalue', '0', true) or update_post_meta($_post_id, 'posts_numericalvalue', $somevalue);

add_action('post_save', 'foo');

And in my template’s index.php, I have (inside the loop):

printf(__('Permanent Link to %s', 'kubrick'), the_title_attribute('echo=0'));
$numerical_val = get_post_meta($post->ID, posts_numericalvalue); 
echo 'this post has a value of ' .$numerical_val;

1) The code above is obviously not working. I think its because my function in plugin.php requires me to pass the current post’s ID, but the action hook doesn’t pass the post’s current ID I guess (correct me if I’m wrong). How do I pass the post ID to my function inside plugin.php using an action hook?

2) Any other elegant way of doing this? I just need to assign my posts with a numerical value which should be updated with 1 if the post already has one, zero if the post hasn’t got one already.

Any help is much appreciated. Thanks.

Solutions Collecting From Web of "WordPress Action Hooks and Post ID?"

When hooking the save_post action, you really need to isolate your operations so that every page/post/post_type save doesn’t try to add your post meta to the post.

function foo_save(){
        update_post_meta($_REQUEST['post_ID'], 'bar', $_REQUEST['bar']);
add_action('save_post', 'foo_save');

The main issue with your code above is posts_numericalvalue needs quotes. Also, to use $post->ID you will need to make sure your code is in the loop or declare global $post; somewhere above your code if you’re using it outside of the loop.

        $foo = get_post_meta($post->ID, 'bar', true);
        echo $foo;


Also, if you are distributing this plugin to the public, you will need to create a function to filter the content and add your post meta there since you won’t have true access to the template files.

If this is just for your own use in your theme, I would place the function foo_save() in your functions.php file instead.

Hope this helps you out!

The hook is save_post, not post_save.