How to Replace Matching Links with Badges Without Editing Saved Content

a small, scoped JavaScript enhancement can turn selected text links into visual download badges without rewriting the content stored in WordPress.

Why it happens

The safest version keeps the original anchor element and changes only its visible contents. This preserves the destination URL, tracking attributes, list structure, and editor content.

The code below is illustrative; replace the sample store URL and badge asset before use. The selector must be narrow. Limit it to the article container and require the URL to begin with the expected store path. A prefix selector is safer than a broad substring search because unrelated links are less likely to match.

A practical pattern

  1. Wait until the document is ready.

  2. Select matching links only inside the post content.

  3. Skip any link that already contains an image.

  4. Create an image with useful alternative text.

  5. Replace the link text while keeping the original anchor.

document.addEventListener('DOMContentLoaded', () => {
  const selector =
    '.entry-content a[href^="https://store.example/apps/details"]';

  document.querySelectorAll(selector).forEach((link) => {
    if (link.querySelector('img')) {
      return;
    }

    const badge = document.createElement('img');
    badge.src = '/assets/download-badge.png';
    badge.alt = 'Download this app';
    badge.width = 135;
    badge.style.height = 'auto';

    link.replaceChildren(badge);
  });
});

Why this approach works

Problem: editing every saved post is slow and can introduce inconsistent markup.
Fix: enhance matching links when the page renders.

Problem: a loose selector can change unrelated links.
Fix: scope the selector to the content area and an exact URL prefix.

Problem: running the script twice can create duplicate badges.
Fix: skip anchors that already contain an image.

Common mistakes

  • Replacing the entire anchor, which can lose attributes or tracking data.
  • Using *= when a stricter ^= prefix match is enough.

  • Omitting alternative text from the badge image.

  • Applying the script outside the article content.

  • Forgetting to test pages where a badge already exists.

Keep the original link usable if an asset fails

Use a valid same-origin badge asset and its real dimensions, then check keyboard focus and the accessible name. If the script can load after DOMContentLoaded, initialize immediately when the document is already ready. Dynamically inserted links need a deliberate second initialization or scoped observer; the original text link remains the fallback before enhancement.

Keep stored content simple, then add the badge as a focused presentation enhancement. The next action is to test one matching link, one unrelated link, and one link that already contains an image.

Leave a Reply