Fixes missing cart image by adjusting script enqueue and adding MutationObserver to handle dynamically rendered book wrappers

This commit is contained in:
Jonathan Rosenbaum 2026-01-20 02:52:52 +00:00
parent d4978a7122
commit 6fe38f323c
2 changed files with 60 additions and 24 deletions

View File

@ -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;
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 = `<a class="shop_link" href="https://cdcshoppingcart.uchicago.edu/Cart2/ChicagoBook?ISBN=${isbn}&PRESS=wvp" target="_blank">
shopLink.innerHTML = `
<a class="shop_link" href="https://cdcshoppingcart.uchicago.edu/Cart2/ChicagoBook?ISBN=${isbn}&PRESS=wvp" target="_blank">
<img src="${imageUrl}" alt="Shop Link">
</a>`;
</a>
`;
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

View File

@ -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__) . '";' );
// 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;