Skip to content

Instantly share code, notes, and snippets.

@WpComet
Last active February 11, 2024 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WpComet/19e370872d50ad82efab5a228fbb5ef3 to your computer and use it in GitHub Desktop.
Save WpComet/19e370872d50ad82efab5a228fbb5ef3 to your computer and use it in GitHub Desktop.
Convert woocommerce catalog ordering from dropdown to buttons
document.addEventListener('DOMContentLoaded', function () {
// Check if we're on a product category archive page
if (document.body.classList.contains('archive') && document.body.classList.contains('woocommerce')) {
// Get a reference to the select element
const sortingSelect = document.querySelector('.woocommerce-ordering select');
// Hide the default select box
sortingSelect.style.display = 'none';
// Create a new div for the sorting buttons
const customSortingContainer = document.createElement('div');
customSortingContainer.classList.add('custom-sorting-container'); // Add your desired class name
// Append the new div after the select element
sortingSelect.parentNode.insertBefore(customSortingContainer, sortingSelect.nextSibling);
// Define the sorting labels
const sortingLabels = {
'price': 'Fiyat artan',
'price-desc': 'Fiyat Azalan',
'popularity': 'En Popüler',
'rating': 'Yüksek puan',
'date': 'En yeni',
'menu_order': 'Varsayılan',
// Add more labels for other sorting options as needed
};
// Create buttons for each sorting option
sortingSelect.querySelectorAll('option').forEach(option => {
if (option.value) {
//const button = document.createElement('button');
const button = document.createElement('a');
button.classList.add('elementor-button', 'elementor-button-link', 'elementor-size-xs');
button.textContent = sortingLabels[option.value] || option.text; // Use the custom label or fallback to original text
button.href = window.location.pathname + '?orderby=' + option.value;
button.dataset.value = option.value;
// Handle button click (customize this logic)
button.addEventListener('click', () => {
const selectedValue = button.dataset.value;
const currentUrl = new URL(window.location.href);
currentUrl.searchParams.set('orderby', selectedValue);
window.location.href = currentUrl.toString();
});
// Check if the current URL matches the sorting option
if (window.location.search.includes('orderby=' + option.value)) {
button.classList.add('active');
}
// Wrap the button with the specified div
const buttonWrapper = document.createElement('div');
buttonWrapper.classList.add('elementor-button-wrapper');
buttonWrapper.appendChild(button);
// Append the wrapped button to the custom container
customSortingContainer.appendChild(buttonWrapper);
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment