Añade un historial de stock a tus productos de WooCommerce

    Podrás consultar los diferentes movimientos de inventario en la ficha de producto.

    <?php
    /* Historial de stock de producto */
    add_action('woocommerce_product_before_set_stock', 'nwp_historial_stock_superior');
    add_action('woocommerce_variation_before_set_stock', 'nwp_historial_stock_superior');
    function nwp_historial_stock_superior($product)
    {
        $stock_history = get_post_meta($product->get_id() , '_stock_history', true) ? get_post_meta($product->get_id() , '_stock_history', true) : array();
        $stock_history[time() ] = (int)get_post_meta($product->get_id() , '_stock', true);
        update_post_meta($product->get_id() , '_stock_history', $stock_history);
    }
    add_action('add_meta_boxes', 'nwp_caja_meta_historial_stock');
    function nwp_caja_meta_historial_stock()
    {
        add_meta_box('stock_history', 'Historial de inventario', 'nwp_mostrar_historial_stock', 'product', 'advanced', 'high');
    }
    function nwp_mostrar_historial_stock()
    {
        global $post;
        $product = wc_get_product($post->ID);
        if ($product->get_type() == 'variable')
        {
            foreach ($product->get_available_variations() as $key)
            {
                $products[] = $key['variation_id'];
            }
        }
        else $products[] = $post->ID;
        foreach ($products as $product_id)
        {
            $product = wc_get_product($product_id);
            echo '<h3>' . $product->get_name() . '</h3>';
            $stock_history = get_post_meta($product_id, '_stock_history', true);
            if ($stock_history)
            {
                foreach ($stock_history as $timestamp => $stockvalue)
                {
                    if (!$stockvalue) continue;
                    echo '<p>' . date(DATE_COOKIE, $timestamp) . ': <b>' . $stockvalue . '</b></p>';
                }
            };
            echo '<p>Existencias actuales: <b>' . $product->get_stock_quantity() . '</b></p>';
        }
    }

    Herramientas relacionadas

    • WooCommerce

      El plugin para crear tiendas online por excelencia. Tanto de productos físicos como digitales. Es la base para prácticamente cualquier proyecto web que acepte pagos online.