I have code for saving metadata for Student post_type. While saving metadata I also want to add separate posts for each payment in payments array:

add_action( 'save_post', 'save_student_meta' );

function save_student_meta( $post_id ) {

    // Code gathering data form $_POST 

    // [...]

    $student_id = $post_id;
    $meta_key = '_student_name'; 
    $meta_value = $student_name,

    update_post_meta( $student_id, $meta_key, $meta_value );

    // For each payment add Payments post into database

    foreach( $student_payments as $payment ) {

        $postarr = array(

        wp_insert_post( $postarr, true );



Problem is, in database every Payment's post has also Student's metadata:

Payment post meta:

  • '_payment_date'
  • '_payment_amount'
  • '_payment_status'
  • '_payment_student_id'
  • '_student_name' <- should not be saved with Payment post

What could be problem here?

  • hmm your code block is incomplete, otherwise this should generate an infinite loop that ends with a fatal error. The fact this does not happen means that super important parts of the code have been removed. Please include the entire function ( including the parts you consider irrelevant )
    – Tom J Nowell
    Oct 2, 2018 at 16:32

1 Answer 1


The reason for that is the save_post loop. When you call wp_insert_post, it triggers save_post and thus inserts the student meta.

what you can do is, to check if the post type is correct while inserting the meta.


add_action( 'save_post', 'save_student_meta', 10, 2 );

function save_student_meta( $post_id, $post ) {
    if ( 'student' !== $post->post_type ) {
    // Code gathering data form $_POST 
  • Yes, you are right. I added post_type check inside save_student_meta() and it works. Thanks Oct 2, 2018 at 18:01
  • You can mark it as accepted answer Oct 2, 2018 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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