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 want to set up a basic 'post rating' system for my site - I don't want to use a plugin - so I want to add the custom field 'rating' to each new custom post and populate this field with the number 1.

Is this possible? Or am I going about this the wrong way? Did a lot of searching a found not much, add_post_meta() ? I'm not sure where that would go.

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

you can do that with hooking a simple function to save_post hook

add_action('save_post','my_rating_field');
function my_rating_field($post_id){
    global $post;
        // verify if this is an auto save routine. 
        // If it is our form has not been submitted, so we dont want to do anything
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
            return;

        // verify this came from the our screen and with proper authorization,
        // because save_post can be triggered at other times
        if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
            return;
        // Check post type
        if ($post->post_type != "YOUR_POST_TYPE_NAME")
            return;

        // OK, we're authenticated: we need to find and save the data
    $rating = get_post_meta($post_id,'rating',true);
    //if field not exists create it and give it the value of one
    if (empty($rating) || !isset($rating)){
        update_post_meta($post_id,'rating',1);
    }
}
share|improve this answer
    
thanks. nice code. I had to comment out the if ( !wp_verify_nonce line - I am calling this from the theme's functions.php and not a plugin. Is there a way I can verify authorisation in this case? thanks –  edzillion May 26 '11 at 12:35
add comment

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.