首页 > 解决方案 > 我如何在帖子保存时插入另一个帖子?

问题描述

我正在尝试在 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 );       

标签: wordpresswordpress-plugin-creation

解决方案


您可以通过删除操作并在 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 ); 

推荐阅读