0

我正在尝试在 Wordpress 中的 save_post 钩子和 wp_insert_post 函数上插入新帖子。当我尝试保存或更新帖子时,它会触发无限循环。任何人都可以帮忙吗?

这是我的代码:

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 );       
4

2 回答 2

0

您可以通过删除操作并在 wp_insert_post() 函数代码之后添加来避免无限循环问题。检查下面的代码。

function mv_save_wc_order_other_fields( $post_id ) {

    remove_action( 'save_post', 'mv_save_wc_order_other_fields' );

    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' );

}
add_action( 'save_post', 'mv_save_wc_order_other_fields', 10, 1 ); 
于 2020-10-13T10:02:16.810 回答
0

您想使用 transition_post_status 以便仅在状态更改时触发。这是我所做的:

function video_post_created($new, $old, $post) {
    if ( ( $new == 'publish' ) && ( $old != 'publish' ) && ( $post->post_type == 'roku_video' ) ) {
        my_update_post_meta_function($post);
    }
}
add_action( 'transition_post_status', 'video_post_created', 10, 3 );

请注意我如何检查新状态是否为已发布但来自不同状态(例如草稿)并检查我的特定帖子类型。我的是自定义帖子类型。如果这一切都匹配,那么我调用我自己的函数 my_update_post_meta_function 并传递 post 对象。您不必调用另一个函数。你可以把你的代码放在那里。我只是保持清洁。

于 2020-10-13T00:48:20.850 回答