跳到正文
DEV Community· Istiak Ahamed·· 1 小時前AI 評分55

如何在 WordPress 不用外掛加入 llms.txt:指南

How to Add llms.txt to WordPress Without a Plugin: Guide

AI 導讀

指南介紹在 WordPress 提供 llms.txt 的三種方式:根目錄靜態檔案、MU-plugin 虛擬 PHP 路由,以及從已發佈內容自動生成並快取。文中指出,llms.txt 是社羣提案而非正式標準,目前沒有已確認的搜尋排名效應。文中亦示範 /llms-full.txt 的生成方式,並説明在已發佈內容狀態變更時清除快取。

正文

When an LLM agent or retrieval tool fetches a typical WordPress page, it has to wade through megamenu markup, inline SVG icons, script tags, and sidebar widgets just to find your documentation or primary articles. Learning how to add llms.txt to WordPress gives AI assistants and developer tools a single Markdown index at /llms.txt that lists your canonical URLs and plain-English descriptions without HTML noise. Most tutorials tell you to install a full SEO suite just to serve a 2 KB text file. You can serve both /llms.txt and /llms-full.txt in WordPress without a plugin using either a static root file, a virtual PHP endpoint, or an event-driven generator hooked into save_post.

Table of Contents


Quick Answer: Serve llms.txt in WordPress With 25 Lines of PHP

If you want a zero-dependency /llms.txt route that runs before WordPress loads your theme templates, drop this Must-Use plugin into wp-content/mu-plugins/kx-llms-txt.php:

<?php
/**
 * Plugin Name: Kinetix Minimal llms.txt Endpoint
 * Description: Serves a Markdown /llms.txt index directly from WordPress core.
 */

defined( 'ABSPATH' ) || exit;

add_action( 'parse_request', function ( WP $wp ): void {
    $path = isset( $_SERVER['REQUEST_URI'] )
        ? trim( (string) wp_parse_url( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ), PHP_URL_PATH ), '/' )
        : '';

    if ( 'llms.txt' !== $path ) {
        return;
    }

    status_header( 200 );
    header( 'Content-Type: text/markdown; charset=UTF-8' );
    header( 'Cache-Control: public, max-age=3600' );
    header( 'X-Robots-Tag: noindex' );

    echo '# ' . esc_html( get_bloginfo( 'name' ) ) . "\n\n";
    echo '> ' . esc_html( get_bloginfo( 'description' ) ) . "\n\n";
    echo "## Primary Pages\n";
    echo '- [' . esc_html( get_bloginfo( 'name' ) ) . '](' . esc_url( home_url( '/' ) ) . "): Main site entry point.\n";
    exit;
}, 1 );

Because this hook intercepts parse_request at priority 1 and calls exit, WordPress never runs the main post query or renders header.php and footer.php.


What the llms.txt Proposal Actually Is (and Is Not)

The llms.txt specification is a community proposal authored by Jeremy Howard at Answer.AI. Its goal is straightforward: give large language models, IDE coding assistants (such as Cursor, Windsurf, and Copilot), and user-triggered retrieval tools a concise Markdown map at the root of a domain (/llms.txt).

Let's be direct about what /llms.txt does and does not do today:

  1. It is a proposed convention, not a ratified W3C or IETF standard. Unlike robots.txt (RFC 9309) or the Sitemaps XML protocol, llms.txt is an informal specification.
  2. AI crawler adoption varies. Developer-focused retrieval agents, RAG pipelines, and chat crawlers frequently look for /llms.txt when a user pastes a documentation domain into a prompt, while general training crawlers still rely primarily on standard HTML crawling and XML sitemaps.
  3. It has no confirmed search ranking effect. Adding /llms.txt will not boost your Google Search positions or replace standard technical SEO, structured data, or clean HTML headings.

Why add it anyway? Because it costs almost nothing to maintain and solves a real engineering problem: context window efficiency. When a developer or researcher points an AI assistant at your domain—just as we expose https://kinetix.software/llms.txt on this site—a clean Markdown directory lets the model see your product documentation, tutorials, and licensing pages in a single small payload instead of guessing URLs from a bloated DOM.

The Strict Markdown Grammar of llms.txt

