由于 WooCommerce 不在訂單頁面上顯示產品圖片,因此我創建了一個 PHP 函式來添加新列并顯示我需要的所有詳細資訊,但我遇到了一些問題。
當舊訂單中的產品之一被洗掉時,訂單會出現錯誤,因為該影像/產品不存在并回傳嚴重錯誤。
有人可以給我一個可能的解決方案嗎?
我需要告訴 wordpress“如果這個圖片/產品不存在或為空,它會顯示一些文本”

// The data of the new custom column in admin order list
add_action( 'manage_shop_order_posts_custom_column' , 'admin_orders_list_column_content', 1, 2 );
function admin_orders_list_column_content( $column, $post_id ){
global $the_order, $post;
if ('custom_column' === $column) {
// Start list
echo '<ul >';
// Loop through order items
foreach($the_order->get_items() as $item) {
$product = $item->get_product();
$img = wp_get_attachment_url($product->get_image_id());
if(file_exists($img)){
$img = wp_get_attachment_url($product->get_image_id());
}else{
echo 'texto2';
}
$name = $item->get_name();
$qty = $item->get_quantity();
echo "<li>
<img src=\"$img\" />
<label>$qty</label> $name
</li>";
}
// End list
echo '</ul>';
}
}
uj5u.com熱心網友回復:
wp_get_attachment_url() 將回傳帶有附件 URL 的字串,否則回傳 false。因此,您可以通過 if 條件添加額外的檢查。
然后你得到:
function action_manage_shop_order_posts_custom_column( $column, $post_id ) {
// Compare
if ( $column == 'custom_column' ) {
// Get order
$order = wc_get_order( $post_id );
// Is a WC_Order
if ( is_a( $order, 'WC_Order' ) ) {
// Start list
echo '<ul >';
// Loop through order items
foreach ( $order->get_items() as $item_key => $item ) {
// Get product
$product = $item->get_product();
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Getters
$image_id = $product->get_image_id();
$image = wp_get_attachment_url( $image_id );
$name = $item->get_name();
$qty = $item->get_quantity();
// NOT false
if ( $image ) {
$image_output = '<img src=' . $image . ' width="50" height="50">';
} else {
$image_output = __( 'Some text', 'woocommerce' );
}
// Output
echo '<li>' . $image_output . '<label>' . $qty . '</label>' . $name . '</li>';
} else {
// Output
echo '<li>' . __( 'N/A', 'woocommerce' ) . '</li>';
}
}
// End list
echo '</ul>';
}
}
}
add_action( 'manage_shop_order_posts_custom_column' , 'action_manage_shop_order_posts_custom_column', 10, 2 );
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/350041.html
標籤:php WordPress的 求购 后端 订单
