مقایسه محصول

ایجاد سیستم مقایسه محصولات ووکامرس با ذخیره محصولات انتخاب‌شده در کوکی، نمایش مشخصات محصولات در جدول و امکان حذف محصولات از لیست مقایسه.

این کد یک سیستم مقایسه محصولات ووکامرس ایجاد می‌کند که به کاربران اجازه می‌دهد چند محصول را به لیست مقایسه اضافه کرده و مشخصات آن‌ها را در کنار یکدیگر مشاهده کنند.

محصولات انتخاب‌شده در کوکی مرورگر ذخیره می‌شوند و در صفحه مقایسه، اطلاعاتی مانند تصویر، نام، قیمت، موجودی و ویژگی‌های محصول به‌صورت جدولی نمایش داده می‌شود. کاربر می‌تواند هر محصول را به‌صورت جداگانه یا همه محصولات را یکجا از لیست مقایسه حذف کند.

برای ایجاد صفحه مقایسه، یک برگه با اسلاگ زیر بسازید:

compare

سپس شورت‌کد زیر را داخل آن قرار دهید:

[woocommerce_compare]

همچنین برای نمایش دکمه افزودن محصول به مقایسه می‌توانید از شورت‌کد زیر استفاده کنید:

[compare_button]

برای مقایسه یک محصول مشخص نیز می‌توانید شناسه محصول را تعیین کنید:

[compare_button id=”123″]

و برای تغییر متن دکمه:

[compare_button id=”123″ text=”مقایسه این محصول”]


