Created
November 5, 2024 17:59
-
-
Save mindbreaker/db9f8b4c19dc54d3e41a2916d077a525 to your computer and use it in GitHub Desktop.
find-cards-woocommerce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Conversion rate from USD to EUR | |
| const usdToEurRate = 1.09; | |
| // Function to fetch and display prices for each product | |
| async function fetchAndDisplayPrices(productTitle, priceContainer) { | |
| // Define the API endpoint with the product title in the search parameter | |
| const apiEndpoint = `https://findstar-api-zegtz.ondigitalocean.app/api/search/1?key=${encodeURIComponent(productTitle)}&country_code=null&limit=50&page=0&filters=%7B%22region%22:%22Europe%22,%22price%22:%7B%22from%22:null,%22to%22:null%7D%7D`; | |
| try { | |
| const response = await fetch(apiEndpoint); | |
| const data = await response.json(); | |
| // Check if data contains the required fields | |
| if (data && data.search_stats) { | |
| const { min_price, avg_price, max_price } = data.search_stats; | |
| // Convert USD to EUR | |
| const minPriceEur = (min_price / usdToEurRate).toFixed(2); | |
| const avgPriceEur = (avg_price / usdToEurRate).toFixed(2); | |
| const maxPriceEur = (max_price / usdToEurRate).toFixed(2); | |
| // Create a new element to display the prices | |
| const priceInfo = document.createElement("div"); | |
| priceInfo.innerHTML = ` | |
| <p>Minimum Price: €${minPriceEur}</p> | |
| <p>Average Price: €${avgPriceEur}</p> | |
| <p>Maximum Price: €${maxPriceEur}</p> | |
| `; | |
| // Append the price info below the current price | |
| priceContainer.insertAdjacentElement("afterend", priceInfo); | |
| } else { | |
| console.error("Price data is not available for", productTitle); | |
| } | |
| } catch (error) { | |
| console.error("Error fetching price data for", productTitle, ":", error); | |
| } | |
| } | |
| // Loop through all h2 elements with class woocommerce-loop-product__title | |
| document.querySelectorAll("h2.woocommerce-loop-product__title").forEach((titleElement) => { | |
| const productTitle = titleElement.textContent; | |
| const priceContainer = titleElement.nextElementSibling.querySelector(".woocommerce-Price-amount"); | |
| // Fetch and display prices for each product | |
| if (priceContainer) { | |
| fetchAndDisplayPrices(productTitle, priceContainer); | |
| } | |
| }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment