Wordpress

Woocommerce Shopping Cart CSV, XML & Excel Export (5 Steps)

Woocommerce Shopping Cart CSV, XML & Excel Export (5 Steps)

Merhaba arkadaşlar, bu yazımızda Woocommerce alışveriş sepetindeki ürünleri CSV, XML ve Excel formatında dışarı nasıl aktarılır. (Woocommerce Shopping Cart CSV, XML & Excel Export). Tüm kodlar için github profilimi ziyaret edin. github.com/gencyazilimcim/Woocommerce-Shopping-Cart-CSV-Export. İyi okumalar

Woocommerce alışveriş sepetini CSV dosyası olarak dışa aktarmak için kodları Görünüm > Tema düzenleyici > function.php sayfasının en alt satırına aşağıdaki kodları adımları takip ederek işlemi tamamlayabilirsiniz.

wordpress görünüm tema düzenleyici funciton php

Adım 1: Sepet Sayfasına Konumlandırma

Sepet sayfasında indirme butonunu konumlandırma için aşağıdaki kodu kullanıyoruz. Farklı yerlere konumlandırma için businessbloomer.com/woocommerce-visual-hook-guide-cart-page/ sayfasını ziyaret edin.

add_action( 'woocommerce_after_cart_totals', 'cart2csv' );
function cart2csv(){
    echo '<button id="cartDownload" class="button alt">Download as CSV</button>';
}
Woocommerce Shopping Cart CSV, XML and Excel Export

Adım 2: Sepetteki Ürün Öğelerini Çek

Woocommerce alışveriş sepetine eklenen ürün öğelerini çekmek için aşağıdaki kodu kullanıyoruz.
Farklı sepet öğelerini çekmek için businessbloomer.com/woocommerce-get-cart-info-total-items-etc-from-cart-object/ sitesini ziyaret edin

add_action('woocommerce_after_cart_totals', 'cart2csv');

function cart2csv()
 {
    echo '<button id="cartDownload" class="button alt">Download as CSV</button>';

    $csvList = array("Product Name", "SKU", "Price", "Quantity", "Subtotal"); // CSV header

    foreach (WC()->cart->get_cart() as $cart_item) {
        $product            = $cart_item['data']; // ürün nesnesi

        $regular_price      = $product->get_regular_price(); // normal fiyat
        $sale_price         = $product->get_sale_price(); //indirimli fiyat
        $price              = $product->get_price(); // son fiyat
        $sku                = $product->get_sku(); // stok kodu
        $name               = $product->get_name(); // ürün ismi
        $quantity           = $cart_item['quantity']; // sipariş adedi
        $line_subtotal      = $cart_item['line_subtotal'];  // ara toplam
        array_push($csvList, $name, $sku, $price, $quantity, $line_subtotal); //diziyi gruplandır.
    }

    $arr = array_chunk($csvList, 5);
    $jsArray = json_encode($arr);
}

Adım 3: Diziyi Boyutlandırma

Burada ki amaç alışveriş sepetindeki verilerin bir boyutlu dizi (One-Dimensional Array) olmasından dolayı bu diziyi iki boyutlu (two-dimensional array) dönüştürmemiz gerekmektedir.

$arr = array(
    "Product Name 1", "Stock Code 1", "Price 1", "Quantity 1", "Subtotal 1",
    "Product Name 2", "Stock Code 2", "Price 2", "Quantity 2", "Subtotal 2",
    "Product Name 3", "Stock Code 3", "Price 3", "Quantity 3", "Subtotal 3"
);

$newList = array_chunk($arr, 5);  // $arr dizisini 5'erli grup yap (array_chunk)

print_r($newList);
One-Dimensional Array to Two-Dimensional Array
One-Dimensional Array to Two-Dimensional Array

Adım 4: Javascript İndirme Dosyası Oluşturma

Alışveriş sepetindeki verileri farklı dosya formatlarına aktarmak için Javascript kullandım çünkü PHP kullandığınızda sayfanın bütünün almaktadır. Bunun yerine javascript kullanarak sadece ilgili verileri alabilirsiniz ve PHP’ye göre daha hızlı.

CSV dönüştürme

Ben genel olarak CSV’ye dönüştürmeyi tercih ediyorum çünkü e-ticaret (Toptan satış yapanlar için) sitelerinin genelinde CSV kullanılıyor.

