How to generate a basic XML sitemap with PHP in WordPress

Contents

Why a sitemap matters

A sitemap is an XML file that lists the URLs of a website along with metadata (last modification, change frequency, priority, images, etc.). Search engines use sitemaps to discover and index pages more efficiently, especially on dynamic sites such as WordPress where content is generated programmatically. WordPress core added its own sitemap in recent versions, but building a custom sitemap remains useful when you need custom filters, image support, specific priorities, or advanced caching and splitting behavior for very large sites.

Sitemap basics and XML structure

The most common sitemap format follows the Sitemaps XML protocol (sitemaps.org). A basic sitemap document looks like this:



  
    https://example.com/
    2025-01-01T12:34:56 00:00
    weekly
    0.8
  

Important points:

  • loc — required: full URL of the resource.
  • lastmod — optional but recommended: last modified date in W3C Datetime format (ISO 8601). In WordPress use published/modified timestamps from posts.
  • changefreq — optional: value like hourly/daily/weekly/monthly/never. Mostly advisory for crawlers.
  • priority — optional: value 0.0 to 1.0 that indicates relative importance.

Image sitemaps

If pages include important images you want indexed, include image extension tags with the image namespace:


  
    https://example.com/post-with-image
    
      https://example.com/wp-content/uploads/2025/01/photo.jpg
      Caption here
    
  

High-level approach for WordPress

Steps to implement a basic but production-aware sitemap:

  1. Decide how the sitemap will be served: dynamically via a rewrite rule (recommended for most cases) or by writing static files to disk (useful for very large sites or very high traffic).
  2. Query the WP database for public content (posts, pages, custom post types) while excluding drafts, password-protected posts, and posts with noindex meta.
  3. Output a valid XML sitemap with correct headers and proper escaping.
  4. Add caching (transients or write-to-disk) to avoid heavy queries on each request.
  5. Optionally split the sitemap into multiple files and add a sitemap index (required if you have >50,000 URLs or >50MB uncompressed per sitemap file).
  6. Notify search engines when the sitemap changes.

Basic, ready-to-use example (plugin or functions.php)

This example creates a rewrite rule that serves /sitemap.xml. It queries public posts and pages and outputs a simple sitemap. Place into your themes functions.php or as a plugin file. After activation or adding the code, visit the WordPress admin Permalinks settings and click Save to flush rewrite rules, or call flush_rewrite_rules() once on activation if packaged as a plugin.




Acepto donaciones de BAT's mediante el navegador Brave :)



Leave a Reply

Your email address will not be published. Required fields are marked *