Skip to content

#276: Fix Social Links in RSS Feed of MkDocs

The Social plug-in of MkDocs Material gives us the nice images with the titles of our blog posts when we share them on social media.

The social card image for the post Introducing DuckDB

Those images are also part of the RSS feed, but once more not in a correct format. Let us see how we can fix that.

The problem

The links in the RSS feed for the social cards are a mix of \ and / and point to the wrong direction. That is why we end up with a link that looks like this:

XML: 
https://pythonfriday.dev/assets/images/social/2025\03\269-introducing-duckdb.png
JSON: 
https://pythonfriday.dev/assets/images/social/2025\\03\\269-introducing-duckdb.png

While it should look like this:

XML:
https://pythonfriday.dev/assets/images/social/posts/2025/269-introducing-duckdb/269-introducing-duckdb.png
JSON: 
https://pythonfriday.dev/assets/images/social/posts/2025/269-introducing-duckdb/269-introducing-duckdb.png

Fix the problem

We can use the script we wrote in #258: Fix the Internal Links in the RSS-Feed of MkDocs. We can create a new method named transform_social_links(link) that accepts a link and fixes it:

def transform_social_links(link):
    # Regex pattern to extract the relevant parts of the URL
    pattern = re.compile(r"(https?://[^\s]+/social/)(\d{4})[\\/]+(\d{2})[\\/]+([^/]+\.png)")
    match = pattern.search(link)

    if match:
        base_url, date_path, month_part, filename = match.groups()
        name_without_extension = filename.rsplit('.', 1)[0]
        new_link = f"{base_url}posts/{date_path}/{name_without_extension}/{filename}"
        return new_link
    return link

In the method fix_feed(feed, valid_posts) we can use another regex to find the links we need to fix and pass it to our new method:

def fix_feed(feed, valid_posts):
    print(f"Work on file {feed}")
    with open(feed, 'r') as file:
        data = file.read()

    links_to_md_file = find_links_to_md_file(data)
    substitutes = find_replacement(valid_posts, links_to_md_file)

    for key, value in substitutes.items():
        data = data.replace(key, value)

    transformed_content = re.sub(r"(https?://[^\s]+/social/\d{4}[\\/]+\d{2}[\\/]+[^/]+\.png)", 
                                 lambda match: transform_social_links(match.group(0)), 
                                 data)

    with open(feed, 'w') as file:
        file.write(transformed_content)

Conclusion

With these few additional lines, we can fix the problem and correct the links to the social card images. Since it is in the script we use to fix the other links, we only need to run one script and get everything inside our RSS feed fixed.

While a build pipeline that offers hooks to fix such things properly in the RSS plug-in would be a better solution, we must take what is available. And for that I think it is a good enough solution. I hope this helps you to fix the links in your feeds.