wp_insert_post_data Is a Data Filter, Not a Publish Gate: Enforcing Editorial Standards Without Lying to Yourself

Symptom. A minimum-word-count rule is wired into wp_insert_post_data. The callback counts words, finds the draft short, and does the only thing a filter can do: returns the array it was given. The post publishes anyway. The editor shows no error. The rule appears to exist and does nothing.

This is not a bug in the hook. It is a category error in the design. wp_insert_post_data filters the post array on its way to the database. It returns data. It cannot return a WP_Error, cannot abort the write, and cannot tell the block editor that a save was rejected. If your editorial policy lives there, it is advisory at best.

What follows traces the hook, shows what it can safely do, and moves enforcement to the place where a status change can actually be inspected and reverted.

Trace: what the hook actually receives

The developer reference documents the signature precisely:

apply_filters( 'wp_insert_post_data', array $data, array $postarr, array $unsanitized_postarr, bool $update )

Per the same page, $data is “slashed, sanitized, and processed post data,” $postarr is “sanitized (and slashed) but otherwise unmodified post data,” $unsanitized_postarr is the array as originally passed to wp_insert_post(), and $update is a boolean indicating whether an existing post is being updated. The filter is described as filtering “slashed post data just before it is inserted into the database.”

Two consequences follow directly from that description.

First, the hook fires on insert and update. The documentation’s own user-contributed note is blunt about it: “Contrary to the name, this hook also runs on post update and post delete.” That means every autosave, every revision write, every programmatic wp_update_post() call, and every REST save from the block editor passes through your callback. A word-count rule placed here is not a publish rule; it is a rule about every write to the posts table.

Second, the return value is the data array. There is no documented mechanism for returning an error, and the hook’s contract is a filter, not an action. If you return the array unchanged, the write proceeds. If you mutate post_status inside the filter, you are changing the data being written, not rejecting the operation — and you are doing so on every save, including saves the editor did not intend as a publish.

Trace: where the filter sits relative to the status transition

wp_insert_post() is the function that inserts or updates a post, and it updates when $postarr contains an ID. The developer reference for wp_update_post() shows that it ultimately calls wp_insert_post(), so both paths converge on the same filter.

The status transition is a separate mechanism. transition_post_status is documented as firing “when a post is transitioned from one status to another,” with three arguments: the new status, the old status, and the WP_Post object. The same page documents a status-specific variant, {$old_status}_to_{$new_status}, so draft_to_publish is a real hook you can attach to.

The retrieved source excerpts do not include the exact call site of wp_transition_post_status() relative to the wp_insert_post_data filter inside wp_insert_post(), so this article does not assert a precise ordering beyond what the documentation states: the filter runs inside wp_insert_post() before the database write, and the transition hook fires via wp_transition_post_status(). What matters for the design is not the microsecond ordering but the contract: one hook filters data, the other observes a status change on a WP_Post object you can inspect and act on.

Root cause: a filter cannot enforce

The failure is structural. Enforcement requires one of three things: refusing the write, returning an error the caller can surface, or reverting the state change after the fact. wp_insert_post_data offers none of these. It offers a data array and expects a data array back.

There is a second, subtler problem with counting words inside this filter. The $data['post_content'] you receive is the stored content, which for block-editor posts includes block comment delimiters and for classic posts may include shortcodes. A word count computed against that string is not the same as a word count computed against what the editor sees rendered. The documentation does not define a canonical word-count function, and this article does not invent one. The point is that the counting decision is separate from the hook decision: even if you count correctly, the filter still cannot reject the save.

What the filter is good for

Normalization. The developer reference includes a user-contributed example that decodes HTML entities from post_title inside the filter:

function filter_post_name( $data, $postarr, $unsanitized_postarr ) {
    $data['post_title'] = html_entity_decode( $data['post_title'] );
    return $data;
}
add_filter( 'wp_insert_post_data', 'filter_post_name', 10, 3 );

That is the correct shape of use: transform a field, return the array, scope it to a post type. The same page notes that you must pass 2 as the $accepted_args argument to reach $postarr, and that the post ID is available as $postarr['ID']. If you need $update, pass 4.

A scoped normalization callback looks like this:

add_filter( 'wp_insert_post_data', function ( $data, $postarr, $unsanitized_postarr, $update ) {
    if ( 'post' !== $data['post_type'] ) {
        return $data;
    }
    $data['post_title'] = trim( html_entity_decode( $data['post_title'] ) );
    return $data;
}, 10, 4 );

Note what this does not do: it does not check word count, does not change status, and does not attempt to signal failure. It normalizes a field on every write, which is exactly what a data filter is for.

Fix: enforce at the status transition

Move the policy to transition_post_status or its status-specific variant. The documentation’s user-contributed notes are explicit that transition_post_status also fires on ordinary updates where the status does not change, so a bailout on $old_status === $new_status is required if you want to act only on real transitions.

The following is a labeled hypothetical, not a tested deployment. It illustrates the mechanism, not a recommended threshold:

add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) {
    if ( 'publish' !== $new_status || 'publish' === $old_status ) {
        return;
    }
    if ( 'post' !== $post->post_type ) {
        return;
    }
    $word_count = str_word_count( wp_strip_all_tags( $post->post_content ) );
    if ( $word_count < 300 ) {
        // Revert to draft. This is a state change, not a filter return.
        wp_update_post( array(
            'ID'          => $post->ID,
            'post_status' => 'draft',
        ) );
    }
}, 10, 3 );

Three things to notice. The callback bails when the status is not changing to publish, so it does not fire on every save. It bails on non-post types. And when it acts, it calls wp_update_post() to change status — a different mechanism than returning a filtered array. That call will itself pass through wp_insert_post_data and through transition_post_status, so the callback must be idempotent: the second transition is publish to draft, which the guard at the top already excludes.

This is not elegant. It is a revert, not a rejection, and the editor may see the post flip back to draft without a clear message. The documentation retrieved for this article does not describe how the block editor surfaces save failures, so this article does not claim a specific editor UX. What it does claim is that the revert is a real state change on a real WP_Post object, which is more than the filter can offer.

Verification

Confirm the hook is firing where you think it is. A minimal probe:

add_filter( 'wp_insert_post_data', function ( $data, $postarr, $unsanitized_postarr, $update ) {
    error_log( sprintf(
        'wp_insert_post_data: type=%s status=%s update=%s id=%s',
        $data['post_type'],
        $data['post_status'],
        $update ? 'true' : 'false',
        isset( $postarr['ID'] ) ? $postarr['ID'] : 'new'
    ) );
    return $data;
}, 10, 4 );

Save a draft, publish it, and autosave it. The log should show multiple entries with different status and update values. If you expected one entry per publish, the log will correct that expectation.

Confirm the transition hook fires on the transition you care about:

add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) {
    error_log( sprintf(
        'transition: %s -> %s (id=%d, type=%s)',
        $old_status, $new_status, $post->ID, $post->post_type
    ) );
}, 10, 3 );

Publish a draft and watch for a single draft -> publish line. Then update the published post without changing status and confirm you see a publish -> publish line — the documentation’s warning about the hook firing on non-transitions, demonstrated.

If you want to inspect the stored content your word-count logic will see, query it directly:

wp db query "SELECT ID, post_status, CHAR_LENGTH(post_content) AS len FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_modified DESC LIMIT 5;"

That gives you the raw length, not a word count, but it is enough to confirm that block markup is present in the stored string and that any count against it is a count against markup-inclusive content.

Debugging checklist

When a rule “does not work,” check these in order.

Hook arity. If your callback declares four parameters but add_filter() passes 10, 2, the third and fourth arguments are null. The documentation is explicit that you must pass 2 to reach $postarr; the same logic applies to 4 for $update.

Return value. A filter callback that returns nothing returns null, and the data array is lost. Every path through the callback must return $data.

Wrong hook for the job. If the requirement is “do not publish below N words,” the filter cannot satisfy it. Move the check to transition_post_status or draft_to_publish.

Missing bailout. A transition_post_status callback without an $old_status === $new_status guard fires on every update, including the revert you just performed, which is how you get a loop.

Counting the wrong string. $post->post_content contains block delimiters and shortcodes. If your threshold was chosen against rendered prose, the stored count will not match it. Decide which string the rule governs before you pick a number.

The general principle is not specific to word counts. Any editorial rule that must prevent a state change belongs at a hook that observes the state change. Any rule that must normalize a field belongs at a data filter. wp_insert_post_data is the second kind. Using it as the first kind produces a rule that logs, mutates, and returns — and publishes anyway.

How to Build a Content Audit Dashboard That Shows Which Posts Are Missing Alt Text, Meta Descriptions, and Internal Links

A content audit dashboard fails in a specific, boring way: it reports zero problems because it looked in the wrong place. Alt text, meta descriptions, and internal links live in three different stores. A dashboard that assumes one store will silently miss the other two, and the report will look clean while the site is not.

This is a data-location problem before it is a UI problem. The three checks read:

  • Alt text — attachment post meta, key _wp_attachment_image_alt.
  • Meta descriptions — a post meta key written by whatever SEO layer the site runs. Core has none.
  • Internal links — the stored post_content. Core maintains no link table.

