php - 在 Woocommerce 订单上使用 save_post 挂钩时出现“未定义索引:post_type”
问题描述
我的 debug.log 中出现错误,某些代码在结帐时保存了我的自定义字段。我似乎无法找到问题所在:
PHP Notice: Undefined index: post_type in /wp-content/themes/theme-child/functions.php on line 857
这是我的代码:
// Saving
add_action( 'save_post', 'tcg_save_meta_box_data' );
function tcg_save_meta_box_data( $post_id ) {
// Only for shop order
if ( 'shop_order' != $_POST[ 'post_type' ] )
return $post_id;
// Check if our nonce is set (and our cutom field)
if ( ! isset( $_POST[ 'tracking_box_nonce' ] ) && isset( $_POST['tracking_box'] ) )
return $post_id;
$nonce = $_POST[ 'tracking_box_nonce' ];
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce ) )
return $post_id;
// Checking that is not an autosave
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Check the user’s permissions (for 'shop_manager' and 'administrator' user roles)
if ( ! current_user_can( 'edit_shop_order', $post_id ) && ! current_user_can( 'edit_shop_orders', $post_id ) )
return $post_id;
// Saving the data
update_post_meta( $post_id, 'Other notes', sanitize_text_field( $_POST[ 'tracking_box' ] ) );
}
谁能发现错误?
解决方案
钩子中$_POST['post_type']
不可用save_post
……这个动作钩子有 3 个可用参数$post_id
:$post
和$update
。所以改为使用:
add_action( 'save_post', 'tcg_save_meta_box_data', 10, 3 );
function tcg_save_meta_box_data( $post_id, $post, $update ) {
// Only for shop order
if ( 'shop_order' != $post->post_type )
return $post_id;
// ...
更好:或者以这种方式直接使用复合钩子save_post_shop_order
:
add_action( 'save_post_shop_order', 'tcg_save_meta_box_data', 10, 3 );
function tcg_save_meta_box_data( $post_id, $post, $update ) {
// Check if our nonce is set (and our custom field)
if ( ! isset( $_POST[ 'tracking_box_nonce' ] ) && isset( $_POST['tracking_box'] ) )
return $post_id;
$nonce = $_POST[ 'tracking_box_nonce' ];
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce ) )
return $post_id;
// Checking that is not an autosave
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// User capability check: Check if the current user can edit an order
if ( ! current_user_can( 'edit_shop_order', $post_id ) )
return $post_id;
// Saving the data
update_post_meta( $post_id, 'Other notes', sanitize_text_field( $_POST[ 'tracking_box' ] ) );
}
代码在您的活动子主题(活动主题)的 function.php 文件中。它应该更好地工作。
推荐阅读
- android - 如何给一个应用程序,在我自己的 AOSP -eng 版本上运行,root 权限?
- python - 如何将元组列表转换为具有重复键的字典?
- python - 使用 sklearn 模块提取 3 个最佳匹配项
- typescript - 根据承诺的结果在量角器中创建动态它
- ios - async function run() { ^^^^^^^^ SyntaxError: Unexpected token function
- sql-server - 为什么在 SQL Server 中违反 PRIMARY KEY 约束返回错误代码 2627 而不是 2601?
- django - Django:如何让 setUpTestData 为所有测试运行一次?
- angular - 如何更改 *ngFor 中的单个 mouseover 和 mouseout 事件?
- powershell - 如何使用 PowerShell 将字符替换为 $_
- javascript - 揭示模块模式结合 ES6 模块