Home > OS >  Change WooCommerce "In Stock" text for custom product type (pre-order)
Change WooCommerce "In Stock" text for custom product type (pre-order)

Time:09-09

A little bit of background - I'm currently using the Product Pre-Orders for WooCommerce plugin by VillaTheme. Overall it works well for my purposes except for this one thing.

I’d like to make a custom “in stock” message for products that have the product type “pre-order” box checked.

Currently I have implemented the below solution via php however it is cumbersome as it requires manually entering/updating the product ids. I should also mention that these are variable products.

function wcs_custom_get_availability( $availability, $_product ) { 
    $product_ids = array(3831, 3832);
    // custom 
    if (in_array( $_product->get_id(), $product_ids ) ) {
        $availability['availability'] = sprintf( __('Available for Pre-Order', 'woocommerce'), $_product->get_stock_quantity());
    }

    // Out of stock
    if ( ! $_product->is_in_stock() ) {
        $availability['availability'] = __('Out of Stock', 'woocommerce');
    }

    return $availability;
}

I would prefer a code solution that is able to automatically recognize when a product is designated as a pre-order item and update the “in stock” text accordingly.

Any updates you can make to my code to function as described are greatly appreciated.

Thanks in advance, Ryan

CodePudding user response:

You can use it like this:

/**
 * Change availability text.
 *
 * @param array      $availability  Availability data array.
 * @param WC_Product $_product      WC Product object.
 *
 * @return array.
 */
function wcs_custom_get_availability( $availability, $_product ) {
    $is_preorder = 'no';

    if ( $_product->is_type( 'variation' ) ) {
        $is_preorder = get_post_meta( $_product->get_id(), '_wpro_variable_is_preorder', true );
    } elseif ( $_product->is_type( 'variable' ) ) {
        $_variations     = $_product->get_available_variations();
        $_variations_ids = ! empty( $_variations ) ? wp_list_pluck( $_variations, 'variation_id' ) : array();
        if ( ! empty( $_variations_ids ) ) {
            $is_preorders = array_map(
                function( $id ) {
                    return wc_string_to_bool( get_post_meta( $id, '_wpro_variable_is_preorder', true ) );
                },
                $_variations_ids
            );
            $is_preorder  = in_array( true, $is_preorders, true ) ? 'yes' : 'no';
        }
    } else {
        $is_preorder = get_post_meta( $_product->get_id(), '_simple_preorder', true );
    }

    if ( wc_string_to_bool( $is_preorder ) ) {
        $availability['availability'] = __( 'Available for Pre-Order', 'woocommerce' );
    }

    return $availability;
}
add_action( 'woocommerce_get_availability', 'wcs_custom_get_availability', 20, 2 );
  • Related