The design rule that follows: name the store each check reads, check key existence separately from value emptiness, and state the dashboard’s coverage. A dashboard that does not say what it scanned cannot be trusted when it says zero.

Symptom: the dashboard says everything is fine

The common failure is a dashboard that queries get_post_meta( $id, 'meta_description', true ), gets an empty string back for every post, and concludes the site is compliant. Or one that reads alt text from the rendered img tag and misses the media library field entirely. Or one that counts internal links by scanning for href and includes every external URL on the page.

Each of these produces a false clean. The fix is not a better UI. It is a query that reads the right store and reports its own scope.

Trace: where each check actually reads

Alt text is attachment meta, not content markup

WordPress stores the media library alt field as post meta on the attachment, under the key _wp_attachment_image_alt. The REST attachments controller reads it exactly that way when it builds the alt_text field:

if ( in_array( 'alt_text', $fields, true ) ) {
    $data['alt_text'] = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
}

That is from the WP_REST_Attachments_Controller::prepare_item_for_response() source. The implication for the dashboard: the check is a query against wp_postmeta joined to attachments, not a parse of post content.

The gap to state up front: this field is the media library’s alt value. It is not the same as an alt attribute typed directly into block markup. If an editor inserted an image and wrote alt text in the block inspector, that value may live in the block attributes inside post_content rather than in the attachment meta. The dashboard should say which one it checks.

Meta descriptions have no core home

Core WordPress does not ship a meta description field. The REST posts schema exposes a meta object, but that object contains only fields that have been registered — it is not a container of SEO data by default. As one practitioner guide puts it, without Yoast SEO or RankMath the REST response has only core fields such as the rendered title and raw content, not meta descriptions or robots directives (RapidDev, “How to Automate WordPress SEO Reports using the API”).

So the dashboard must read whatever key the site’s SEO layer writes. That key is plugin- and version-dependent. The same guide notes that Yoast exposes a yoast_head_json object in REST responses, but also that the exact meta key names used for updates vary by version. Do not hardcode a key from a blog post. Confirm it against the site’s own database before building the check.

Here is the failure mode that matters. get_post_meta() with $single = true returns an empty string when the key is absent. The function reference documents the $single parameter and notes it has no effect if $key is not specified. The practical consequence: “missing” and “present but empty” look identical through that call. A dashboard that treats the empty string as proof of absence will report a site as clean when the key is simply named differently.

The fix is to check key existence separately from value emptiness. get_post_custom_keys() returns the keys that exist for a post, so the dashboard can distinguish “no such key” from “key exists, value empty.”

Internal links are a content parse, not a table lookup

Core does not maintain a table of links between posts. The only reliable source is the stored post_content. The check is a parse of that column for links whose host matches the site’s own host, with a stated rule for what counts.

The blind spots are real and should be printed on the dashboard, not buried in a footnote:

  • Links rendered by blocks at output time, shortcodes, or templates will not appear in post_content.
  • Links added by the block editor’s navigation or query blocks may be stored as block attributes rather than as href values in the content string.
  • Relative URLs and protocol-relative URLs need an explicit rule.

A dashboard that claims to count internal links without naming these limits is overstating its coverage.

Root cause: per-post loops and wrong-store assumptions

Two design mistakes produce most of the false results.

Mistake one: a per-post get_post_meta loop. For a site with a few hundred posts, looping over every post and calling get_post_meta turns one query into N queries and hides the key-existence question inside a falsy return value. The wpdb documentation describes get_col() as returning a one-dimensional array and an empty array when no result is found — which is exactly the shape needed for a set-based “which posts lack this key” pass.

Mistake two: assuming the REST posts endpoint returns SEO meta. It does not, unless a plugin registers those fields. The posts schema lists meta as an object, but the object is populated only by registered meta. A dashboard that reads meta.meta_description from /wp/v2/posts without confirming registration will get nothing and report clean.

Fix: three set-based queries and one content scan

The dashboard should be read-only. It reports state; it does not write corrections. Mixing audit and repair invites save_post recursion and makes the report’s state ambiguous. The save_post reference documents the infinite-loop hazard when a callback calls wp_update_post without unhooking first. Keep the audit pass out of that path entirely.

Check 1: attachments missing alt text

This is a set-based query against wp_postmeta. Use $wpdb->prepare() for the key value. The wpdb documentation states that all untrusted values in an SQL statement must be escaped and that prepare() performs this for WordPress.

global $wpdb;

$missing_alt = $wpdb->get_col(
    $wpdb->prepare(
        "SELECT p.ID
         FROM {$wpdb->posts} p
         LEFT JOIN {$wpdb->postmeta} pm
           ON pm.post_id = p.ID
          AND pm.meta_key = %s
         WHERE p.post_type = 'attachment'
           AND p.post_mime_type LIKE %s
           AND ( pm.meta_value IS NULL OR pm.meta_value = '' )",
        '_wp_attachment_image_alt',
        'image/%%'
    )
);

Note the double-% in the LIKE pattern. The wpdb documentation is explicit: all % characters inside SQL string literals, including LIKE wildcards, must be double-% escaped as %%. Getting this wrong produces a prepare error, not a wrong result — which is at least a loud failure.

This query returns attachments where the meta row is absent or the value is empty. It does not distinguish the two. If the dashboard needs that distinction, run a second query that selects only rows where the meta key exists and the value is empty, and subtract.

Check 2: posts missing the SEO meta description key

First, confirm the key. Run this against the site’s database or via WP-CLI:

wp db query "SELECT meta_key, COUNT(*) AS n
FROM wp_postmeta
WHERE meta_key LIKE '%desc%'
GROUP BY meta_key
ORDER BY n DESC;"

That surfaces the actual key names in use. Do not assume _yoast_wpseo_metadesc or any other name from a tutorial. The RapidDev guide cited above notes that the exact key names vary by plugin version.

Once the key is confirmed, the missing-key query is a LEFT JOIN that selects posts where the meta row is absent:

global $wpdb;

$seo_key = '_yoast_wpseo_metadesc'; // confirm against the site first

$missing_desc = $wpdb->get_col(
    $wpdb->prepare(
        "SELECT p.ID
         FROM {$wpdb->posts} p
         LEFT JOIN {$wpdb->postmeta} pm
           ON pm.post_id = p.ID
          AND pm.meta_key = %s
         WHERE p.post_type = 'post'
           AND p.post_status = 'publish'
           AND pm.meta_id IS NULL",
        $seo_key
    )
);

This returns posts where the key does not exist at all. A separate query returns posts where the key exists but the value is empty:

$empty_desc = $wpdb->get_col(
    $wpdb->prepare(
        "SELECT p.ID
         FROM {$wpdb->posts} p
         INNER JOIN {$wpdb->postmeta} pm
           ON pm.post_id = p.ID
          AND pm.meta_key = %s
         WHERE p.post_type = 'post'
           AND p.post_status = 'publish'
           AND pm.meta_value = ''",
        $seo_key
    )
);

Two queries, two lists. The dashboard can now report “key absent” and “key present, value empty” as distinct states. That distinction is the difference between a dashboard that finds the wrong-key problem and one that hides it.

Check 3: internal links in post content

There is no link table. The check is a parse of post_content. Use WP_Query or get_posts here because the scan needs full post objects, not just IDs. The set-based SQL shape is wrong for this pass.

$site_host = wp_parse_url( home_url(), PHP_URL_HOST );

$posts = get_posts( array(
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'fields'         => 'ids',
) );

$no_internal = array();

foreach ( $posts as $post_id ) {
    $content = get_post_field( 'post_content', $post_id );
    $has_internal = false;

    if ( preg_match_all( '/]*href=["\']([^"\']+)["\']/i', $content, $matches ) ) {
        foreach ( $matches[1] as $href ) {
            $host = wp_parse_url( $href, PHP_URL_HOST );
            if ( $host === null || $host === $site_host ) {
                $has_internal = true;
                break;
            }
        }
    }

    if ( ! $has_internal ) {
        $no_internal[] = $post_id;
    }
}

This is a regex over stored content, not a DOM parse. It will miss links rendered by blocks at output time and links stored as block attributes rather than as href strings. The dashboard should print that limitation next to the result.

For a more accurate parse, run the content through do_blocks() and then parse the rendered HTML. That catches links that blocks render. It does not catch links added by templates or shortcodes that run later in the render pipeline. State the boundary.

Verification: make the dashboard report its own coverage

A dashboard that says “zero missing” is only useful if it also says what it scanned. The output should include:

  • Number of published posts scanned.
  • Number of image attachments scanned.
  • The exact meta key checked for meta descriptions.
  • Whether the internal-link check parsed raw content or rendered blocks.
  • The site host used to classify links as internal.

Without those five facts, a zero is not a result. It is a guess.

To verify the queries themselves, run them against a known-bad post. Create a draft with no meta description, confirm it appears in the missing-key list, then add the key and confirm it moves to the empty-value list or drops out. If the dashboard cannot distinguish those states, the key-existence check is not working.

What the dashboard cannot tell you

