Skip to content

Instantly share code, notes, and snippets.

@Niq1982
Created May 21, 2021 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Niq1982/5e7a8d5ad401b43130698ffaced4d618 to your computer and use it in GitHub Desktop.
Save Niq1982/5e7a8d5ad401b43130698ffaced4d618 to your computer and use it in GitHub Desktop.
Woocommerce: Show stock amounts for a product depending on the local and wholesale stock
<?php
/**
* Echo stock amounts for a product depending on the local and wholesale stock
* quantities and possibly add wholesale information.
*
* @param int $product_id Product ID (optional)
*/
function show_stock( $product_id = 0 ) {
$product_id = $product_id ? $product_id : get_the_ID();
// Bail out if we don't have product id
if ( ! $product_id ) {
return;
}
// Get the local and wholesale stock quantities and convert to integer
$stock = intval( get_post_meta( $product_id, '_stock', true ) );
$wholesale_stock = intval( get_post_meta( $product_id, 'wholesaleqty', true ) );
// Set the estimates if available for wholesale
$estimates = [
'Supplier 1' => '1-3',
'Supplier 2' => '4-6',
'Supplier 3' => '1-3',
];
// Prepare the string to be outputted
$output = '';
if ( 0 === $stock && $wholesale_stock ) {
// Set wholesale stock
if ( $wholesale_stock > 10 ) {
$output .= sprintf( esc_html__( 'Yli %s kpl maahantuojalla', 'my-text-domain' ), $wholesale_stock );
} else {
$output .= sprintf( esc_html__( '%s kpl maahantuojalla', 'my-text-domain' ), $wholesale_stock );
}
// Get estimate time by supplier if they have product in stock
$supplier = get_post_meta( $product_id, 'maahantuoja', true );
if ( $wholesale_stock && $supplier && ! empty( $estimates[ $supplier ] ) ) {
$output .= sprintf( esc_html__( '(arvio %s pv)', 'my-text-domain' ), $estimates[ $supplier ] );
}
} elseif ( $stock <= 3 ) {
$output .= sprintf( esc_html__( 'Vain %s kpl varastossa', 'my-text-domain' ), $stock );
} elseif ( $stock > 3 ) {
$output .= sprintf( esc_html__( '%s kpl varastossa', 'my-text-domain' ), $stock );
} else {
$output .= sprintf( esc_html__( '%s kpl jälkitoimituksessa', 'my-text-domain' ), $stock );
}
if ( ! empty( $output ) ) {
// Wrap output to div element
$output = '<div class="remaining">' . $output . '</div>';
// Escape and echo output
echo wp_kses_post( $output );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment