Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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:

<?php
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):

<?php
....
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.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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(){
    if(isset($_REQUEST['bar')
        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.

if(have_posts()):
    while(have_posts()):
        the_post();
        $foo = get_post_meta($post->ID, 'bar', true);
        echo $foo;
    endwhile;
else:

endif;

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!

share|improve this answer

The hook is save_post, not post_save.

share|improve this answer
    
Yeah, sorry, thanks :) –  imaginonic Sep 25 '11 at 14:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.