State these limits in the dashboard itself, not in a README nobody reads:

  • Alt text in block markup. The _wp_attachment_image_alt check reads the media library field. Alt text typed into a block’s image settings may live in block attributes inside post_content and will not appear in this check.
  • Links generated at render time. Shortcodes, template parts, and blocks that build links dynamically will not appear in a post_content parse.
  • SEO fields from plugins that do not expose a queryable meta key. If the SEO layer stores descriptions somewhere other than wp_postmeta, the meta-key check will report every post as missing. Confirm the storage location before trusting the result.
  • REST-only SEO data. Some plugins expose SEO fields in REST responses without writing a queryable meta key. The dashboard reads the database, not the REST output, so those fields are invisible to it.

The shape of a trustworthy audit

Three checks, three stores, one rule: name the store, check key existence separately from value emptiness, and print the coverage. The dashboard is a read-only diagnostic over WordPress’s own data model. It does not wrap a plugin’s REST output, and it does not write corrections.

The failure mode to design around is the false clean. A dashboard that queries the wrong meta key, or that treats an empty string as proof of absence, will report a site as compliant when it is not. The fix is not a better UI. It is a query that reads the right place and says so.

If the site is new enough that the dashboard returns nothing at all, start with the basics before building audit queries — see What to Fix First When a New WordPress Site Says Nothing Found.

FAQ

Why does get_post_meta return an empty string for a key I know exists?

It may not exist. With $single = true, a missing key returns an empty string, and a key that exists with an empty value also returns an empty string. Use get_post_custom_keys() to check existence separately from value.

Can I read meta descriptions from the REST posts endpoint?

Only if a plugin registers the field. The posts schema lists meta as an object, but it contains only registered meta. Without an SEO plugin that registers the field, the response has no meta description. Confirm registration before relying on it.

Why does my internal-link count include external links?

The parse is matching every href without comparing the host. Compare wp_parse_url( $href, PHP_URL_HOST ) against wp_parse_url( home_url(), PHP_URL_HOST ) and treat relative URLs as internal by rule.

Should the dashboard fix the issues it finds?

No. Keep the audit pass read-only. Writing corrections from the audit invites save_post recursion and makes the report’s state ambiguous. Let editors fix issues in the editor.

How do I know the dashboard is checking the right meta key?

Query the database for keys matching the pattern before building the check. wp db query "SELECT meta_key, COUNT(*) FROM wp_postmeta WHERE meta_key LIKE '%desc%' GROUP BY meta_key;" surfaces the actual key names in use. Do not assume a key name from a tutorial.

The Small Lowercase ‘meh.’ Is a Typographic Null, Not a Personality

The native garment preview shows a dark shirt with very small, centered lowercase meh. lettering. No animal illustration is present. That is the entire design. The period is there, the letters are lowercase, and the type is set small enough that the word reads as a quiet annotation rather than a declaration. Previous coverage of this listing has called the shirt a null return, a log line with no stack trace, a typographic volume knob, a state machine, a shrug, and a contract. Each of those readings treated the word as a message. This one treats the scale as the message, and asks what a typographic null actually does when you wear it into a room.

The shirt is available at the Amazon listing. The design is a small lowercase word on a dark ground. The word is meh. The period is printed. The letters are not capitalized. There is no illustration, no secondary text, and no visual joke beyond the word itself. That is the observed object. Everything below is interpretation, not a claim about the shirt’s history, popularity, or effect on the wearer.

Editorial note: this publication and Quirky Cotton Collective share an owner.

What the period does

A period at the end of a word is a terminator. In prose it closes a sentence. In typography it closes a thought. On a shirt, a period closes the interaction before it starts. The word meh without a period is a sound, a shrug, a trailing vowel. The word meh with a period is a verdict. The period is what makes the design a null return rather than a mood. It says: this evaluation is complete, and the result is neither positive nor negative. It is a closed record.

That is a different object from a shirt that says meh in large letters. Large letters invite comment. Small letters with a period do not invite comment; they preempt it. The scale and the punctuation work together. The word is small enough that you have to be close to read it, and the period is there when you do. The design is not asking for a reaction. It is filing one.

Scale as a boundary

The previous headlines on this listing have mostly read the word. The scale is the part they leave open. A small centered word on a dark shirt is a low-volume signal. It does not carry across a room. It does not start a conversation from ten feet away. It is legible only at conversational distance, which means the shirt’s message is available exactly to the people who are already close enough to read it. That is a boundary condition, not a personality trait.

In systems terms, the design has a short broadcast radius. It is not a banner ad. It is a status field rendered at the smallest legible size. The word is the value; the scale is the access control. You do not have to explain the shirt to anyone who cannot read it, because they cannot read it. The people who can read it are already in the room. That is a coherent design decision, and it is the one the artwork actually makes.

Why ‘meh.’ is not a slogan

A slogan makes a promise. It says just do it or think different or i’m with stupid. A slogan is a forward commitment: wear this and you are this kind of person. The small lowercase meh. does not make a forward commitment. It makes a backward one. It reports an evaluation that has already happened. The period is the evidence. The word is the finding. The shirt is the record.

That distinction matters for anyone who has to write interface copy, error messages, or team norms. A slogan is a promise you have to keep. A null return is a finding you have already filed. The shirt is the second kind of object. It does not ask the wearer to perform enthusiasm or detachment. It states a completed assessment at the smallest possible volume. The design is consistent: lowercase, centered, small, terminated. Nothing in the artwork oversells the word.

What the shirt does not do

The shirt does not cure anything, improve anything, or demonstrate anything about the wearer’s personality. It is a printed word on a garment. The observed design is a small lowercase meh. on a dark shirt, and that is the whole of the evidence. The rest is a reading of the typography, offered as interpretation rather than fact. The period is printed. The letters are lowercase. The type is small. Those are the observable details, and they are enough to make the argument: the design is a typographic null, not a personality. The scale is the point. The period is the proof.

Why Your Custom Taxonomy Archive Shows Posts in the Wrong Order When You Use a Custom Field for Sorting

Symptom

The archive page for your custom taxonomy loads. The posts appear. The pagination works. But the order is wrong: it does not follow the custom field you set as the sort key. Sometimes the posts come out in descending ID order, sometimes in whatever order the database returned them, sometimes in an order that looks almost right until you check a specific post.

The template file is not the problem. The archive order is a property of the main query’s arguments. If the rendered order is wrong, the first question is which query the loop is iterating, not what the template prints.

Trace: Which Query Is Producing the Loop?

WordPress fires pre_get_posts on every WP_Query instance, not just the main one. The hook documentation is explicit: it fires after the query variable object is created but before the actual query is run, and it receives the WP_Query instance by reference. That means a callback that sets meta_key and orderby without checking which query it is modifying can easily hit a secondary query in a sidebar, a related-posts block, or a widget. The main archive query then runs with its default arguments and renders in default order.

The documentation also warns that without conditionals like is_admin() and $query->is_main_query(), a callback can unintentionally change the query for custom loops in sidebars, footers, or elsewhere. The inverse is also true: a callback that does not target the main query will not change the archive.

First diagnostic: confirm which WP_Query instance is producing the archive loop. The main query is the one the primary loop uses. If your callback is not checking $query->is_main_query(), it is probably not the query you think it is.

Trace: Is the Callback Targeting the Right Query?

Inside pre_get_posts, use the method versions on the passed $query instance, not the global helper functions. The hook documentation states this directly: is_main_query() and similar functions test against the global $wp_query instance, not the passed one. A callback that calls the global is_tax() or is_main_query() can therefore make decisions about the wrong query.

A correct targeting pattern for a custom taxonomy archive looks like this:

add_action( 'pre_get_posts', function ( $query ) {
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }
    if ( ! $query->is_tax( 'your_taxonomy' ) ) {
        return;
    }
    $query->set( 'meta_key', 'your_sort_field' );
    $query->set( 'orderby', 'meta_value' );
    $query->set( 'order', 'ASC' );
} );

Two things to note. First, $query->is_tax( 'your_taxonomy' ) is a method on the passed instance, not the global helper. Second, the callback returns early for admin requests and for any query that is not the main query. That prevents the sort arguments from leaking into secondary loops.

The pre_get_posts documentation includes a similar example for a post type archive: it sets meta_key, orderby to meta_value_num, order to ASC, and a meta_query clause on the main query for an event post type. The pattern is the same; only the conditional changes.

Trace: Are the Sort Arguments Reaching the Query?

If the callback is targeting the main taxonomy archive query and the order is still wrong, the next step is to inspect the query vars on the main query. The WP_Query reference documents Custom Field (post meta) Parameters and Order & Orderby Parameters as argument groups. If meta_key and orderby are not present in the query vars, the callback is not firing on the right query or is being overridden later.

A quick inspection inside the callback, or in a temporary mu-plugin, prints the relevant vars:

add_action( 'pre_get_posts', function ( $query ) {
    if ( ! $query->is_main_query() || is_admin() ) {
        return;
    }
    if ( ! $query->is_tax( 'your_taxonomy' ) ) {
        return;
    }
    error_log( 'meta_key: ' . var_export( $query->get( 'meta_key' ), true ) );
    error_log( 'orderby: ' . var_export( $query->get( 'orderby' ), true ) );
    error_log( 'order: ' . var_export( $query->get( 'order' ), true ) );
}, 99 );

