productdetailcategorylabel

<!-- category above product detail title @tuanphan -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function() {
    console.log('jQuery ready - using AJAX method with cache');
    
    const CACHE_KEY_PREFIX = 'product_category_';
    const CACHE_EXPIRY = 3600000; // 1 hour
    
    // Cache manager
    const cacheManager = {
        get: function(key) {
            try {
                const cached = localStorage.getItem(key);
                if (!cached) return null;
                
                const data = JSON.parse(cached);
                if (Date.now() > data.expiry) {
                    localStorage.removeItem(key);
                    return null;
                }
                return data.value;
            } catch (e) {
                console.warn('Cache read failed:', e);
                return null;
            }
        },
        set: function(key, value) {
            try {
                const data = {
                    value: value,
                    expiry: Date.now() + CACHE_EXPIRY
                };
                localStorage.setItem(key, JSON.stringify(data));
            } catch (e) {
                console.warn('Cache storage failed:', e);
            }
        }
    };
    
    function insertCategories() {
        if ($('.product-categories').length > 0) {
            console.log('Categories already exist');
            return;
        }
        
        const $titleElement = $('h1.product-title');
        console.log('Title element found:', $titleElement.length);
        
        if ($titleElement.length === 0) {
            console.log('No title element found');
            return;
        }
        
        var pathname = window.location.pathname;
        const cacheKey = CACHE_KEY_PREFIX + pathname;
        
        // Check cache first
        const cachedData = cacheManager.get(cacheKey);
        if (cachedData) {
            console.log('Using cached data');
            renderCategories(cachedData, $titleElement);
            return;
        }
        
        console.log('Fetching data from:', pathname + "?format=json-pretty");
        
        jQuery.ajax({
            url: pathname + "?format=json-pretty",
            dataType: "json",
            cache: false,
            timeout: 10000, // 10 second timeout
            success: function (data) {
                console.log('AJAX success - got data:', data);
                
                // Save to cache
                cacheManager.set(cacheKey, data);
                
                renderCategories(data, $titleElement);
            },
            error: function(xhr, status, error) {
                console.log('AJAX error:', status, error);
                
                // Retry once after 1 second if failed
                if (!this.retried) {
                    console.log('Retrying in 1 second...');
                    setTimeout(function() {
                        jQuery.ajax({
                            ...arguments[0],
                            retried: true
                        });
                    }, 1000);
                }
            }
        });
    }
    
    function renderCategories(data, $titleElement) {
        const item = data.item;
        const nestedCategories = data.nestedCategories;
        
        console.log('Item:', item);
        console.log('Category IDs:', item ? item.categoryIds : 'No item');
        console.log('Nested categories:', nestedCategories);
        
        if (!item || !item.categoryIds || !nestedCategories || !nestedCategories.itemCategories) {
            console.log('Missing required data');
            return;
        }
        
        const $categoriesContainer = $('<div class="product-categories"></div>');
        
        item.categoryIds.forEach(function(categoryId) {
            const category = nestedCategories.itemCategories.find(function(cat) {
                return cat.id === categoryId;
            });
            
            if (category) {
                console.log('Adding category:', category.displayName);
                const $categoryLink = $('<a class="product-category-link"></a>')
                    .attr('href', category.fullUrl)
                    .text(category.displayName);
                
                $categoriesContainer.append($categoryLink);
            }
        });
        
        if ($categoriesContainer.children().length > 0) {
            $titleElement.before($categoriesContainer);
            console.log('Categories inserted successfully');
        } else {
            console.log('No categories to insert');
        }
    }
    
    insertCategories();
});
</script>
<style>
a.product-category-link {
    border: 1px solid #000;
    padding: 10px 20px;
    margin-right: 10px;
    border-radius: 50px;
}
</style>

 

Buy me a coffee