Change WordPress Fragment Links in RSS Feeds to be Permalinks


Here's a knotty problem. Lots of my posts use URl Fragments. Those are links which start with #. They allow me to write:

HTML HTML<a href="#where-is-this-a-problem>Jump to heading</a>

So when someone clicks on a link, they go straight to the relevant section. For example, they might want to skip straight to how to fix it.

Isn't that clever?

Where is this a problem?

This works great when someone is on my website. They're on the page, and a fragment links straight to the correct section of that page.

But some people view this blog in RSS & Atom feeds - and those feeds also power my newsletter.

When those people see a fragment, it is devoid of its original context. So they end up going to some random location, or my homepage.

How to fix it?

Stick this into your WordPress theme's functions.php file:

PHP PHP//  In the RSS feed, change #whatever to <permalink>#whatever
function rewrite_fragment_links_in_rss($content) {
    global $post;

    //  Ensure this is a feed
    if ( is_feed() && $post instanceof WP_Post ) {
        //  Get the permalink
        $base_url = get_permalink( $post );

        //  Regex to get href="#
        $content = preg_replace_callback(
            '/href=["\']#([^"\']+)["\']/',
            function ( $matches ) use ( $base_url ) {
                return 'href="' . esc_url( $base_url . '#' . $matches[1] ) . '"';
            },
            $content
        );
    }

    return $content;
}

//  Hook into feed filters for both excerpts and full content
add_filter( "the_excerpt_rss",  "rewrite_fragment_links_in_rss" );
add_filter( "the_content_feed", "rewrite_fragment_links_in_rss" );

That listens out for the RSS feed being generated and replaces #whatever with https://shkspr.mobi/blog/2024/12/change-wordpress-fragment-links-in-rss-feeds-to-be-permalinks#whatever

Nifty!

Hopefully, if you click on the links in my emails and feeds, it should take you to the right place now.


Share this post on…

  • Mastodon
  • Facebook
  • LinkedIn
  • BlueSky
  • Threads
  • Reddit
  • HackerNews
  • Lobsters
  • WhatsApp
  • Telegram

What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.

Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <p> <pre> <br> <img src="" alt="" title="" srcset="">