WooCommerce管理员订单编辑保存帖子
问题描述:
在WooCommerce中,当我提交时,如何捕获添加到订单中的自定义选择字段编辑管理页面?WooCommerce管理员订单编辑保存帖子
我在文件class-wc-meta-box-order-data.php
中添加了此自定义选择字段。我得到这个:
但我不知道如何捕捉或保存$_POST['vendor']
我试图在wp-admin/post.php
,添加$_POST['vendor']
但它不工作。
这是我添加的代码:
<select class="wc-customer-search" id="customer_user" name="customer_user" data-placeholder="<?php esc_attr_e('Guest', 'woocommerce'); ?>" data-allow_clear="true">
<option value="<?php echo esc_attr($user_id); ?>" selected="selected"><?php echo htmlspecialchars($user_string); ?></option>
</select>
<!--/email_off-->
</p>
<p> <label for="order_status">供應商: </label>
<select name="vendor">
<?php
global $wpdb;
$user_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->users");
for($i=1;$i<=$user_count;$i++){
$user_info = get_userdata($i);
if (implode(', ', $user_info->roles)=='vendor')
echo "<option value=".$user_info->user_login.">$user_info->user_login</option>";
}
?>
</select></p>
如何,我可以得到提交的值,我怎么能保存呢?
答
覆盖核心文件是开发者禁止的东西。 所以这不是正确的做法。
执行此操作的方法是使用源代码中的可用钩子,而不是覆盖此核心文件,因为在插件更新时您将失去一切。
- 全部替换原有的核心文件
- 添加该代码,而不是(我有做一些轻微的必要的修改)。
这里是替换代码+钩子将数据保存到订单元数据:
add_action('woocommerce_admin_order_data_after_order_details', 'custom_code_after_order_details', 10, 1);
function custom_code_after_order_details ($order) {
$value = get_post_meta($order->get_id(), '_vendor', true);
?>
<p> <label for="order_status">供應商: </label>
<select name="vendor">
<?php global $wpdb;
$user_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->users");
echo '<option value="">Select a vendor</option>';
for($i=1;$i<=$user_count;$i++){
$user_info = get_userdata($i);
if (implode(', ', $user_info->roles)=='customer'){
$user_login = $user_info->user_login;
$selected = $value == $user_login ? 'selected' : '';
echo '<option '.$selected.' value="'.$user_login.'">'.$user_login.'</option>';
}
}
?>
</select></p>
<input type="hidden" name="custom_select_field_nonce" value="<?php echo wp_create_nonce(); ?>">
<?php
}
add_action('save_post', 'save_custom_code_after_order_details', 10, 1);
function save_custom_code_after_order_details($post_id) {
// We need to verify this with the proper authorization (security stuff).
// Check if our nonce is set.
if (! isset($_POST[ 'custom_select_field_nonce' ])) {
return $post_id;
}
$nonce = $_REQUEST[ 'custom_select_field_nonce' ];
//Verify that the nonce is valid.
if (! wp_verify_nonce($nonce)) {
return $post_id;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post_id;
}
// Check the user's permissions.
if ('page' == $_POST[ 'post_type' ]) {
if (! current_user_can('edit_page', $post_id)) {
return $post_id;
}
} else {
if (! current_user_can('edit_post', $post_id)) {
return $post_id;
}
}
// Update the meta field in the database.
update_post_meta($post_id, '_vendor', $_POST[ 'vendor' ]);
}
代码放在您的活动子主题(或主题)的function.php文件或还在任何插件文件中。
此代码已经过测试并可正常工作。