Tag Archives: WooCommerce

Fix "out of stock" products count on archives in WooCommerce

/**
 * fix_hide_out_of_stock_products.
 */
add_action( 'pre_get_posts', 'fix_hide_out_of_stock_products' );
function fix_hide_out_of_stock_products( $q ) {
	if ( ! $q->is_main_query() || is_admin() || ! $q->is_archive() ) {
		return;
	}
	$meta_query   = ( array ) $q->get( 'meta_query' );
	$meta_query[] = array(
		'key'       => '_stock_status',
		'value'     => 'outofstock',
		'compare'   => 'NOT IN'
	);
	$q->set( 'meta_query', $meta_query );
	remove_action( 'pre_get_posts', 'fix_hide_out_of_stock_products' );
}

Check if product is in cart by product ID in WooCommerce

if ( ! function_exists( 'is_product_in_cart' ) ) {
	/**
	 * is_product_in_cart.
	 *
	 * @return bool
	 */
	function is_product_in_cart( $product_id ) {
		if ( 0 != $product_id ) {
			if ( isset( WC()->cart->cart_contents ) && is_array( WC()->cart->cart_contents ) ) {
				foreach ( WC()->cart->cart_contents as $cart_item_key => $cart_item_data ) {
					if (
						( isset( $cart_item_data['product_id'] )   && $product_id == $cart_item_data['product_id'] ) ||
						( isset( $cart_item_data['variation_id'] ) && $product_id == $cart_item_data['variation_id'] )
					) {
						return true;
					}
				}
			}
		}
		return false;
	}
}