在那里我想在我的订单woocommerce中添加自定义元框。我已经创建了它,但在那里我有问题,每当我试图保存它不会改变我的代码:
add_action( 'add_meta_boxes', 'add_meta_boxes' );
function add_meta_boxes()
{
add_meta_box(
'woocommerce-order-my-custom',
__( 'Order Driver' ),
'order_my_custom',
'shop_order',
'side',
'default'
);
}
function order_my_custom()
{
$servername = "localhost";
$username = "root";
$password = "no_password";
$dbname = "testtable";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM wp_posts WHERE post_type='drivers'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select style='width:100%;' >";
echo "<option> --- Select ---</option>";
while($row = $result->fetch_assoc()) {
echo "<option value=".$row['ID'].">".$row['post_title']."</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
}
我现在该怎么办?有人给我解决方案,所以我的代码可以像我想要的那样工作吗?
当我使用时:
echo "<option".($selected=='')?'':'selected'." value=".$row['ID'].">".$row['post_title']."</option>";
如果我只使用:
echo "<option value=".$row['ID'].">".$row['post_title']."</option>";
现在:
答案 0 :(得分:1)
在选择驱动程序后保存订单时,您缺少在订单元中保存所选驱动程序ID的代码。
我没有对代码进行测试,但希望它有所帮助。
add_action( 'add_meta_boxes', 'add_meta_boxes' );
function add_meta_boxes()
{
add_meta_box(
'woocommerce-order-my-custom',
__( 'Order Driver' ),
'order_my_custom',
'shop_order',
'side',
'default'
);
}
function order_my_custom()
{
global $woocommerce, $post;
$order_id =$post->ID;
$servername = "localhost";
$username = "root";
$password = "no_password";
$dbname = "testtable";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM wp_posts WHERE post_type='drivers'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
ob_start();?>
<select name='order_driver' style='width:100%;' >
<option value=""> --- Select ---</option>
<?php
while($row = $result->fetch_assoc()) {
$order_driver = get_post_meta($order_id,'order_driver',true);
?>
<option <?php echo ($row['ID']==$order_driver)?'selected':''?> value="<?php echo $row['ID']?>"><?php echo $row['post_title']?></option>
<?php } ?>
</select>
<?php } else {?>
<option value="">0 Results</option>
<?php }
echo ob_get_clean();
$conn->close();
}
function save_drivers_meta( $post_id, $post, $update ) {
$post_type = get_post_type($post_id);
/*
* Make sure we are updating post meta only for shop orders
*/
if ( "shop_order" != $post_type ) return;
// - Update the post's order_driver value if it's set.
if ( isset( $_POST['order_driver'] ) ) {
update_post_meta( $post_id, 'order_driver', sanitize_text_field( $_POST['order_driver'] ) );
}
}
add_action( 'save_post', 'save_drivers_meta', 10, 3 );