I'm trying to insert new post on save_post hook and wp_insert_post function in Wordpress. When i try to save or update post it's triggering an infinite loop. Can anyone help?
Here is my code:
function mv_save_wc_order_other_fields( $post_id ) {
if(isset($_POST[ '....' ]) && !empty($_POST["...."])){
if($_POST[ '....' ] == 3){
$my_post = array(
'post_title' => "$post_id Bill",
'post_content' => "-",
'post_status' => 'publish',
'post_type' => 'tahsilat',
'post_author' => 1,
);
$bill_id = wp_insert_post( $my_post, $wp_error );
update_post_meta( $bill_id, 'customer', $_POST[ 'user' ] );
update_post_meta( $bill_id, 'customer', $_POST[ 'user' ] );
}else{
update_post_meta( $post_id, 'payment', $_POST[ '...' ] );
update_post_meta( $post_id, 'amount', $_POST[ 'amount' ] );
}
}
add_action( 'save_post', 'mv_save_wc_order_other_fields', 10, 1 );
You can avoid an infinite loop issue by removing your action and add after your wp_insert_post() function code. check below code.