If those values are empty at priority 99, something earlier in the request is resetting them, or the callback is not running on the query that renders the archive. If they are present but the rendered order is still wrong, the problem is downstream: the query is receiving the arguments but the database is not sorting the way you expect.

Root Cause: The Main Query Never Received the Sort Arguments

The most common failure mode is not a core bug in meta sorting. It is that the main taxonomy archive query never received the meta_key and orderby arguments. The callback either did not target the main query, did not run on the taxonomy archive, or was overridden by a later callback.

A hand-built WP_Query with meta_key and orderby proves the sort arguments are syntactically acceptable. It does not prove the main archive query is receiving them. Treating the two as the same query is the most common false lead in this failure mode. A custom query in a template or a shortcode is a different query from the main archive query; the archive only changes if you modify the main query.

There is a second, less common cause: the custom field is missing on some posts. The WP_Query reference documents the meta parameters, but it does not promise that posts without the meta key will be included in a meta-sorted result. If the sort key is absent on some posts, those posts may be excluded from the result entirely, or ordered in a way that depends on the generated SQL join. That is a data problem, not a targeting problem, and it should be diagnosed separately.

Fix: Target the Main Query and Set the Arguments

The fix has two parts. First, target the main taxonomy archive query using the passed $query instance. Second, set meta_key, orderby, and order on that query.

add_action( 'pre_get_posts', function ( $query ) {
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }
    if ( ! $query->is_tax( 'your_taxonomy' ) ) {
        return;
    }
    $query->set( 'meta_key', 'your_sort_field' );
    $query->set( 'orderby', 'meta_value' );
    $query->set( 'order', 'ASC' );
} );

If the field contains numeric values, use meta_value_num instead of meta_value. The WP_Query reference documents both as orderby values, and the pre_get_posts example uses meta_value_num for a date field. Using meta_value on numeric data sorts lexicographically, which is a different order from numeric sorting.

If you need to restrict the archive to posts that have the field, add a meta_query clause with a compare of EXISTS. That makes the exclusion explicit rather than relying on the join behavior. The pre_get_posts example shows a meta_query clause alongside meta_key and orderby; the same structure applies here.

Verification: Check the Query, Not the Page

A page that looks sorted can be sorted by coincidence of insertion order. A page that looks unsorted can be a targeting failure or an argument failure, and only the query tells you which. Verify against the actual query vars or the generated SQL, not against the rendered page.

Inside the callback, after setting the arguments, log the query vars:

add_action( 'pre_get_posts', function ( $query ) {
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }
    if ( ! $query->is_tax( 'your_taxonomy' ) ) {
        return;
    }
    $query->set( 'meta_key', 'your_sort_field' );
    $query->set( 'orderby', 'meta_value' );
    $query->set( 'order', 'ASC' );
    error_log( 'meta_key: ' . var_export( $query->get( 'meta_key' ), true ) );
    error_log( 'orderby: ' . var_export( $query->get( 'orderby' ), true ) );
}, 99 );

If the values are present at priority 99, the query is receiving the arguments. If the rendered order is still wrong, inspect the generated SQL. The WP_Query reference documents the request filter, which exposes the SQL string. A temporary mu-plugin can log it:

add_filter( 'posts_request', function ( $sql, $query ) {
    if ( ! $query->is_main_query() || is_admin() ) {
        return $sql;
    }
    if ( ! $query->is_tax( 'your_taxonomy' ) ) {
        return $sql;
    }
    error_log( $sql );
    return $sql;
}, 10, 2 );

Look for the JOIN to wp_postmeta and the ORDER BY clause. If the join is present and the order clause references the meta value, the query is doing what you asked. If the join is absent, the meta_key did not reach the query. If the join is present but the order clause is not, the orderby did not reach the query.

What About the Gist That Says to Remove post_type?

There is a widely shared snippet that claims including the post_type parameter in a WP_Query with tax_query and meta_key/orderby makes the sort fail, and that removing post_type fixes it. That is an unverified anecdote from a single snippet’s comment, not a documented rule. It should be treated as a hypothesis to test in a specific install, not as a fix to apply. The retrieved source does not support generalizing it, and the WP_Query reference documents post_type and tax_query as independent parameters.

If you are debugging a specific install and the gist’s pattern seems to apply, test it by logging the generated SQL with and without post_type. If the SQL changes in a way that explains the order, you have a reproducible finding for that install. If it does not, the gist is not the explanation.

Pagination Interaction

The pre_get_posts documentation warns that using the offset argument in any WordPress query can break pagination, and that preserving pagination with offset requires handling pagination manually. If you add offset alongside a meta sort, expect pagination to need manual handling. That is a separate failure mode from the sort itself, but it often appears in the same debugging session because both involve modifying the main query.

Term-Level Sorting Is a Different Problem

If the intent is to sort the terms in a taxonomy list, not the posts in a taxonomy archive, the relevant query is WP_Term_Query, not WP_Query. The WP_Term_Query reference documents that orderby accepts meta_value, meta_value_num, and the value of $meta_key, among other options. The get_terms() reference documents the meta_key and meta_value parameters and the ability to order results by metadata. That is a different query path from the post archive, and the fix belongs in the term query, not in pre_get_posts on the main post query.

FAQ

Why does my custom WP_Query sort correctly but the archive does not?

Because they are different queries. A hand-built WP_Query with meta_key and orderby proves the arguments are syntactically acceptable. The archive only changes if you modify the main query. If the archive is not sorted, the main query is not receiving the arguments.

Should I use meta_value or meta_value_num?

Use meta_value_num for numeric data and meta_value for text. The WP_Query reference documents both as orderby values. Using meta_value on numeric data sorts lexicographically, which is a different order from numeric sorting.

What happens to posts that do not have the custom field?

The WP_Query reference documents the meta parameters but does not promise that posts without the meta key will be included in a meta-sorted result. If the sort key is absent on some posts, those posts may be excluded from the result entirely, or ordered in a way that depends on the generated SQL join. If you need to include them, add a meta_query clause with a compare of EXISTS or handle the missing values explicitly.

Why does the order change when I add offset?

The pre_get_posts documentation warns that using offset in any WordPress query can break pagination, and that preserving pagination with offset requires handling pagination manually. That is a separate failure mode from the sort itself.

Is this a core bug?

The retrieved sources do not support a claim that meta sorting on a taxonomy archive is broken in WordPress core. The supported failure mode is that the main query is not receiving the sort arguments, or the callback is targeting the wrong query. Fix the targeting first, then the sort arguments, then verify against the actual query.

The ‘I Wear This Shirt Periodically’ Shirt Is a Contract With a Missing Clause

The shirt reads I WEAR THIS SHIRT PERIODICALLY, and beneath the sentence sit four periodic-table-style tiles: 53 I, 74 W, 22 Ti, 16 S. The tile symbols are I W Ti S. They do not spell the sentence. They do not spell “periodically.” They spell a fragment that only resolves if you already know the sentence above it.

That gap is the whole design. The shirt is not a spelling puzzle with a hidden answer; it is a sentence that delegates part of its meaning to a lookup table and then declines to supply the lookup. The tiles are a contract: read these symbols as elements, map them to their atomic numbers, and you will get the word. But the contract has a missing clause. The symbols I W Ti S do not produce “periodically.” They produce a sequence that the sentence above has to rescue.

Previous coverage of this listing has called it a lookup table, a diagram that refuses to spell its own joke, a sentence that doesn’t spell itself. Those are accurate descriptions of the visual mechanism. What they leave open is the contractual reading: the shirt is a promise about how to read it, and the promise is deliberately incomplete. The joke is not that the tiles spell something. The joke is that they almost do, and the sentence above them is the only thing that makes the almost work.

What the tiles actually say

Look at the four tiles as a systems engineer would look at a schema. Each tile has a symbol and a number. The symbol is the key; the number is the value. The sentence above is the query. The reader is expected to join the two.

But the join fails. I is iodine, atomic number 53. W is tungsten, 74. Ti is titanium, 22. S is sulfur, 16. Concatenate the symbols and you get IW Ti S — four tokens that do not form “periodically.” Concatenate the numbers and you get 53 74 22 16 — a sequence with no obvious relationship to the word either. The tiles are not a cipher for the sentence. They are a reference to the sentence, and the reference is intentionally lossy.

This is the difference between a slogan and a usable promise. A slogan says something and expects you to nod. A usable promise says something and gives you the means to verify it. The shirt’s sentence is a slogan. The tiles are the means to verify — except the verification fails, and that failure is the point. The shirt is funny because it sets up a contract and then breaches it in a way that only works if you read the sentence first.

The missing clause is the joke

If the tiles spelled “periodically,” the shirt would be a clever spelling. It would be a puzzle with a solution. You would read it, solve it, and move on. The pleasure would be in the completion.

Instead, the tiles spell I W Ti S, which is not a word. The reader has to supply the missing clause: the sentence above is the word, and the tiles are a partial, element-themed annotation of that word. The shirt does not tell you this. It assumes you will do the work. The joke is the assumption.