According to the official spec at llmstxt.org, a valid llms.txt file follows a predictable Markdown hierarchy so simple parsers can split it deterministically:

  1. One H1 heading (# Site or Project Name): Required at the very top of the file. This is the only H1 in the document.
  2. One blockquote summary (> Short description...): Directly below the H1, summarizing what the site or project does and who it is built for.
  3. Optional plain-text notes: Zero or more paragraphs explaining how to interpret the site, version scope, or API conventions (with no headings).
  4. H2 file list sections (## Section Name): Each H2 groups related links formatted as - [Title](https://example.com/url): Brief plain-text summary of what that page covers.
  5. A reserved ## Optional section: Links placed under ## Optional tell an LLM parser that these URLs are secondary and can be skipped when the caller has a tight token budget.

Here is a complete, spec-compliant example modeled after a WordPress software and research site:

# Kinetix Studio & Research Lab

> Modular dark-glass WordPress theme and companion plugins for creative studios, academic labs, and WooCommerce storefronts.

All documentation targets WordPress 6.5+ and PHP 8.2+. Content types (Projects and Research) are registered by the companion Kinetix Core plugin so content stays portable across theme switches.

## Documentation

- [Getting Started](https://example.com/docs/getting-started): Installation, minimum PHP/WP requirements, and child theme setup.
- [Projects & Research Post Types](https://example.com/docs/projects-and-research): Custom post types, taxonomies, and archive templates.
- [Customizer & Design Tokens](https://example.com/docs/customizer): Glass blur, alpha, border opacity, and typography controls.

## Engineering Guides

- [Add Schema Markup Without a Plugin](https://example.com/blog/wordpress-schema-markup-without-plugin): Native JSON-LD output in wp_head.
- [Google Scholar Meta Tags in WordPress](https://example.com/blog/wordpress-google-scholar-meta-tags): Highwire Press citation_title and citation_pdf_url implementation.

## Optional

- [Changelog](https://example.com/changelog): Release history and upgrade notes.
- [Licensing Policy](https://example.com/docs/licences): GNU GPLv2+ code terms and commercial support rules.

How llms.txt Differs From robots.txt and XML Sitemaps

Site owners often ask why /llms.txt exists when /robots.txt and /sitemap.xml are already present on every WordPress installation. Each file solves a different problem at a different stage of automated retrieval.

File & Endpoint Primary Consumer Format & Spec Core Purpose Token & Context Suitability
/robots.txt Search & AI crawler bots (Googlebot, GPTBot, ClaudeBot) Plain text (RFC 9309) Access control directives (Allow, Disallow, Sitemap) telling crawlers where they may or may not crawl. Contains no content descriptions or curated page summaries.
/sitemap.xml (wp-sitemap.xml) Search engine indexers XML Sitemaps protocol Exhaustive machine inventory of every indexable URL and <lastmod> timestamp across the domain. Poor for LLM context windows; lists hundreds or thousands of raw URLs without titles or explanations.
/llms.txt LLM inference agents, IDE assistants, RAG fetchers Markdown (llmstxt.org proposal) Curated, human-and-LLM-readable syllabus of the site's most important pages with one-line summaries. Built specifically for token-constrained prompts; includes ## Optional for fast truncation.
/llms-full.txt Bulk documentation ingestion scripts Markdown (community convention) Concatenated full-text Markdown dump of core documentation pages in one file. High token volume; best reserved for small documentation sets rather than 5,000-post blogs.

Notice the distinction between discovery and curation. An XML sitemap lists every tag archive, paginated post, and product URL so Googlebot does not miss anything. An llms.txt file intentionally leaves out low-value archive pages and highlights the 20 to 60 evergreen pages that best explain your product, research, or documentation.


Request Lifecycle: How WordPress Resolves /llms.txt

Before choosing how to add llms.txt to WordPress, it helps to trace how Nginx/Apache and the WordPress rewrite router handle a request to https://example.com/llms.txt.

flowchart TD
    A["HTTP GET /llms.txt"] --> B{"Static file exists in web root?"}
    B -- "Yes (Method 1)" --> C["Nginx / Apache serves /llms.txt directly"]
    C --> D["Fast static response (PHP not invoked)"]
    B -- "No" --> E["Web server forwards request to /index.php"]
    E --> F["WordPress Bootstrap (wp-settings.php)"]
    F --> G["Action: init (register rewrite rule) & parse_request"]
    G --> H{"Matched /llms.txt route?"}
    H -- "Yes (Method 2 or 3)" --> I{"Cached Markdown in transient / object cache?"}
    I -- "Cache Hit" --> J["Send text/markdown headers + cached body + exit"]
    I -- "Cache Miss" --> K["Run lean WP_Query (fields => ids / no_found_rows)"]
    K --> L["Build Markdown + set_transient('kx_llms_txt')"]
    L --> J
    H -- "No" --> M["Standard WordPress Template Loader (404 / Page)"]

If an actual file exists on disk at ABSPATH . 'llms.txt' (or if your build pipeline writes it to public/llms.txt), Nginx's try_files $uri $uri/ /index.php?$args; directive serves the file directly from the filesystem without starting a PHP worker. If no static file exists on disk, the request falls through to index.php, where you can either serve a dynamic response via PHP or write a static file whenever posts are updated.

Let's compare the three implementation strategies before walking through the code for each.

Implementation Method How It Works PHP / DB Cost on Request Update Effort Best Use Case
Method 1: Static File in Web Root Hand-authored llms.txt placed in WordPress root (ABSPATH) Zero (served directly by Nginx/Apache) Manual edit via Git/SFTP Product sites, studio portfolios, and stable docs where top links change monthly.
Method 2: Virtual PHP Route (parse_request) Must-Use plugin intercepts /llms.txt and outputs curated PHP strings Minimal PHP bootstrap; zero post queries if hardcoded Edit MU-plugin array or filter Managed WordPress hosts with read-only web roots or multisite networks.
Method 3: Auto-Generated + Cached on save_post Builds Markdown from published posts/docs, caches in transient or writes file, invalidates on publish Zero DB queries on cache hit; rebuilds only when content changes Fully automatic on post publish/update Active editorial blogs, documentation hubs, and research repositories.

Method 1: Add llms.txt to WordPress as a Static Root File

If your site has a clear set of cornerstone pages—such as your main product pages, documentation chapters, and top tutorials—a static file in the WordPress document root (the same directory as wp-config.php and index.php) is the simplest and most reliable option.

Create llms.txt in your web root with UTF-8 encoding and LF line endings:

# Your Site Name

> One-sentence summary of what your organization, studio, or publication builds and who it serves.

Use the links below to retrieve canonical documentation and engineering guides.

## Core Pages

- [About & Architecture](https://example.com/about): Studio background, engineering principles, and stack details.
- [Documentation Hub](https://example.com/docs): Complete technical reference and setup chapters.

## Guides & Tutorials

- [WordPress Custom Post Type Without a Plugin](https://example.com/blog/wordpress-custom-post-type-without-plugin): Registering portable content types with register_post_type.
- [Add Schema Markup to WordPress Without a Plugin](https://example.com/blog/wordpress-schema-markup-without-plugin): Outputting Organization, Article, and BreadcrumbList JSON-LD.

## Optional

- [RSS Feed](https://example.com/feed/): Full syndication feed of recent posts.

Setting the Right MIME Type and UTF-8 Charset on Nginx and Apache

By default, web servers return text/plain for .txt files. While text/plain; charset=UTF-8 works fine for every LLM fetcher, adding an explicit UTF-8 charset and cache header prevents mojibake on em-dashes or non-ASCII characters.

In Nginx (inside your server block):

location = /llms.txt {
    default_type "text/plain; charset=UTF-8";
    add_header Cache-Control "public, max-age=3600";
    add_header X-Robots-Tag "noindex";
    try_files $uri /index.php?$args;
}

Or in Apache .htaccess (above # BEGIN WordPress):

<FilesMatch "^llms(-full)?\.txt$">
    ForceType "text/plain; charset=UTF-8"
    <IfModule mod_headers.c>
        Header set Cache-Control "public, max-age=3600"
        Header set X-Robots-Tag "noindex"
    </IfModule>
</FilesMatch>

Why X-Robots-Tag: noindex? Because /llms.txt is an index file for AI agents and developers, not a landing page meant to rank in Google Search results ahead of your actual HTML articles.


Method 2: Serve a Virtual PHP Route Without Theme Output

On many managed WordPress platforms (such as WP Engine, Kinsta, or WordPress VIP, or containerized setups where the root directory is read-only outside wp-content), dropping a static file next to wp-config.php is awkward. A virtual PHP route in wp-content/mu-plugins/ keeps everything inside version-controlled code.

There are two ways to wire a virtual route in WordPress:

  1. The Rewrite API (add_rewrite_rule + query_vars + template_redirect): Registers ^llms\.txt$ in the WordPress rewrite array. Clean, follows WordPress conventions, and works alongside register_post_type() rewrite rules, though it requires flushing permalinks once on activation.
  2. Early request interception on parse_request: Checks the normalized request path directly against home_url() path prefixes and exits before WP::query_posts() runs. It works immediately without touching the rewrite_rules option in wp_options.

Below is a production implementation that supports both subdirectory installs (e.g., example.com/wp/llms.txt) and root installs (example.com/llms.txt), exposes a filter (kx_llms_txt_sections) so themes or companion plugins can register their own sections, and never loads theme templates.

<?php
/**
 * Plugin Name: Kinetix Virtual llms.txt Router
 * Description: Serves /llms.txt dynamically with filterable sections and zero theme overhead.
 * Version:     1.0.0
 * License:     GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

/**
 * Determine whether the current HTTP request targets /llms.txt or /llms-full.txt.
 *
 * @return string Empty string if unmatched, otherwise 'llms.txt' or 'llms-full.txt'.
 */
function kx_match_llms_route(): string {
    if ( is_admin() || wp_doing_ajax() || wp_doing_cron() ) {
        return '';
    }

    $request_uri = isset( $_SERVER['REQUEST_URI'] )
        ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) )
        : '';
    $req_path    = (string) wp_parse_url( $request_uri, PHP_URL_PATH );
    $home_path   = (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH );

    // Strip subdirectory prefix if WordPress lives in a subfolder.
    if ( '' !== $home_path && '/' !== $home_path && str_starts_with( $req_path, $home_path ) ) {
        $req_path = substr( $req_path, strlen( $home_path ) );
    }

    $slug = trim( $req_path, '/' );
    if ( in_array( $slug, array( 'llms.txt', 'llms-full.txt' ), true ) ) {
        return $slug;
    }

    return '';
}

Method 3: Auto-Generate and Cache llms.txt From Published Content

When your site publishes new documentation, research papers, or engineering tutorials every week, hand-editing a static list gets stale. Method 3 generates /llms.txt dynamically from your published pages, custom post types, and posts, caches the compiled Markdown string for 12 hours using the WordPress Transients API (or persistent Redis object cache), and flushes the cache automatically whenever a published post is saved, trashed, or unpublished.

Save this complete file as wp-content/mu-plugins/kx-auto-llms-txt.php:

<?php
/**
 * Plugin Name: Kinetix Auto-Generated llms.txt & llms-full.txt
 * Description: Generates spec-compliant /llms.txt and /llms-full.txt with transient caching and save_post invalidation.
 * Version:     1.1.0
 * Author:      Kinetix
 * License:     GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

const KX_LLMS_CACHE_KEY      = 'kx_llms_txt_v1';
const KX_LLMS_FULL_CACHE_KEY = 'kx_llms_full_txt_v1';
const KX_LLMS_CACHE_TTL      = 12 * HOUR_IN_SECONDS;

/**
 * Clean a single-line plain-text summary for an llms.txt list item.
 */
function kx_llms_clean_summary( WP_Post $post, int $max_words = 24 ): string {
    $raw = has_excerpt( $post ) ? $post->post_excerpt : wp_strip_all_tags( $post->post_content );
    $raw = preg_replace( '/\s+/', ' ', trim( (string) $raw ) );
    return wp_trim_words( (string) $raw, $max_words, '...' );
}

/**
 * Build the /llms.txt Markdown payload.
 */
function kx_build_llms_txt(): string {
    $cached = get_transient( KX_LLMS_CACHE_KEY );
    if ( is_string( $cached ) && '' !== $cached ) {
        return $cached;
    }

    $site_name = wp_strip_all_tags( get_bloginfo( 'name' ) );
    $tagline   = wp_strip_all_tags( get_bloginfo( 'description' ) );
    if ( '' === $tagline ) {
        $tagline = sprintf( 'Official documentation, articles, and reference pages for %s.', $site_name );
    }

    $lines   = array();
    $lines[] = '# ' . $site_name;
    $lines[] = '';
    $lines[] = '> ' . $tagline;
    $lines[] = '';
    $lines[] = 'This file follows the llmstxt.org Markdown convention. Follow individual links for complete code examples and structured documentation.';
    $lines[] = '';

    // 1. Key Top-Level Pages (only published pages, ordered by menu_order).
    $pages = get_posts(
        array(
            'post_type'              => 'page',
            'post_status'            => 'publish',
            'posts_per_page'         => 15,
            'orderby'                => 'menu_order title',
            'order'                  => 'ASC',
            'no_found_rows'          => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        )
    );

    if ( ! empty( $pages ) ) {
        $lines[] = '## Core Pages';
        $lines[] = '';
        foreach ( $pages as $page ) {
            $title   = wp_strip_all_tags( get_the_title( $page ) );
            $url     = get_permalink( $page );
            $summary = kx_llms_clean_summary( $page, 20 );
            $lines[] = sprintf(
                '- [%s](%s)%s',
                $title,
                esc_url_raw( (string) $url ),
                '' !== $summary ? ': ' . $summary : ''
            );
        }
        $lines[] = '';
    }

    // 2. Custom Post Types (e.g., Projects or Research registered by Kinetix Core).
    $custom_types = get_post_types(
        array(
            'public'   => true,
            '_builtin' => false,
        ),
        'objects'
    );

    foreach ( $custom_types as $cpt ) {
        if ( in_array( $cpt->name, array( 'attachment', 'elementor_library' ), true ) ) {
            continue;
        }
        $items = get_posts(
            array(
                'post_type'              => $cpt->name,
                'post_status'            => 'publish',
                'posts_per_page'         => 20,
                'orderby'                => 'date',
                'order'                  => 'DESC',
                'no_found_rows'          => true,
                'update_post_meta_cache' => false,
                'update_post_term_cache' => false,
            )
        );
        if ( empty( $items ) ) {
            continue;
        }
        $lines[] = '## ' . wp_strip_all_tags( $cpt->labels->name );
        $lines[] = '';
        foreach ( $items as $item ) {
            $title   = wp_strip_all_tags( get_the_title( $item ) );
            $url     = get_permalink( $item );
            $summary = kx_llms_clean_summary( $item, 22 );
            $lines[] = sprintf(
                '- [%s](%s)%s',
                $title,
                esc_url_raw( (string) $url ),
                '' !== $summary ? ': ' . $summary : ''
            );
        }
        $lines[] = '';
    }

    // 3. Recent Published Blog Posts / Tutorials.
    $posts = get_posts(
        array(
            'post_type'              => 'post',
            'post_status'            => 'publish',
            'posts_per_page'         => 30,
            'orderby'                => 'date',
            'order'                  => 'DESC',
            'no_found_rows'          => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        )
    );

    if ( ! empty( $posts ) ) {
        $lines[] = '## Tutorials & Articles';
        $lines[] = '';
        foreach ( $posts as $post ) {
            $title   = wp_strip_all_tags( get_the_title( $post ) );
            $url     = get_permalink( $post );
            $summary = kx_llms_clean_summary( $post, 24 );
            $lines[] = sprintf(
                '- [%s](%s)%s',
                $title,
                esc_url_raw( (string) $url ),
                '' !== $summary ? ': ' . $summary : ''
            );
        }
        $lines[] = '';
    }

    // 4. Spec-compliant Optional section for secondary feeds.
    $lines[] = '## Optional';
    $lines[] = '';
    $lines[] = sprintf( '- [Full Markdown Corpus](%s): Expanded plain-text content of recent articles.', esc_url_raw( home_url( '/llms-full.txt' ) ) );
    $lines[] = sprintf( '- [RSS Feed](%s): XML syndication feed.', esc_url_raw( get_feed_link() ) );
    $lines[] = sprintf( '- [XML Sitemap](%s): Complete machine URL index.', esc_url_raw( home_url( '/wp-sitemap.xml' ) ) );
    $lines[] = '';

    $output = implode( "\n", $lines );
    set_transient( KX_LLMS_CACHE_KEY, $output, KX_LLMS_CACHE_TTL );

    return $output;
}

Excluding Noindex, Password-Protected, and Future Scheduled Posts

One critical rule when generating /llms.txt from WordPress queries: never leak unpublished, password-protected, or noindexed pages.

  1. Always pass 'post_status' => 'publish' and 'has_password' => false to get_posts(). Scheduled posts ('post_status' => 'future') and drafts ('draft') are automatically excluded when 'post_status' is locked to 'publish'.
  2. If you store a custom per-post meta flag such as _kx_noindex (or if you use our native JSON-LD schema and SEO meta setup), check that flag or filter it out before adding the post to the Markdown list.

Building a Companion /llms-full.txt Endpoint Safely

While /llms.txt acts as a compact table of contents, some developers also expose /llms-full.txt—a single Markdown document that concatenates the cleaned body text of their documentation or core tutorials. Note that /llms-full.txt is a community convention popularized by documentation platforms (such as Mintlify and VitePress) rather than a required part of the core llmstxt.org specification.

If you add /llms-full.txt to a WordPress site, enforce two safety limits:

  1. Cap the post count (posts_per_page => 25). Attempting to concatenate 2,000 posts on a single PHP request will exhaust memory_limit and produce a multi-megabyte file too large for any LLM context window anyway.
  2. Strip shortcodes and HTML tags cleanly while preserving headings and code blocks.

Here is the companion generator and request handler that pairs with the code above:

/**
 * Build a bounded /llms-full.txt Markdown corpus from the latest 20 published posts/pages.
 */
function kx_build_llms_full_txt(): string {
    $cached = get_transient( KX_LLMS_FULL_CACHE_KEY );
    if ( is_string( $cached ) && '' !== $cached ) {
        return $cached;
    }

    $site_name = wp_strip_all_tags( get_bloginfo( 'name' ) );
    $chunks    = array(
        '# ' . $site_name . ' — Full Content Corpus',
        '',
        '> Aggregated plain-text corpus of primary pages and recent technical guides.',
        '',
    );

    $items = get_posts(
        array(
            'post_type'              => array( 'page', 'post' ),
            'post_status'            => 'publish',
            'has_password'           => false,
            'posts_per_page'         => 20,
            'orderby'                => 'date',
            'order'                  => 'DESC',
            'no_found_rows'          => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        )
    );

    foreach ( $items as $item ) {
        $title = wp_strip_all_tags( get_the_title( $item ) );
        $url   = get_permalink( $item );
        $date  = get_the_date( 'Y-m-d', $item );

        // Strip shortcodes and block comments while keeping readable line breaks.
        $body = strip_shortcodes( (string) $item->post_content );
        $body = preg_replace( '/<!--\s*\/?wp:[^>]+-->/', '', (string) $body );
        $body = wp_strip_all_tags( (string) $body, false );
        $body = preg_replace( "/\n{3,}/", "\n\n", trim( (string) $body ) );

        $chunks[] = '---';
        $chunks[] = '## ' . $title;
        $chunks[] = sprintf( 'Canonical URL: %s | Published: %s', esc_url_raw( (string) $url ), $date );
        $chunks[] = '';
        $chunks[] = (string) $body;
        $chunks[] = '';
    }

    $output = implode( "\n", $chunks );
    set_transient( KX_LLMS_FULL_CACHE_KEY, $output, KX_LLMS_CACHE_TTL );

    return $output;
}

/**
 * Serve /llms.txt or /llms-full.txt on parse_request and invalidate cache on post changes.
 */
add_action(
    'parse_request',
    function (): void {
        $route = kx_match_llms_route();
        if ( '' === $route ) {
            return;
        }

        status_header( 200 );
        header( 'Content-Type: text/markdown; charset=UTF-8' );
        header( 'Cache-Control: public, max-age=3600, s-maxage=43200' );
        header( 'X-Robots-Tag: noindex' );

        echo 'llms-full.txt' === $route ? kx_build_llms_full_txt() : kx_build_llms_txt(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        exit;
    },
    1
);

/**
 * Flush cached llms.txt transients only when a published post transitions or updates.
 */
add_action(
    'transition_post_status',
    function ( string $new_status, string $old_status ): void {
        if ( 'publish' === $new_status || 'publish' === $old_status ) {
            delete_transient( KX_LLMS_CACHE_KEY );
            delete_transient( KX_LLMS_FULL_CACHE_KEY );
        }
    },
    10,
    2
);

Notice why we hook transition_post_status instead of save_post unguarded: WordPress fires save_post on every autosave and draft edit. Checking 'publish' === $new_status || 'publish' === $old_status ensures the transient cache only invalidates when a public post is actually published, updated, or unpublished.


Testing, Caching, and Troubleshooting

Once your file or MU-plugin is deployed, test both the HTTP response headers and the Markdown body from your terminal using curl:

# 1. Inspect HTTP status, Content-Type, Cache-Control, and X-Robots-Tag headers
curl -I https://example.com/llms.txt

# 2. Verify the first 30 lines of Markdown output and check for stray HTML tags
curl -s https://example.com/llms.txt | head -n 30

A clean response returns HTTP/2 200, content-type: text/markdown; charset=UTF-8 (or text/plain; charset=UTF-8), and starts immediately with # Your Site Name at byte 0—with no leading whitespace, BOM, or theme <head> markup.

If you also run Redis object caching or Nginx FastCGI page caching (see our guide on WordPress speed optimization without a plugin), the Cache-Control: public, max-age=3600, s-maxage=43200 header lets Cloudflare or Nginx cache the /llms.txt response at the edge so repeat bot fetches never hit PHP-FPM. For research labs publishing academic papers alongside their documentation, combine your /llms.txt index with Google Scholar meta tags in WordPress and inspect how Kinetix structures its own /llms.txt and documentation chapters.

Troubleshooting: Why does /llms.txt return my theme's 404 page or HTML?

  1. Nginx static file rule intercepting .txt files: Some Nginx templates contain a location ~* \.(txt|xml)$ { try_files $uri =404; } block that returns a hard Nginx 404 when a .txt file does not exist physically on disk, preventing the request from reaching WordPress's index.php. If you use Method 2 or Method 3 on Nginx, either change that rule to try_files $uri /index.php?$args; for /llms.txt or write the generated string directly to ABSPATH . 'llms.txt' on transition_post_status.
  2. Output buffering from another plugin: If an optimization or security plugin opens an output buffer (ob_start()) on muplugins_loaded, call while ( ob_get_level() &gt; 0 ) { ob_end_clean(); } immediately before echoing your Markdown in the parse_request callback.
  3. Subdirectory URL mismatch: If your WordPress site URL (siteurl) is https://example.com/wp while your home URL (home) is https://example.com, make sure your route matcher compares against home_url( '/' ) rather than site_url( '/' ).

Troubleshooting: Cloudflare or WAF blocks AI agents from reading /llms.txt

If you enable Cloudflare's "Block AI Scrapers and Crawlers" toggle, Cloudflare may challenge or block requests from user agents like GPTBot, ClaudeBot, PerplexityBot, or ChatGPT-User across your entire domain—including /llms.txt. If you want user-triggered AI assistants to read your /llms.txt while still rate-limiting bulk scraping on heavy dynamic routes, add a WAF Custom Rule in Cloudflare:

  • When incoming requests match: (http.request.uri.path in {"/llms.txt" "/llms-full.txt"}) and (http.request.method eq "GET")
  • Then take action: Skip (Bot Fight Mode / Super Bot Fight Mode).

Frequently Asked Questions

Does adding llms.txt improve Google Search rankings?

No. Google Search does not use /llms.txt as a ranking signal or indexing input. Google relies on HTML crawl links, robots.txt, XML sitemaps, and JSON-LD structured data. The purpose of /llms.txt is to give LLM tools, coding assistants, and retrieval agents a clean Markdown map when someone queries or references your site inside an AI workflow.

Should I use text/plain or text/markdown for the Content-Type header?

Both work across every major LLM client and HTTP fetcher. text/markdown; charset=UTF-8 (registered under RFC 7763) is the most semantically accurate MIME type for a Markdown document, while text/plain; charset=UTF-8 renders identically in browser tabs. Always include charset=UTF-8 so punctuation and non-ASCII characters decode properly.

Do I need to list every blog post in llms.txt?

No. Unlike /wp-sitemap.xml, which is meant to be exhaustive, /llms.txt works best when it stays under a few thousand tokens. List your core product pages, primary documentation chapters, and your top 20 to 30 technical guides, and move secondary feeds or archives under the ## Optional heading.

How does llms.txt interact with robots.txt AI crawler rules?

/robots.txt controls crawler permissions, while /llms.txt provides a content summary. If you disallow GPTBot or ClaudeBot from / in /robots.txt, compliant crawlers from those providers will not fetch /llms.txt either unless you explicitly add Allow: /llms.txt under their User-agent block.


Originally published at https://kinetix.software/blog/wordpress-llms-txt-without-plugin.

來源:DEV Community · dev.to