Advanced custom field in orders email and on order page (order history)

Question

I have a working code i will post it below. my problem is i have a custom field (stock_number) which i display in orders email and on orders page instead of the default woocommerce title. everything works fine but the problem arise when the product is deleted from the database normally if i am displaying the title even when the product is deleted the orders history will still show that product and title. but i am displaying custom field and when the product is not in the database then it gives an error in the orders page (orders History).

My question is how to make the below code that if the stock number is not available then display the title.

// Replace part number with stock number in the order email and in the orders page
add_filter( 'woocommerce_order_item_name', 'custom_order_item_name', 10, 2 );
function custom_order_item_name( $item_name, $item ) {

    // Get the WC_Product object (from order item)
    $product = $item->get_product();

    if( $stock_number = get_field('stock_number', $product->get_id()) ) {
       $item_name = '<p class="item-stck" style="margin:12px 0 0;">
        <strong>' . __( 'Stock ', 'woocommerce' ) . '# </strong>' . $stock_number . '</p>';
    }
    return $item_name;
}
0
, , Sam 3 years 2020-04-01T08:52:23-05:00 0 Answers 86 views 0

Leave an answer

Browse
Browse