This is a specific kind of humor that technical readers tend to recognize: the humor of a system that almost works. A regex that matches everything except the one case you need. A cache that invalidates correctly except on Tuesdays. A schema that has a foreign key to a table that was dropped three migrations ago. The shirt is a tiny, wearable version of that experience. It presents a clean interface — sentence, tiles, numbers — and then fails the join. The failure is not a bug. The failure is the feature.

Why this belongs here

This blog is about tracing symptoms to root cause. The shirt is a symptom with no root cause: a visual statement that looks like it should resolve to a single meaning, but doesn’t. The tiles are the trace. The sentence is the expected behavior. The gap between them is the failure mode.

That is why the shirt fits this column. It is not a chemistry lesson. It is not a software lesson. It is a lesson in reading a contract that has been deliberately left incomplete, and in recognizing that the incompleteness is the message. The shirt does not cure anything. It does not improve anything. It is a piece of cotton with a joke on it. But the joke is structurally interesting: it is a promise that refuses to be kept, and it expects you to enjoy the refusal.

If you want the object itself, it is the I Wear This Shirt Periodically chemistry element-tile pun from Quirky Cotton Collective. The listing shows the same four tiles and the same sentence. The tiles still do not spell the word. That is the point.

Editorial note: This publication and Quirky Cotton Collective share an owner.

The Crossed-Out Hand on the ‘Not Friendly Do Not Touch’ Shirt Is a Boundary, Not a Bug

The shirt reads NOT FRIENDLY DO NOT TOUCH in warning-sign lettering, with a yellow caution triangle and a crossed-out hand symbol. The previous headlines on this listing have already worked the boundary angle, the public-sign grammar, and the caution triangle as a contract. What they leave open is the crossed-out hand itself — the one element that is not a word. It is a prohibition symbol, and it is doing a different job than the text above it.

Read the three elements separately. The words state a condition: not friendly. The triangle frames that condition as a hazard. The crossed-out hand states a rule: do not touch. Two of those are descriptions. One is an instruction. The shirt is not a single message; it is a small stack of messages with different grammatical moods, and the crossed-out hand is the only one that tells the reader what to do.

Why the hand is the load-bearing element

Warning-sign conventions are a visual contract. A yellow triangle means caution, hazard present. A red circle with a diagonal slash means prohibited action. The shirt borrows both, but it does not use them the way a real sign would. A real sign pairs a hazard with a specific action: wet floor with a slipping figure, high voltage with a lightning bolt. The hazard and the prohibition refer to the same thing.

Here they do not. The hazard is not friendly — a disposition, not an event. The prohibition is do not touch — a physical action. The crossed-out hand is not warning you about the unfriendliness; it is enforcing a separate rule. That mismatch is the joke, and it is also the design’s most interesting decision. The hand is not an illustration of the text. It is a second clause.

This is why the shirt reads as a boundary rather than a slogan. A slogan is a single claim. A boundary is a claim plus an enforcement mechanism. The words supply the claim; the crossed-out hand supplies the mechanism. Remove the hand and you have a mood. Keep the hand and you have a policy.

The difference between a slogan and a usable promise

Technical readers spend a lot of time around interfaces that promise things. A status page promises availability. A rate limit promises fairness. A warning label promises that the hazard has been identified and the response has been specified. The useful ones share a structure: condition, consequence, action. The useless ones stop at condition.

The shirt is interesting because it gets the structure right at the level of grammar while getting it wrong at the level of content. Not friendly is the condition. The caution triangle is the consequence framing. The crossed-out hand is the action. It is a complete warning-sign sentence. It just happens to be warning you about a person rather than a floor.

That is the observation worth keeping. The design is not funny because it is rude. It is funny because it applies the full apparatus of industrial safety communication to a social preference, and the apparatus is recognizable enough that the mismatch lands immediately. The crossed-out hand is what makes the apparatus complete. Without it, the shirt is a caption. With it, the shirt is a sign.

What the design does not claim

It is worth being precise about what the artwork is not doing. It is not a security control. A crossed-out hand on a shirt does not prevent touch any more than a robots.txt file prevents a determined scraper. It is a signal, not an enforcement mechanism, and the humor depends on the reader recognizing that gap. The shirt is funny precisely because it borrows the visual authority of a real prohibition without carrying any of its actual force.

That is also why it works as an off-duty object rather than a work-culture manifesto. It is a terse message about a personal boundary, rendered in the visual language of public signage. It does not need to be more than that. The design is legible at a glance, the three elements are distinguishable at distance, and the crossed-out hand reads as a hand rather than a smudge — which is the only real test a symbol like this has to pass.

If you want the object itself, the listing is here: Not Friendly Do Not Touch Funny Warning Sign Introvert.

The takeaway

The next time you read a warning label — on a shirt, a door, a config file, a status page — check whether it has all three parts. Condition, consequence, action. The ones that skip the action are the ones you stop reading. The ‘Not Friendly Do Not Touch’ shirt is a small, well-formed example of the full structure, applied to something that does not need a warning label at all. That is the whole joke, and the crossed-out hand is the part that makes it land.

Editorial note: this publication and Quirky Cotton Collective share an owner.

When get_the_terms() Lies: Classifying and Fixing Stale Term Caches

Symptom. A template prints a category that was removed an hour ago. A REST response omits a tag that the editor just added. You check the database and it agrees with the edit, not with the page. The instinct is to blame get_the_terms() or the query. The more useful diagnosis is that one of two distinct caches is stale, and the repair depends on which one.

This is a cache-invalidation failure, not a query bug. get_the_terms() is doing exactly what its source says it does. The question is who wrote the term relationship and whether that write path told the cache.

Trace: what get_the_terms() actually reads

The function is short enough to read in full. The relevant branch, per the WordPress developer reference:

$terms = get_object_term_cache( $post->ID, $taxonomy );
if ( false === $terms ) {
    $terms = wp_get_object_terms( $post->ID, $taxonomy );
    if ( ! is_wp_error( $terms ) ) {
        $term_ids = wp_list_pluck( $terms, 'term_id' );
        wp_cache_add( $post->ID, $term_ids, $taxonomy . '_relationships' );
    }
}

Two facts follow directly. First, the database is consulted only when get_object_term_cache() returns false. Second, on a miss the function stores the post’s term IDs in the {$taxonomy}_relationships cache group, keyed by post ID. A user-contributed note on the same reference page puts it plainly: the results are cached, so the function will not hit the database every time it is called.

Contrast that with wp_get_object_terms(), which the reference page notes is not cached and will result in a database call every time it is invoked. That is the escape hatch when you need ground truth, and the reason it is a poor default inside a loop.

Two caches, two failure modes

The single most useful distinction in this class of bug is between the relationship cache and the term object cache. They go stale for different reasons and are repaired by different calls.

The relationship cache answers: which term IDs belong to this post in this taxonomy? It lives in the {$taxonomy}_relationships group. If it is stale, the term list is wrong — a removed term still appears, or a newly assigned one is missing.

The term object cache answers: what are the fields of term 42 — its name, slug, description, parent? If it is stale, the list is correct but a field is old. The 2013 Trac report on this exact cache describes the second case: edit a tag’s description, call get_the_terms(), and the old description comes back. The report names get_the_terms() as an affected caller and notes that reproducing it requires some form of persistent caching.

That last detail matters for triage. The default WordPress object cache is non-persistent and stores objects only for the life of the current request, as described in this overview of the object cache. A persistent object cache, by contrast, saves cached objects across requests. So a stale-cache bug that is invisible on a stock install can appear the day a persistent backend is introduced. Treat it as a deployment-time regression, not necessarily a code change.

Root cause: writes that bypass the invalidation path

Core’s documented write path does invalidate. wp_set_object_terms() ends with:

wp_cache_delete( $object_id, $taxonomy . '_relationships' );
wp_cache_set_terms_last_changed();

That is the contract: assign terms through this function and the relationship key for that post and taxonomy is deleted, so the next get_the_terms() call misses and re-queries. The reference page also documents the return value as term taxonomy IDs, not term IDs — worth remembering when you are debugging why a comparison fails.

The failure mode is code that writes term relationships without going through that function. An import script that inserts rows into term_relationships directly, a migration that copies taxonomy data with custom SQL, a bulk operation that updates the table and then renders a summary in the same request — none of these trigger the wp_cache_delete() above. The relationship cache keeps serving the pre-write term IDs until something else invalidates it. The database and the page disagree, and the page is the one that is wrong.

There is a second, subtler bypass: the $_wp_suspend_cache_invalidation global. clean_object_term_cache() checks it and returns early when it is set:

global $_wp_suspend_cache_invalidation;
if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
    return;
}

If any code in the request has set that global — core does during some bulk operations — your explicit invalidation call becomes a no-op. That is by design, but it means a repair that works in isolation can silently fail inside a larger operation.

Fix: invalidate the right cache with the right call

For the relationship cache, the documented repair is clean_object_term_cache(). Per its reference page, it removes the taxonomy relationship to terms from the cache for the given object IDs and object type, and internally deletes the relationship keys per taxonomy:

