It is dead easy to set a custom field to your post, programmatically when the post is published. For example, whenever your post is published, you might want to add a custom field “submitted” and set its value to “1”, when a post is published.

Here is how you do it. Call the publish_post hook, pass a function since the hook runs whenever a post it published.

We are creating a new custom field “submit” and setting its value to “1” when ever the post is published. The code will only create custom field, when the user role is “author”. If you dont check for user role, this code will run for even admins and all users. We are going one more step with this code, against by checking another custom field “custom_field_1” with a particular value exists.

We pull the value of a custom field using get_post_meta function and we create custom field for the post using add_post_meta function. Note that true parameter, makes the custom field unique and no duplication possible.

[php]

add_action(‘publish_post’,’create_custom_field’)

function create_custom_field ($post_id) {
global $wpdb;
if ( current_user_can(‘contributor’) ) {

if(get_post_meta($post_id,’custom_field_1′,true) == ‘1’){
add_post_meta($post_ID,’submit’,’1′,true);
return $post_id;
}

return $post_id;
}

}

[/php]

For full list of action hooks, applied to posts, please go through: http://codex.wordpress.org/Plugin_API/Action_Reference