wp_insert_post
runs whenever a post is updated, not just when it’s first saved. So your payment_meta()
function is running every time a post is saved, and since you’re using add_post_meta()
in that function, a new meta entry is created every time the post is saved.
Instead of using add_post_meta()
stick to just using update_post_meta()
if a value isn’t already set this will still create the meta, but if it already exists it will update the existing value, rather than adding a new one:
function payment_meta($post_ID)
{
$user_id = get_post_field( 'post_author', $post_ID );
$user_role="editor";
$post_type="portfolio";
if( get_post_type( $post_ID ) == $post_type ) {
if ( get_post_meta($post_ID, '_payment', true) != '1' && !user_can( $user_id, $user_role )) {
update_post_meta($post_ID, '_payment', '0');
}
else if ( get_post_meta($post_ID, '_payment', true) == '' && user_can( $user_id, $user_role )) {
update_post_meta($post_ID, '_payment', '1');
}
}
}
add_action('wp_insert_post', 'payment_meta', 11, 1);