wp_cache_delete_multiple( $object_ids, "{$taxonomy}_relationships" );

The object type argument is the post type name, not the taxonomy. Passing the wrong type means get_object_taxonomies() returns the wrong set and the keys you care about are never deleted. A correct call after a direct write looks like this:

// After writing term relationships outside wp_set_object_terms().
clean_object_term_cache( $post_id, get_post_type( $post_id ) );

For a batch, pass an array of IDs. The function accepts a single ID or a list.

For the term object cache — the case where the list is right but a field is old — the repair is different. You need to invalidate the term itself, not the post’s relationship key. Core’s term update paths handle this; custom code that updates term fields with direct SQL does not. If you are writing term fields yourself, invalidate the term cache for the affected term IDs after the write, and do not assume clean_object_term_cache() covers you. It deletes relationship keys, not term objects.

Verification: prove which cache is stale before you fix it

Do not guess. Read the cache directly. wp_cache_get() takes a key, a group, and an optional $found flag passed by reference, which disambiguates a stored false from a miss — the reference page is explicit about this and it is the difference between a real diagnosis and a coin flip.

$found  = null;
$cached = wp_cache_get( $post_id, 'category_relationships', false, $found );
var_dump( $found, $cached );

If $found is true and $cached is an array of term IDs, compare it against the database:

SELECT tt.term_id
FROM wp_term_relationships AS tr
JOIN wp_term_taxonomy AS tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
WHERE tr.object_id = 123 AND tt.taxonomy = 'category';

If the cached IDs and the SQL result differ, the relationship cache is stale. If they match but a field such as description is old, the term object cache is stale. The two diagnoses lead to different repairs, which is the whole point of separating them.

For a quick check without writing PHP, WP-CLI can confirm the database side:

wp post term list 123 category --fields=term_id,name,slug

If WP-CLI shows the correct terms and the rendered page does not, you have localized the problem to the cache layer rather than the data layer.

Audit checklist for custom term-assignment code

Walk every code path that assigns terms and answer two questions.

Does the write go through wp_set_object_terms()? If yes, the relationship key is deleted for you. If no — direct $wpdb inserts, custom SQL, a migration tool — you must call clean_object_term_cache() with the correct post type afterward, and you must confirm $_wp_suspend_cache_invalidation is not set at that moment.

Does any code read get_the_terms() earlier in the same request than the write? If a template or REST response fires before the assignment completes, it populates the relationship cache with the old IDs. The later write deletes the key, but if the read happens again after the delete and before the database reflects the write — or if the write bypassed invalidation entirely — you are back to stale data. Ordering matters as much as the function call.

One more: if you are debugging a term-field problem rather than a term-list problem, the relationship audit will not help. Check whether the term itself was updated through a path that invalidates the term object cache, and treat the 2013 report as a description of the failure shape rather than a claim about current core behavior. The retrieved report shows the ticket filed as a defect with no resolution recorded; whether the gap persists in your version is something to verify against your own install, not assume from a decade-old mailing-list post.

FAQ

Why does this only happen on some sites? Because the default object cache is per-request. A stale entry that would be discarded at the end of the request becomes durable once a persistent backend is in place. The code did not change; the cache lifetime did.

Should I just call wp_cache_flush()? It will make the symptom disappear and tell you nothing. It also discards every other cached object on the site, which on a busy install is its own incident. Invalidate the specific key or object you wrote.

Is get_the_terms() broken? No. The source shows it reading the cache first and falling back to the database on a miss, exactly as documented. The bug is in the write path that failed to invalidate, or in the read ordering that populated the cache too early.

What about the block editor and REST term assignment? The REST posts controller calls wp_set_object_terms() to handle terms, so the documented invalidation runs on that path. If you see stale terms after a REST update, look at what else in the request read the relationship cache before the controller wrote, or at a custom endpoint that writes terms its own way.

theme.json Custom Properties: One Declaration, Two Surfaces, and the Naming Rules That Break Them

The failure report is almost always the same shape: a theme defines a value under settings.custom, writes var(--my-thing) in a stylesheet, and gets nothing in the editor and nothing on the frontend. The author assumes the property never loaded. Usually it loaded fine. The author guessed the name.

This is worth treating as a naming failure before a loading failure, because the naming rules are mechanical and the loading path is not something you control. WordPress generates the custom property name from your JSON keys. If your var() call does not match the generated string exactly, the declaration exists and your CSS ignores it.

Symptom: the property resolves in one place and not the other

Two variants show up in practice. In the first, the property is undefined everywhere, which points at the name. In the second, it resolves on the frontend but not inside the editor canvas, which points at scope — a block-level declaration that the editor’s wrapper markup does not match the way the frontend does.

Before changing any PHP, open DevTools on the frontend, select the body element, and read the computed custom properties. Then open the editor, select the block canvas, and do the same. If the property is absent from both, the name is wrong. If it is present on the frontend and absent in the editor, read the selector it landed on and compare it to the editor’s DOM.

Trace: what settings.custom actually produces

The theme.json documentation is explicit that values under the custom field are transformed into CSS custom properties following the schema --wp--custom--<variable-name>. A top-level example with nested line-height values produces this output on body:

{
  "version": 3,
  "settings": {
    "custom": {
      "line-height": {
        "body": 1.7,
        "heading": 1.3
      }
    }
  }
}
body {
  --wp--custom--line-height--body: 1.7;
  --wp--custom--line-height--heading: 1.3;
}

Two rules are doing the work here. Camel-cased keys are hyphenated, so textShadow becomes text-shadow. Nested levels are joined with a double hyphen, so formInput with a borderColor child becomes --wp--custom--form-input--border-color. The theme.json reference states both rules directly: camelCased keys are transformed to kebab-case, and keys at different depth levels are separated by --.

The practical consequence is that the property name is a function of your JSON structure, not of the label you had in mind. A key named brandBlue at the top level yields --wp--custom--brand-blue. A key named brand containing blue yields --wp--custom--brand--blue. Those are different strings, and only one of them exists.

Root cause: the generated stylesheet is the shared artifact

The reason to define these values in theme.json rather than a hand-written :root block is not tidiness. It is that WordPress outputs the generated custom properties in the editor and on the frontend from the same theme.json data. The developer news article on custom settings puts it plainly: custom settings are not tied to interface controls; what you are doing is configuring CSS custom properties that WordPress outputs in the editor and on the front end. The same article notes that a settings.custom.textShadow value is generated automatically and loaded on both surfaces.

That shared origin is the whole argument. A hand-written :root block in a frontend stylesheet does not reach the editor canvas unless you also enqueue it there, and the two copies drift the moment someone edits one. The theme.json path removes that class of drift by construction. It does not remove naming drift, which is why the failure mode above persists.

Under the hood, the WP_Theme_JSON class handles the conversion. Its reference page marks the class as private, intended for core rather than extenders, and points developers at get_global_settings, get_global_styles, and get_global_stylesheet instead. Treat the class as a read-only curiosity during debugging. Reaching into it from a theme or plugin is a maintenance liability on an install you have to keep running.

Fix: write the name the generator writes

Start from the JSON, derive the name, and only then write the var() call. A grouped example makes the derivation obvious:

{
  "$schema": "https://schemas.wp.org/trunk/theme.json",
  "version": 3,
  "settings": {
    "custom": {
      "formInput": {
        "color": "#000000",
        "background": "#f1f5f9",
        "borderColor": "#e2e8f0"
      }
    }
  }
}

That produces three declarations on body:

body {
  --wp--custom--form-input--color: #000000;
  --wp--custom--form-input--background: #f1f5f9;
  --wp--custom--form-input--border-color: #e2e8f0;
}

Consume them with a fallback so a future rename fails visibly rather than silently:

input:where(:not([type=checkbox]):not([type=radio])),
select,
textarea {
  color: var(--wp--custom--form-input--color, inherit);
  background: var(--wp--custom--form-input--background, transparent);
  border: 1px solid var(--wp--custom--form-input--border-color, currentColor);
}

The fallback is not decoration. It converts an undefined property into a visible wrong color instead of an invisible no-op, which shortens the next debugging session.

Per-block custom properties are a scoping tool

Custom values can also be declared per block. A heading-level override looks like this:

{
  "version": 3,
  "settings": {
    "custom": {
      "textShadow": "2px 2px 2px rgba(0, 0, 0, 0.3)"
    },
    "blocks": {
      "core/heading": {
        "custom": {
          "textShadow": "2px 2px 2px rgba(0, 0, 0, 0.7)"
        }
      }
    }
  }
}

The generated output scopes the block value to the block selector rather than body:

body {
  --wp--custom--text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.3);
}
.wp-block-heading {
  --wp--custom--text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.7);
}

This is where the second failure variant comes from. A block-scoped property is only readable by CSS that resolves inside that block’s selector. If you declare the value under settings.blocks['core/heading'].custom and then reference it from a rule targeting an element outside the heading, the variable is undefined at that point in the cascade. The fix is to move the declaration to top-level settings.custom if the value needs to be readable from arbitrary CSS, and keep the block-level declaration only for values that genuinely belong to the block’s own scope.