<?php
if ( ! defined( 'ABSPATH' ) ) exit;
function gap_set_compare_cookie($value, $expire) {
    $secure = is_ssl();
    if (PHP_VERSION_ID >= 70300) {
        setcookie('gap_compare_products', $value, [
            'expires'  => $expire,
            'path'     => '/',
            'domain'   => '',
            'secure'   => $secure,
            'httponly' => false,
            'samesite' => 'Lax',
        ]);
    } else {
        setcookie(
            'gap_compare_products',
            $value,
            $expire,
            '/; samesite=Lax',
            '',
            $secure,
            false
        );
    }
    $_COOKIE['gap_compare_products'] = $value;
}
add_action('wp_enqueue_scripts', 'gap_compare_system_assets');
function gap_compare_system_assets() {
    wp_register_style('gap-compare-style', false);
    wp_enqueue_style('gap-compare-style');
    wp_add_inline_style('gap-compare-style', "
        .compare-table-container {
            overflow-x: auto;
            margin: 10px 0;
            border: 1px solid #eee;
            box-shadow: 0 2px 12px rgba(0,0,0,0.04);
            background: #fff;
        }
        .compare-actions-bar {
            padding: 10px;
            display: flex;
        }
        .compare-clear-btn {
            color: #d9534f !important;
            font-size: 12px;
            text-decoration: none;
            border: 1px solid #d9534f;
            padding: 5px 10px;
            display: inline-block;
            cursor: pointer;
            transition: all 0.3s;
        }
        .compare-clear-btn:hover {
            background: #d9534f;
            color: #fff !important;
        }
        table.gap-compare-table {
            width: 100%;
            border-collapse: collapse;
            background: #fff;
            font-size: 13px;
            direction: rtl;
            line-height: 1.5;
            margin: 0 !important;
        }
        table.gap-compare-table th,
        table.gap-compare-table td {
            border-bottom: 1px solid #f2f2f2;
            border-left: 1px solid #f2f2f2;
            padding: 10px 8px;
            text-align: center;
            min-width: 150px;
            vertical-align: middle;
        }
        table.gap-compare-table thead th {
            background: #fafafa;
            position: sticky;
            top: 0;
            z-index: 10;
            border-bottom: 2px solid #eee;
        }
table.gap-compare-table thead th:first-child,
table.gap-compare-table tbody td:first-child {
    background: #f9f9f9;
    font-weight: 600;
    width: 60px;
    min-width: 60px;
    max-width: 60px;
    position: sticky;
    right: 0;
    z-index: 11;
    color: #555;
    border-left: 2px solid #eee;
    padding: 8px 4px;
    white-space: nowrap;
    font-size: 12px;
}
        .compare-img-wrapper {
            width: 80px;
            height: 80px;
            margin: 0 auto 8px;
            border: 1px solid #f0f0f0;
            background: #fff;
            padding: 4px;
        }
        .compare-img-wrapper img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
        .compare-product-title {
            font-size: 12px;
            font-weight: bold;
            display: block;
            margin-bottom: 4px;
            color: #222;
        }
        .compare-remove-item {
            color: #cc0000;
            font-size: 10px;
            cursor: pointer;
            opacity: 0.6;
            text-decoration: none;
            display: block;
            margin-top: 5px;
        }
        .compare-remove-item:hover {
            opacity: 1;
        }
        .compare-price {
            font-size: 14px;
            font-weight: 800;
            color: #000;
        }
        .compare-stock-in {
            color: #27ae60;
        }
        .compare-stock-out {
            color: #e74c3c;
        }
        .gap-compare-btn {
            font-size: 12px !important;
            padding: 8px 12px !important;
            margin: 0 !important;
        }
        .gap-compare-btn.added {
            background-color: #333 !important;
            color: #fff !important;
        }
        .gap-compare-action-btn,
        .gap-compare-table .add_to_cart_button,
        .gap-compare-table .product_type_simple,
        .gap-compare-table .product_type_variable,
        .gap-compare-table .single_add_to_cart_button {
            font-size: 11px !important;
            padding: 7px 12px !important;
            line-height: 1.4;
            display: inline-block;
            text-decoration: none;
        }
    ");
    wp_register_script('gap-compare-js', '', ['jquery'], '', true);
    wp_enqueue_script('gap-compare-js');
    wp_localize_script('gap-compare-js', 'gapVars', [
        'url' => home_url('/compare/')
    ]);
    wp_add_inline_script('gap-compare-js', "
        jQuery(document).ready(function($) {
            function getC(name) {
                let match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
                return match ? decodeURIComponent(match[1]) : '';
            }
            function setC(name, value) {
                let d = new Date();
                d.setTime(d.getTime() + (7 * 24 * 60 * 60 * 1000));
                document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + d.toUTCString() + '; path=/; SameSite=Lax';
            }
            function getIds() {
                return getC('gap_compare_products').split(',').filter(Boolean);
            }
            function updateBtn() {
                let ids = getIds();
                $('.gap-compare-btn').each(function() {
                    let pid = $(this).data('product-id');
                    if(pid) {
                        let pidStr = pid.toString();
                        if (ids.includes(pidStr)) {
                            $(this)
                                .addClass('added')
                                .text('مشاهده مقایسه')
                                .attr('href', gapVars.url);
                        } else {
                            $(this)
                                .removeClass('added')
                                .text('افزودن به مقایسه')
                                .attr('href', '#');
                        }
                    }
                });
            }
            updateBtn();
            $(document).on('click', '.gap-compare-btn', function(e) {
                if ($(this).hasClass('added')) {
                    return true; 
                }
                e.preventDefault();
                let id = $(this).data('product-id').toString();
                let ids = getIds();
                if (!ids.includes(id)) {
                    ids.push(id);
                    setC('gap_compare_products', ids.join(','));
                }
                updateBtn();
            });
            $(document).on('click', '.compare-remove-item', function(e) {
                e.preventDefault();
                let id = $(this).data('product-id').toString();
                let index = $(this).closest('th').index();
                let ids = getIds();
                let newIds = ids.filter(item => item !== id);
                if (newIds.length > 0) {
                    setC('gap_compare_products', newIds.join(','));
                } else {
                    document.cookie = 'gap_compare_products=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax';
                }
                $('.gap-compare-table tr').each(function() {
                    $(this).find('td, th').eq(index).fadeOut(300, function() {
                        $(this).remove();
                    });
                });
                if (newIds.length === 0) {
                    setTimeout(function() {
                        $('.compare-table-container').fadeOut(300, function() {
                            $(this).after('<div class=\"compare-empty-msg\" style=\"text-align:center;padding:50px;color:#999;\">لیست مقایسه شما خالی است.</div>').remove();
                        });
                    }, 300);
                }
                setTimeout(function() {
                    updateBtn();
                }, 350);
            });
            $(document).on('click', '.compare-clear-btn', function(e) {
                e.preventDefault();

                if (!confirm('آیا مطمئن هستید؟')) {
                    return false;
                }
                document.cookie = 'gap_compare_products=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax';
                $('.compare-table-container').fadeOut(300, function() {
                    $(this).after('<div class=\"compare-empty-msg\" style=\"text-align:center;padding:50px;color:#999;\">لیست مقایسه شما خالی است.</div>').remove();
                });
                setTimeout(function() {
                    updateBtn();
                }, 350);
            });
        });
    ");
}

add_action('woocommerce_single_product_summary', 'gap_render_btn', 35);
function gap_render_btn() {
    global $product;
    if (!$product) return;
    echo '<a href="#" class="button gap-compare-btn" data-product-id="' . esc_attr($product->get_id()) . '">افزودن به مقایسه</a>';
}
add_shortcode('compare_button', 'gap_compare_button_shortcode');
function gap_compare_button_shortcode($atts) {
    $atts = shortcode_atts([
        'id'   => get_the_ID(),
        'text' => 'افزودن به مقایسه'
    ], $atts, 'compare_button');
    $product_id  = intval($atts['id']);
    $button_text = sanitize_text_field($atts['text']);
    if (!$product_id) return '';
    $product = wc_get_product($product_id);
    if (!$product) return '';
    ob_start();
    ?>
    <a href="#" class="button gap-compare-btn" data-product-id="<?php echo esc_attr($product_id); ?>">
        <?php echo esc_html($button_text); ?>
    </a>
    <?php
    return ob_get_clean();
}
function gap_get_compare_action_button($product) {
    if (!$product || !is_a($product, 'WC_Product')) {
        return '—';
    }
    if ($product->is_type('variable')) {
        return sprintf(
            '<a href="%s" class="button gap-compare-action-btn">%s</a>',
            esc_url(get_permalink($product->get_id())),
            esc_html__('انتخاب گزینه‌ها', 'woocommerce')
        );
    }
    if (!$product->is_purchasable()) {
        return sprintf(
            '<a href="%s" class="button gap-compare-action-btn">%s</a>',
            esc_url(get_permalink($product->get_id())),
            esc_html__('مشاهده محصول', 'woocommerce')
        );
    }
    if (!$product->is_in_stock()) {
        return sprintf(
            '<a href="%s" class="button gap-compare-action-btn">%s</a>',
            esc_url(get_permalink($product->get_id())),
            esc_html__('اطلاعات بیشتر', 'woocommerce')
        );
    }
    return sprintf(
        '<a href="%s" data-quantity="1" class="%s" %s>%s</a>',
        esc_url($product->add_to_cart_url()),
        esc_attr(implode(' ', array_filter([
            'button',
            'product_type_' . $product->get_type(),
            $product->supports('ajax_add_to_cart') ? 'add_to_cart_button ajax_add_to_cart' : ''
        ]))),
        wc_implode_html_attributes([
            'data-product_id' => $product->get_id(),
            'data-product_sku' => $product->get_sku(),
            'aria-label' => $product->add_to_cart_description(),
            'rel' => 'nofollow'
        ]),
        esc_html($product->add_to_cart_text())
    );
}
add_shortcode('woocommerce_compare', 'gap_render_compare_page');
function gap_render_compare_page() {
    $cookie_data = isset($_COOKIE['gap_compare_products'])
        ? sanitize_text_field(wp_unslash($_COOKIE['gap_compare_products']))
        : '';
    if (empty($cookie_data)) {
        return '<div class="compare-empty-msg" style="text-align:center;padding:50px;color:#999;">لیست مقایسه شما خالی است.</div>';
    }
    $ids = array_filter(array_map('intval', explode(',', $cookie_data)));
    $ids = array_unique($ids);
    $products = [];
    $attributes_map = [];
    foreach ($ids as $id) {
        $p = wc_get_product($id);

        if ($p) {
            $products[] = $p;

            foreach ($p->get_attributes() as $slug => $attr) {
                $attributes_map[$slug] = wc_attribute_label($slug);
            }
        }
    }
    if (empty($products)) {
        return '<div class="compare-empty-msg" style="text-align:center;padding:50px;color:#999;">محصولی برای مقایسه یافت نشد.</div>';
    }
    ob_start();
    ?>
    <div class="compare-table-container">
        <div class="compare-actions-bar">
            <a href="#" class="compare-clear-btn">حذف همه محصولات</a>
        </div>
        <table class="gap-compare-table">
            <thead>
                <tr>
                    <th>ویژگی‌ها</th>
                    <?php foreach ($products as $p) : ?>
                        <th>
                            <div class="compare-img-wrapper"><?php echo $p->get_image('thumbnail'); ?></div>
                            <span class="compare-product-title"><?php echo esc_html($p->get_name()); ?></span>
                            <a href="#" class="compare-remove-item" data-product-id="<?php echo esc_attr($p->get_id()); ?>">حذف</a>
                        </th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>قیمت</td>
                    <?php foreach ($products as $p) : ?>
                        <td class="compare-price"><?php echo wp_kses_post($p->get_price_html() ?: '—'); ?></td>
                    <?php endforeach; ?>
                </tr>
                <tr>
                    <td>موجودی</td>
                    <?php foreach ($products as $p) : ?>
                        <td>
                            <?php echo $p->is_in_stock()
                                ? '<span class="compare-stock-in">موجود</span>'
                                : '<span class="compare-stock-out">ناموجود</span>'; ?>
                        </td>
                    <?php endforeach; ?>
                </tr>
                <?php foreach ($attributes_map as $slug => $label) : ?>
                    <tr>
                        <td><?php echo esc_html($label); ?></td>
                        <?php foreach ($products as $p) : ?>
                            <?php $val = $p->get_attribute($slug); ?>
                            <td><?php echo !empty($val) ? esc_html($val) : '—'; ?></td>
                        <?php endforeach; ?>
                    </tr>
                <?php endforeach; ?>
                <tr>
                    <td>عملیات</td>
                    <?php foreach ($products as $p) : ?>
                        <td><?php echo wp_kses_post(gap_get_compare_action_button($p)); ?></td>
                    <?php endforeach; ?>
                </tr>
            </tbody>
        </table>
    </div>
    <?php
    return ob_get_clean();
}

روش اول: فایل functions.php

اگر از قالب فرزند (Child Theme) استفاده می‌کنید، می‌توانید کد را در فایل: functions.php قالب فرزند قرار دهید.

توصیه می‌شود کد را مستقیماً در فایل functions.php قالب اصلی قرار ندهید؛ زیرا با به‌روزرسانی قالب ممکن است تغییرات شما از بین برود.

روش دوم: استفاده از افزونه Code Snippets

روش ساده‌تر این است که از افزونه‌های مدیریت Snippet استفاده کنید.

در این روش، کد را به‌عنوان یک Snippet جدید اضافه کرده و آن را فعال می‌کنید.

مزیت این روش این است که برای اضافه کردن کدهای PHP نیازی به ویرایش مستقیم فایل‌های قالب ندارید.

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *