wordpress - 我如何在帖子保存时插入另一个帖子?
问题描述
我正在尝试在 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 );
解决方案
您可以通过删除操作并在 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 );
推荐阅读
- javascript - Onclick history.push 在子组件中反应。- 警告:在现有状态转换期间无法更新(例如在 `render` 中)
- php - 如何使用 PHP 将输出数组转换为字符串或变量?
- c++ - 我的 NQueens 问题代码中的错误是什么?
- java - 使用嵌套的 for-each 删除元素时出现 ConcurrentModificationException
- javascript - JS - 数组项不可用
- php - X-Editable 添加分组到下拉菜单
- rust - Rust Traits - 我如何在不消耗它的情况下使用它?
- reactjs - React Native Expo:如何使用 Firebase 从集合中的多个文档中查询选择字段?
- flutter - 在 Flutter 中设置 ToggleButtons 之间的间隙
- c++ - 使用 wxMac 在 OSX 上构建 wxWidgets wxWebView 失败