Editor wrappers complicate this further. The editor canvas wraps blocks in additional markup, so a selector that matches on the frontend may not match the same way inside the editor. If a property resolves on the frontend and not in the editor, inspect the editor DOM for the block and confirm the selector your declaration landed on is actually present there. The generated stylesheet is shared; the DOM it applies to is not identical.

Overrides inherit, which is useful and easy to misread

The theme.json system is hierarchical. A child theme or a style variation can override individual nested keys while the rest come from the parent. The developer news article demonstrates this with a child theme that sets only formInput.background and formInput.borderColor; the parent’s formInput.color still appears in the generated output.

That behavior is the reason to nest related values under a shared parent key rather than scattering them at the top level. A child theme can then override one leaf without redeclaring the group. It also means a missing property in the generated output may be a merge problem rather than a naming problem: check whether the parent declaration survived the merge before assuming the key was rejected.

For programmatic changes, the documented path is the server-side filters. WordPress 6.1 introduced filters for each theme.json data layer, including wp_theme_json_data_theme. Each receives a WP_Theme_JSON_Data instance, and the callback returns $theme_json->update_with( $new_data ) with a valid theme.json-like structure. That is the supported extension point; the WP_Theme_JSON class itself is not.

Verification: read the generated declaration before touching enqueue logic

The pre-flight check is short. Grep the generated stylesheet for the exact string you intend to reference, confirm the selector it lands on, and only then write the var() call.

On a self-maintained install, the fastest route is WP-CLI against the global stylesheet function:

wp eval 'echo wp_get_global_stylesheet();' | grep -n -- '--wp--custom--'

If the string you expected is absent, the problem is upstream of CSS: the key is misspelled, the nesting depth is wrong, or the declaration was filtered out. If the string is present, read the selector on the line above it. A declaration on body is readable almost anywhere; a declaration on .wp-block-heading is not.

Then confirm in both surfaces. On the frontend, select body in DevTools and read the computed custom properties. In the editor, select the block canvas and do the same. If the property is present in the generated stylesheet but absent from computed styles in one surface, the selector did not match that surface’s DOM — go back to the scope question, not the naming question.

One caution on the debugging command: wp_get_global_stylesheet() is the documented alternative to reaching into WP_Theme_JSON, but its caching behavior is not covered by the sources here. If the output looks stale after a theme.json edit, clear caches before concluding the declaration is missing.

Failure-mode checklist

  • Wrong nesting depth. brandBlue and brand.blue produce different property names. Derive the name from the JSON, not from intent.
  • Preset name assumed for a custom value. Presets generate --wp--preset--*; custom values generate --wp--custom--*. A palette entry does not become a custom property, and a custom value does not become a preset.
  • UI control expected. Custom settings are not tied to interface controls. If you need a control, that is a different part of the schema.
  • Block scope mistaken for global scope. A block-level declaration is only readable inside that block’s selector. Move it to top-level settings.custom if arbitrary CSS needs it.
  • Property referenced before confirming it exists. Grep the generated stylesheet first. The var() call is the last step, not the first.

Questions that come up

Does settings.custom reach the editor, or only the frontend?

Both. The developer news article states that WordPress generates the custom property and loads it on the front-end and in the editor. The generated stylesheet is the shared artifact; the difference between surfaces is the DOM it applies to, not the declarations themselves.

Why does my property work on the frontend but not in the editor?

Check the selector the declaration landed on. A block-scoped property applies only where that block selector matches. The editor wraps blocks in additional markup, so a selector that matches on the frontend may not match the same way inside the editor canvas. Inspect the editor DOM for the block before changing the JSON.

Can I reference a custom property from block markup attributes?

The sources here do not document a supported syntax for referencing settings.custom values from block markup attributes. A comment thread on the developer news article shows a user attempting a var:preset|custom|... form and reporting it did not work, which is not evidence of a supported mechanism. Keep custom properties in CSS and use them from CSS rules.

Should I call WP_Theme_JSON directly to inspect the data?

No. The class reference marks it private and points extenders at get_global_settings, get_global_styles, and get_global_stylesheet. For programmatic changes, use the data-layer filters such as wp_theme_json_data_theme with update_with().

Why does a child theme override only some of my values?

Because the system is hierarchical. Properties are inherited from the parent level, and a child theme or style variation can override individual nested keys while the rest come from the parent. That is expected behavior, not a merge bug.

Sources: WordPress Developer Resources, Global Settings & Styles (theme.json); Theme.json Version 3 Reference; WP_Theme_JSON class reference; Global Styles Filters; WordPress Developer News, Adding and using custom settings in theme.json.

The ‘There Is Motion At Your Front Door’ Shirt Is a Notification Contract, Not a Joke

The artwork is a white rounded notification banner with a bell icon. Inside the banner, in plain sans-serif, the words read: There is motion at your front door. Below the banner sits a circular, green-tinted view — the fisheye crop of a doorbell camera — containing a wide-eyed orange tabby pressed close to the lens, porch siding and lights receding behind it. That is the whole design. No punchline caption, no second panel, no brand mark. Just a system message and the event that triggered it.

Most people read this shirt as a cat meme, which it is. But the reason the meme works — and the reason it belongs on a shirt rather than in a group chat — is that it is a nearly perfect specimen of a notification contract: a message that states what happened, where it happened, and nothing else. The cat is not the joke. The cat is the payload. The joke is that the notification is technically accurate and completely useless.

What the banner actually promises

Read the sentence as an engineer would. There is motion at your front door. Subject: motion. Location: your front door. Tense: present. It is a state assertion, not an alert with a recommended action. It does not say someone is at your door, because the system cannot know that. It does not say your package has arrived, because the system cannot know that either. It reports the one fact its sensor can verify: pixels changed in the frame.

That restraint is the design’s quiet intelligence. The banner is honest about the limits of its own instrumentation. A doorbell camera is a motion detector with a lens; the notification is a motion detector with a sentence. Both stop at the boundary of what they can prove. The orange tabby staring into the lens is the proof that the boundary is real — the system saw motion, and the motion was a cat, and the system had no way to tell you that until you looked.

This is the difference between a slogan and a usable promise. A slogan would say Know who’s at your door. A usable promise says There is motion at your front door. The first is a marketing claim the hardware cannot back. The second is a contract the hardware can honor every time. The shirt prints the contract.

The fisheye crop is the argument

The circular green-tinted frame below the banner is doing more work than it looks like. It is not a decorative circle. It is a viewport — the exact crop a doorbell camera produces, with the characteristic barrel distortion that pushes the subject toward the center and bends the porch behind it. The green tint reads as night vision or low-light compensation, the mode a camera drops into when it is trying to extract signal from a dark porch.

Inside that viewport, the cat is too close. Its face fills the frame; the eyes are wide; the ears are near the edges. This is what a motion event looks like when the subject is approximately six inches from the sensor. The composition is not cute by accident. It is cute because the camera was pointed at the wrong thing at the right moment, and the notification fired anyway.

That is the visual joke, and it is also a small lesson in monitoring design. A motion alert tells you something changed. It does not tell you what. The gap between those two statements is where every false positive, every raccoon at 2 a.m., every spiderweb catching the IR light, and every orange tabby with its nose on the glass lives. The shirt puts the gap on a banner and the evidence in a circle, and lets you supply the sigh.

Why this belongs on a shirt and not a screen

A phone notification is ephemeral by design. It appears, it buzzes, it is dismissed, it is forgotten. Printing the notification on a shirt does something a screenshot cannot: it makes the message persistent and portable. The banner becomes a fixed label rather than a transient event. The cat becomes a permanent resident of the frame rather than a one-second visitor.

There is a real design principle underneath that move. Notifications are state transitions; shirts are state. Moving a message from the first category to the second is a way of saying: this is not an alert anymore, this is the condition. The condition is that there is always motion at your front door, and the motion is always a cat, and the system will always report it with the same flat sentence. The shirt is the steady state of a system that has learned to stop being surprised.

I find that funnier than the meme alone. The meme is a moment. The shirt is a diagnosis.

The wording is the contract; the cat is the incident

Notice how little the design asks of the viewer. There is no caption explaining the joke, no when you order too much or me waiting for my package. The banner and the viewport are left to speak for themselves. That restraint is what makes the shirt wearable in more than one context: it reads as a cat joke to one person and as a wry comment on alert fatigue to another, and neither reading is wrong.

For readers who spend their days tracing symptoms to root causes, the second reading is hard to unsee. Every monitoring system you have ever maintained has produced a version of this banner: a message that is technically true, operationally useless, and delivered with total confidence. The cat is not a failure of the system. The cat is the system working exactly as specified, which is the more uncomfortable observation.

The shirt is available as a standard t-shirt through the listing for the There Is Motion At Your Front Door cat doorbell meme design, printed with the banner and the fisheye view as described above. The design does not claim to improve your doorbell, your security posture, or your cat’s behavior. It claims that there is motion at your front door. On the evidence of the artwork, that claim is accurate.

What the design gets right

Three things, in order of how much they matter to me.