<script>
    // Example data given in question text
    var data = [
        ['Product Name 1', 'Stock Code 1', 'Price 1', 'Quantity 1', 'Subtotal 1'],
        ['Product Name 2', 'Stock Code 2', 'Price 2', 'Quantity 2', 'Subtotal 2'],
    ];

    // Building the CSV from the Data two-dimensional array
    // Each column is separated by ";" and new line "\n" for next row
    var csvContent = '';
    data.forEach(function (infoArray, index) {
        dataString = infoArray.join(';');
        csvContent += index < data.length ? dataString + '\n' : dataString;
    });

    // The download function takes a CSV string, the filename and mimeType as parameters
    // Scroll/look down at the bottom of this snippet to see how download is called
    var download = function (content, fileName, mimeType) {
        var a = document.createElement('a');
        mimeType = mimeType || 'application/octet-stream';

        if (navigator.msSaveBlob) {
            // IE10
            navigator.msSaveBlob(
                new Blob(["\uFEFF"+content], {
                    type: mimeType,
                }),
                fileName,
            );
        } else if (URL && 'download' in a) {
            //html5 A[download]
            a.href = URL.createObjectURL(
                new Blob(["\uFEFF"+content], {
                    type: mimeType,
                }),
            );
            a.setAttribute('download', fileName);
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        } else {
            location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
        }
    };

    //download button click
    const downloadClick = document.getElementById('cartDownload');
    downloadClick.addEventListener('click', () => {
        download(csvContent, 'cart-dowload.csv', 'text/csv;encoding:utf-8');
    }, false);
</script>

Source for converting javascript array to CSV: stackoverflow.com/a/29304414/12118468

Diğer Formatlar için

Alışveriş sepetinizdeki ürünleri farklı formatlarda indimek istiyorsanız (örn: XML, CSV EXCEL, HTML, CSS, Text, JSON gibi) aşağıdaki javascript kodunu deneyebilirsiniz.

<script src="https://unpkg.com/export-from-json@1.7.0/dist/umd/index.min.js"></script>
<script>
    var data = [
        ['Product Name 1', 'Stock Code 1', 'Price 1', 'Quantity 1', 'Subtotal 1'],
        ['Product Name 2', 'Stock Code 2', 'Price 2', 'Quantity 2', 'Subtotal 2'],
    ];
    //Format: txt, json, csv, xls, xml, html, css
    function download(exportType, fileName) {
        (exportType == "txt") ? data = JSON.stringify(data) : "";
        window.exportFromJSON({ data, fileName, exportType });
    }
    const downloadClick = document.getElementById("cartDownload");
    downloadClick.addEventListener("click", () => {
        download("txt", "text olarak indir");
    }, false);
</script>

Adım 5: Sonuç

Sonuç olarak bütün adımların toparlanmış hali için aşağıya bıraktım.

<?php
add_action('woocommerce_after_cart_totals', 'cart2csv');

function cart2csv() {
    echo '<button id="cartDownload" class="button alt">Download as CSV</button>';

    $csvList = array("Product Name", " SKU", "Price", "Quantity", "Subtotal");

    foreach (WC()->cart->get_cart() as $cart_item) {
        // gets the product object
        $product            = $cart_item['data'];
        // gets the product prices
        $regular_price      = $product->get_regular_price();
        $sale_price         = $product->get_sale_price();
        $price              = $product->get_price();
        $sku                = $product->get_sku();
        $name               = $product->get_name();
        $quantity           = $cart_item['quantity'];
        $line_subtotal      = $cart_item['line_subtotal'];
        array_push($csvList, $name, $sku, $price, $quantity, $line_subtotal);
    }

    $arr = array_chunk($csvList, 5);
    $jsArray = json_encode($arr);
?>
    <script>
        var data = <?= $jsArray  ?>; // Cart list

        // Building the CSV from the Data two-dimensional array
        // Each column is separated by ";" and new line "\n" for next row
        var csvContent = '';
        data.forEach(function(infoArray, index) {
            dataString = infoArray.join(';');
            csvContent += index < data.length ? dataString + '\n' : dataString;
        });

        // The download function takes a CSV string, the filename and mimeType as parameters
        // Scroll/look down at the bottom of this snippet to see how download is called
        var download = function(content, fileName, mimeType) {
            var a = document.createElement('a');
            mimeType = mimeType || 'application/octet-stream';

            if (navigator.msSaveBlob) { // IE10
                navigator.msSaveBlob(new Blob([content], {
                    type: mimeType
                }), fileName);
            } else if (URL && 'download' in a) { //html5 A[download]
                a.href = URL.createObjectURL(new Blob([content], {
                    type: mimeType
                }));
                a.setAttribute('download', fileName);
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            } else {
                location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
            }
        }

        const downloadClick = document.getElementById("cartDownload");

        downloadClick.addEventListener("click", () => {
            download(csvContent, 'cart-dowload.csv', 'text/csv;encoding:utf-8');
        });
    </script>
<?php
}

Değerli takipçilerim yazımızda hata veya önerileriniz olursa lütfen yorum yapmayı unutmayın.
Unutmayın! Paylaşmak; kazanmanın en hızlı ve kolay yoludur. Bir sonraki makalede görüşmek dileğiyle esen kalın.

Bu makale yardımcı oldu mu?
EvetHayır

Paylaş

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir