As WooCommerce doesn't show product images on the order page I created a PHP function to add new columns and to show all the details i need, but i am getting some problems.
When one of the products from old orders is deleted, the order appears with error because that image/product does not exist and give me back critical error.
Can someone give me a possible solution to this case?
I need to tell wordpress "if this image/product doesn't exist or is empty it shows some text"
// 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>';
}
}
CodePudding user response:
wp_get_attachment_url() will return a string with the attachment URL, otherwise false. So can you add an extra check via an if condition.
Then you get:
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 );