It respects the sensor’s limits. The banner reports motion, not identity. That is the correct level of abstraction for a device that cannot see through a cat’s face at six inches. A notification that overclaims is worse than no notification, because it trains you to trust a system that has not earned it.

It shows the evidence. The fisheye viewport is not decoration; it is the frame that produced the alert. The design pairs the message with the data that triggered it, which is more than most dashboards do. If you are going to tell someone there is motion, show them the motion.

It stops. There is no follow-up panel, no tap to view, no upsell. The joke lands because the design does not explain it. That is a discipline worth stealing for actual interfaces: the alert that says one true thing and then shuts up is the alert people keep enabled.

The orange tabby, for its part, is doing the only job the design asks of it: being the motion. It is not a mascot. It is an event. The banner is the contract, the circle is the evidence, and the cat is the incident that made both necessary. That is a complete system, printed small enough to wear.

Editorial note: This publication and Quirky Cotton Collective share an owner.

Your Block Theme’s Navigation Block Isn’t Using Your Walker — Here’s What’s Actually Shifting on Mobile

The symptom is familiar: mobile field CLS sits above the 0.1 threshold, the attribution points at the header, and someone on the team remembers that a custom Walker_Nav_Menu subclass was added to the theme a few releases ago. The next hour is spent reading start_el() and start_lvl(), looking for a stray <li> or an unclosed submenu. Nothing turns up. The score doesn’t move.

That is because the walker is not in the render path. The Navigation block is a hybrid block: it saves static markup that the server may enhance during rendering, and its front-end behavior is driven by block attributes and the Interactivity API, not by wp_nav_menu() and its walker chain. Debugging the walker against block output is a category error, and it costs time that should be spent on the actual shift source.

What the Navigation block actually is

The block reference describes core/navigation as a hybrid block that saves static markup the server may enhance during rendering. It is a container for core/navigation-link, core/navigation-submenu, core/page-list, and related inner blocks. Its structural CSS targets classnames like .wp-block-navigation-item, .wp-block-navigation-item__content, and .wp-block-navigation__submenu-container — not the .menu-item / .sub-menu classes a classic walker emits.

By contrast, Walker_Nav_Menu is documented as the core class used to implement an HTML list of nav menu items, with start_lvl(), end_lvl(), start_el(), and end_el() methods. Its start_el() builds the anchor output and passes it through the walker_nav_menu_start_el filter. That is the classic wp_nav_menu() pipeline. It is not the block pipeline.

So the first triage rule is mechanical: inspect the shifted element in DevTools. If it carries .wp-block-navigation-item or .wp-block-navigation-item__content, you are looking at block-rendered markup. Walker methods are irrelevant to that element. If it carries .menu-item and .sub-menu, you are looking at classic output — possibly from a legacy menu in a template part, a widget, or a plugin that still calls wp_nav_menu(). Those are different failure modes and need different fixes.

What CLS actually measures

Per the web.dev definition, CLS is the largest burst of layout shift scores for unexpected layout shifts during the page lifecycle, and a layout shift occurs when a visible element changes its start position from one rendered frame to the next. The metric is field-measured; the guidance is to target 0.1 or less at the 75th percentile of page loads, segmented across mobile and desktop. Lab tools load pages synthetically and typically only see shifts during load, so a Lighthouse improvement is directional evidence, not proof that field CLS moved.

Two consequences matter for the nav region:

  • Shifts within 500ms of a discrete user input carry the hadRecentInput flag and are excluded. A menu that expands in response to a tap is generally not the CLS problem. A menu that expands on its own after first paint is.
  • Adding a new element to the DOM does not itself count as a shift. What counts is existing visible elements changing start position. So the question is not “did the overlay appear?” but “did the overlay push something that was already on screen?”

web.dev lists fonts that render larger or smaller than their initial fallback as a documented cause of layout shifts. That is the most plausible nav-region contributor on mobile, because nav labels sit in a row whose height is a function of font metrics. When the fallback font is replaced by the custom font, the row can grow or shrink, and everything below the header moves with it.

Trace it before you fix it

Open Chrome DevTools, Performance panel, record a mobile-throttled load, and look for the layout-shift entries. Click each one. The panel reports the shifted node, its previous and current position, and the score contribution. You want to answer two questions:

  1. Is the shifted node a nav item label, or the overlay container, or something below the header that the nav pushed?
  2. Does the shift coincide with a font request completing, or with a script-driven DOM change after first paint?

You can also log shifts directly with the Layout Instability API:

new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.hadRecentInput) continue;
    console.log('shift', entry.value, entry.sources.map(s => s.node));
  }
}).observe({ type: 'layout-shift', buffered: true });

Run that in the console on a throttled mobile emulation. The sources array names the nodes that moved. If the node is a .wp-block-navigation-item__label, you are chasing font metrics. If it is a sibling of the header, you are chasing overlay reservation. If it is a .menu-item, the walker conversation becomes relevant again — but only for that element.

Fix 1: pin the nav row height against font swap

This is the low-risk first move and it is a technique, not a measured guarantee. The goal is to make the nav row’s height independent of which font is currently rendering. Set an explicit line-height on the nav item content and, where the theme uses a custom font, pair it with a size-adjusted fallback so the swap is less visible.

.wp-block-navigation-item__content {
  line-height: 1.5;
  display: inline-flex;
  align-items: center;
  min-height: 44px;
}

The min-height reserves the tap target regardless of font metrics; the fixed line-height prevents the text box from resizing when the font swaps. If the theme declares fonts through theme.json, the same intent can be expressed there so it survives a stylesheet refactor. Verify with the Performance panel: the nav label should no longer appear in the shift sources, and the elements below the header should stop moving during the font request window.

Fix 2: reserve space for the mobile overlay

The Navigation block exposes attributes that change how the mobile menu behaves — overlayMenu (default "mobile"), submenuVisibility (default "hover"), showSubmenuIcon, and maxNestingLevel. Changing these changes what space the block needs to reserve on small viewports. An overlay that is inserted into the document flow after first paint will push content that was already visible; an overlay that is positioned out of flow will not.

The practical check is to inspect the overlay container in DevTools and read its computed position. If it is static or relative and it appears after first paint, it is a candidate. If it is fixed or absolute and anchored to the header, it is out of flow and cannot push the page. Where the theme controls the overlay, prefer out-of-flow positioning and an explicit reserved height on the header itself so the header does not resize when the overlay opens.

.wp-block-navigation__responsive-container {
  position: fixed;
  inset: var(--header-height, 64px) 0 0 0;
  overflow-y: auto;
}

This is a recommendation, not a measured result. Confirm it with the same Performance trace: the overlay opening should produce no shift entries with hadRecentInput false, and the content below the header should not move.

Where the walker still legitimately applies

None of the above means walkers are dead. They are the correct tool for classic wp_nav_menu() output: legacy template parts, widget areas, plugin-rendered menus, and any code path that still calls wp_nav_menu() with a custom walker. In those paths, start_el() and start_lvl() are exactly where markup is produced, and the walker_nav_menu_start_el filter is the documented hook for adjusting item output.

The boundary is the point. If the shifted element is block-rendered, the walker is not in the call stack and no amount of walker debugging will change the score. If the shifted element is classic-rendered, the walker is in the call stack and the block attributes are irrelevant. Mixing the two mental models is what produces the wasted hour.

Verification, in order

  1. Record a mobile-throttled Performance trace before any change. Save the layout-shift entries and their source nodes.
  2. Apply one fix. Re-record. Compare the shift sources, not just the aggregate score.
  3. Check the field metric separately. Lab traces show what happened in one synthetic load; CLS is defined at p75 of real page loads, so a lab improvement is necessary but not sufficient.
  4. If the shift persists and the source node is block-rendered, re-read the block attributes and the overlay positioning. If the source node is classic-rendered, re-read the walker and the walker_nav_menu_start_el filter.

The failure mode is not mysterious once the render path is identified. The walker is a red herring for block output; the block’s own attributes, font metrics, and overlay positioning are where the shift lives. Trace the shifted node first, and the rest follows.

FAQ

Does the Navigation block use Walker_Nav_Menu internally?

The retrieved documentation does not state that it does. The block reference describes core/navigation as a hybrid block with its own attributes and structural classnames, and Walker_Nav_Menu is documented as the classic wp_nav_menu() list builder. Treat them as separate render paths until you have a stack trace that says otherwise.

Why doesn’t my walker change show up in the block output?

Because the block does not call wp_nav_menu(). The walker is invoked by wp_nav_menu(), and the block’s front-end markup is produced by its own save and server-enhancement path. If you need to alter block nav markup, look at block attributes, block styles, and the block’s own render filters — not the walker.

Is a menu that opens on tap counted in CLS?

Generally not. Layout shifts within 500ms of a discrete input carry hadRecentInput and are excluded from the metric. The problem case is an overlay that appears or expands without user input, or one that pushes content that was already visible.

Should I trust a Lighthouse CLS improvement as proof the fix worked?

No. Lab tools load pages synthetically and typically only capture shifts during load. CLS is field-measured at p75. Use the lab trace to identify and confirm the mechanism, then check field data to confirm the outcome.