diff --git a/js/search_shop_link.js b/js/search_shop_link.js index 13dd97c..1f8d074 100644 --- a/js/search_shop_link.js +++ b/js/search_shop_link.js @@ -1,23 +1,46 @@ -(function waitForBookWrappers(imageUrl) { - const interval = setInterval(() => { - const bookWrappers = document.querySelectorAll(".book-wrapper"); - if (bookWrappers.length === 0) return; +function addShopLinks(imageUrl) { + document.querySelectorAll(".book-wrapper").forEach(wrapper => { + if (wrapper.querySelector(".shop_link")) return; - bookWrappers.forEach(wrapper => { - const coverLink = wrapper.querySelector(".sp__the-cover a"); - if (!coverLink || wrapper.querySelector(".shop_link")) return; + const coverLink = wrapper.querySelector(".sp__the-cover a"); + if (!coverLink) return; - const hrefParts = coverLink.getAttribute("href").split("/"); - const isbn = hrefParts[1]; + const href = coverLink.getAttribute("href"); + const isbn = href.split("/")[1]; + if (!isbn) return; - const shopLink = document.createElement("p"); - shopLink.innerHTML = ` - Shop Link - `; + const shopLink = document.createElement("p"); + shopLink.innerHTML = ` + + Shop Link + + `; - wrapper.appendChild(shopLink); - }); + wrapper.appendChild(shopLink); + }); +} + +function waitForImageUrl(callback) { + if (window.SearchShopLinkData && window.SearchShopLinkData.imageUrl) { + callback(window.SearchShopLinkData.imageUrl); + } else { + setTimeout(() => waitForImageUrl(callback), 50); + } +} + +waitForImageUrl(function(imageUrl) { + + // Run once in case elements already exist + addShopLinks(imageUrl); + + // Watch for dynamically added book wrappers + const observer = new MutationObserver(() => { + addShopLinks(imageUrl); + }); + + observer.observe(document.body, { + childList: true, + subtree: true + }); +}); - clearInterval(interval); - }, 100); -})(window.searchShopLinkImageUrl); // Pass URL dynamically diff --git a/plugin.php b/plugin.php index c3271df..14e4e65 100644 --- a/plugin.php +++ b/plugin.php @@ -26,18 +26,31 @@ add_action('template_redirect', function() { }); - function enqueue_shop_links_script() { - if (is_singular()) { - wp_enqueue_script('search_shop_link',plugins_url('/js/search_shop_link.js', __FILE__)); - wp_add_inline_script( 'search_shop_link', 'window.searchShopLinkImageUrl = "' . plugins_url('assets/cart_add.png', __FILE__) . '";' ); - + if (is_singular()) { + + // 1. Enqueue your JS file + wp_enqueue_script( + 'search_shop_link', + plugins_url('js/search_shop_link.js', __FILE__), + [], + false, + true + ); + + // 2. Localize data for that script + wp_localize_script( + 'search_shop_link', + 'SearchShopLinkData', + [ + 'imageUrl' => plugins_url('assets/cart_add.png', __FILE__) + ] + ); } } add_action('wp_enqueue_scripts', 'enqueue_shop_links_script'); - function br_replace_book_wrapper($html) { if (strpos($html, 'product-details') === false) { return $html;