Why wp_insert_term() Says a Term Exists When the Admin Shows Nothing

Symptom

You call wp_insert_term( 'News', 'category', array( 'parent' => 12 ) ) from a plugin, an import script, or a REST callback. It returns a WP_Error with code term_exists and the message “A term with the name provided already exists with this parent.” You open Posts → Categories, filter to parent 12, and see nothing named News. The admin list is empty. The function insists otherwise.

Both observations are correct. They are answers to different questions. The duplicate check inside wp_insert_term() asks whether a term with this name, taxonomy, and parent exists anywhere in the database. The admin screen asks a narrower question shaped by screen options, pagination, and the hide_empty default. When those two answers diverge, the error is authoritative and the screen is not.

Trace: read the error object before you read the database

WP_Error stores a code, one or more messages, and optional data. The term_exists error is constructed with the colliding term’s ID as its data argument. That ID is the single most useful fact in the whole failure, and it is the one most people skip past.

$result = wp_insert_term( 'News', 'category', array( 'parent' => 12 ) );

if ( is_wp_error( $result ) ) {
    error_log( 'code: ' . $result->get_error_code() );
    error_log( 'message: ' . $result->get_error_message() );
    error_log( 'data: ' . var_export( $result->get_error_data(), true ) );
}

Per the WP_Error reference, get_error_data() retrieves the most recently added error data for a code. For term_exists, that data is the existing term’s term_id. Once you have it, you can stop searching the admin UI and start inspecting the row directly.

$term_id = $result->get_error_data();
$term    = get_term( (int) $term_id, 'category' );

if ( $term && ! is_wp_error( $term ) ) {
    error_log( sprintf(
        'id=%d name=%s slug=%s parent=%d count=%d taxonomy=%s',
        $term->term_id,
        $term->name,
        $term->slug,
        $term->parent,
        $term->count,
        $term->taxonomy
    ) );
}

If get_term() returns a valid object, the term exists. The remaining question is why the admin screen did not show it. If get_term() returns null or a WP_Error, the collision is not a database row at all — see the pre_insert_term section below.

Trace: the duplicate check inside wp_insert_term()

The wp_insert_term() reference documents the contract plainly: “If the term already exists on the same hierarchical level, or the term slug and name are not unique, a WP_Error object will be returned.” The source shows the mechanism. After sanitizing the name and deriving a slug, core runs:

$name_matches = get_terms( array(
    'taxonomy'             => $taxonomy,
    'name'                 => $name,
    'hide_empty'           => false,
    'parent'               => $args['parent'],
    'update_term_meta_cache' => false,
) );

Two details matter. First, hide_empty is explicitly false, so the duplicate check sees terms with a post count of zero that the admin list may not display. Second, the query is scoped by parent, so a same-named term under a different parent is not returned by this query — but the subsequent slug check is not scoped the same way.

Core then performs a stricter comparison than get_terms() does, because the name argument does not differentiate accented characters. The source comment is explicit: “The name match in get_terms() doesn’t differentiate accented characters, so we do a stricter comparison here.” The loop compares lowercased names for exact equality and keeps the first match.

If a name match is found, core resolves the slug with get_term_by( 'slug', $slug, $taxonomy ) and then branches on hierarchy:

  • Hierarchical taxonomies (categories, custom hierarchical taxonomies): core fetches all siblings under the requested parent and checks whether the name or slug is already present among them. If so, it returns term_exists with the message “A term with the name provided already exists with this parent.”
  • Non-hierarchical taxonomies (tags, most custom flat taxonomies): core returns term_exists with the message “A term with the name provided already exists in this taxonomy.”

Those two messages are not cosmetic. They tell you which branch fired and therefore where to look. The hierarchical message means the collision is at the requested parent level. The flat message means the collision is taxonomy-wide.

Root cause: the collision is real, the visibility is not

The error and the admin screen disagree because they query differently. The duplicate check uses hide_empty => false and an explicit parent. The admin term list is a WP_Term_Query whose defaults, per the WP_Term_Query reference, include 'hide_empty' => true. The admin screen also applies screen options for per-page counts and can be filtered by plugins. Any of the following will produce a term that exists, blocks insertion, and does not appear where you are looking:

  1. Zero-count term. The term exists with count = 0. The duplicate check sees it because hide_empty is false. The admin list hides it because hide_empty defaults to true. This is the most common cause and the easiest to confirm.
  2. Different parent. A term named News exists under parent 7, not parent 12. The get_terms() name query is scoped to parent 12 and returns nothing, but the slug check via get_term_by( 'slug', $slug, $taxonomy ) is not parent-scoped. If the derived slug matches, the hierarchical branch can still resolve an existing term and return the error. Inspect the returned term_id‘s parent before assuming the admin list is wrong.
  3. Slug collision across the taxonomy. The name is new, but the slug derived from it (sanitize_title( $name )) already belongs to a different term in the same taxonomy. The name match may be absent, but the slug path can still produce a collision depending on which branch evaluates. wp_unique_term_slug() normally resolves this by appending a parent slug or a numeric suffix, but the duplicate check runs before that function is called, so a pre-existing slug can short-circuit insertion first.
  4. Admin screen filters. A plugin can filter the term list query on the edit-tags screen. The term is present in the database and visible to get_terms() with hide_empty => false, but excluded from the rendered list. This is a visibility problem, not a data problem.

None of these is a core defect. The duplicate check is doing what the documentation says it does. The admin screen is doing what its query arguments say it does. The bug is in the assumption that the two views are equivalent.

Root cause: pre_insert_term can fabricate the error

There is a second path to the same error code that involves no database row at all. Before sanitization, wp_insert_term() runs:

$term = apply_filters( 'pre_insert_term', $term, $taxonomy, $args );
if ( is_wp_error( $term ) ) {
    return $term;
}

The pre_insert_term reference describes the filter as running “before it is sanitized and inserted into the database.” A plugin can return a WP_Error from this filter with any code and message it likes, including term_exists. If your get_error_data() returns an ID that get_term() cannot resolve, or returns nothing at all, suspect a filter before you suspect the database.

To confirm, temporarily remove filters and retry:

remove_all_filters( 'pre_insert_term' );
$result = wp_insert_term( 'News', 'category', array( 'parent' => 12 ) );
// Restore or re-add your filters afterward.

If the insertion now succeeds, the error was manufactured by a filter. If it still fails, the collision is in the database and you can proceed to the SQL checks below.

Diagnostic sequence

Work in this order. Each step narrows the next.

1. Capture the error data

Log get_error_code(), get_error_message(), and get_error_data() as shown above. The message variant tells you hierarchical versus flat. The data tells you the term ID, if any.

2. Resolve the term ID

Call get_term( $term_id, $taxonomy ) and log name, slug, parent, count, and taxonomy. If the object is valid, the term exists. If it is null, the error came from a filter.

3. Query the database directly

Bypass the object cache and the admin screen. Replace the prefix and taxonomy as needed:

SELECT t.term_id, t.name, t.slug, tt.taxonomy, tt.parent, tt.count
FROM wp_terms AS t
INNER JOIN wp_term_taxonomy AS tt ON tt.term_id = t.term_id
WHERE tt.taxonomy = 'category'
  AND ( t.name = 'News' OR t.slug = 'news' );

This returns every row the duplicate check could match, regardless of parent or count. If it returns a row with count = 0, you have confirmed the zero-count case. If it returns a row with a different parent, you have confirmed the parent-scoping case. If it returns nothing, the error is not a database collision.

4. Check for orphaned term_taxonomy rows

A wp_terms row without a matching wp_term_taxonomy row, or a term_taxonomy row pointing at a missing term, can produce confusing results. The join above will not surface a term row with no taxonomy row. Run both directions:

-- Terms with no taxonomy row
SELECT t.term_id, t.name, t.slug
FROM wp_terms AS t
LEFT JOIN wp_term_taxonomy AS tt ON tt.term_id = t.term_id
WHERE tt.term_id IS NULL;

-- Taxonomy rows with no term row
SELECT tt.term_taxonomy_id, tt.term_id, tt.taxonomy
FROM wp_term_taxonomy AS tt
LEFT JOIN wp_terms AS t ON t.term_id = tt.term_id
WHERE t.term_id IS NULL;

Orphaned rows are not a normal state, but they occur after partial imports, manual SQL edits, or interrupted migrations. If you find one, resolve it before retrying the insertion.

5. Check with WP-CLI

WP-CLI gives you the same view without opening a database client:

wp term list category --name=News --fields=term_id,name,slug,parent,count --format=table
wp term get category <term_id>
wp term list category --slug=news --fields=term_id,name,slug,parent,count

If wp term list returns the term but the admin screen does not, the term exists and the admin query is filtering it out. If wp term list returns nothing, the collision is not a term row and you should return to the pre_insert_term check.

6. Inspect the admin query

If you need to prove the admin screen is filtering the term, hook get_terms_args temporarily and log the arguments for the edit-tags screen. The WP_Term_Query reference documents hide_empty as defaulting to true, and the admin list inherits that default unless a screen option or plugin changes it. A term with count = 0 will not appear under the default. That is the whole explanation in most cases.

Fix

The fix depends on which cause you confirmed. There is no single patch.

  • Zero-count term: If the existing term is the one you want, use it. Call get_term_by( 'name', 'News', 'category' ) or use the ID from the error data and assign posts to it. If you genuinely need a second term with the same name under the same parent, you cannot have one — core prevents it by design. Rename one of them or restructure the hierarchy.
  • Different parent: Decide whether the existing term should move. If so, use wp_update_term( $term_id, 'category', array( 'parent' => 12 ) ). If not, choose a different name for the new term. The duplicate check is not going to let you create a sibling with the same name under a different parent if the slug path collides.
  • Slug collision: Pass an explicit slug argument that does not collide, or let wp_unique_term_slug() do its job by not passing a slug at all. The wp_unique_term_slug() reference documents that it appends a parent slug and then a numeric suffix until the slug is unique. If you are passing a slug manually, you are bypassing that safety net.
  • pre_insert_term filter: Find the callback. Search your plugin and theme code for add_filter( 'pre_insert_term'. If it is returning a WP_Error for a legitimate reason, handle the error at the call site. If it is returning one incorrectly, fix or remove the filter.
  • Orphaned rows: Delete the orphaned row after confirming it is not referenced. Back up first. Orphaned rows are a data integrity problem, not a WordPress behavior problem.

Verification

After applying a fix, verify in three places, not one.

  1. The function call. Retry wp_insert_term() and confirm it returns an array with term_id and term_taxonomy_id, not a WP_Error. Log the return value; do not assume success from the absence of an exception.
  2. The database. Re-run the join query from step 3. Confirm exactly one row matches the name or slug in the target taxonomy, and that its parent and count are what you expect.
  3. The admin screen. Reload Posts → Categories. If the term has count = 0, it may still not appear under the default view. That is expected. Confirm visibility with wp term list or by assigning a post to the term and reloading.

If all three agree, the failure is resolved. If the function succeeds but the admin screen still hides the term, you have a visibility problem, not an insertion problem, and the two should be debugged separately.

FAQ

Why does the error say “with this parent” when the term is under a different parent?

The hierarchical branch fetches siblings under the requested parent and checks names and slugs among them. If the slug check via get_term_by( 'slug', $slug, $taxonomy ) resolves a term elsewhere in the taxonomy, the branch can still return the hierarchical message. The message describes the branch that fired, not necessarily the location of the colliding row. Always inspect the term_id in the error data.

Can a term exist in the database but be invisible to get_term()?

Yes, if the wp_terms row exists without a matching wp_term_taxonomy row. get_term() resolves through the taxonomy table, so a bare term row is not a valid term object. The duplicate check queries through get_terms(), which joins the taxonomy table, so a bare term row should not trigger term_exists on its own. If you suspect orphaned rows, run the left-join queries above.

Does the object cache affect the duplicate check?

wp_insert_term() passes update_term_meta_cache => false to its internal get_terms() call, but term queries can still be served from the object cache depending on the cache backend and the cache_results argument. If you suspect stale cache, flush the term cache for the taxonomy with clean_term_cache( $term_id, $taxonomy ) or use wp cache flush, then retry. Do not treat cache as the first suspect; confirm the database row first.

Is there a way to allow duplicate names?

Core does not provide a supported filter to disable the duplicate-name check. The wp_insert_term_duplicate_term_check filter, documented in the wp_insert_term() reference, runs after insertion and handles a different case: it detects a duplicate created by a race condition and returns the older term’s IDs. It does not bypass the pre-insert name check. If you need duplicate names, you are working against the function’s contract and should reconsider the data model.

Related reading

If you are debugging a fresh install where the front end returns nothing at all, the failure modes are different but the diagnostic discipline is the same: What to Fix First When a New WordPress Site Says Nothing Found.

The ‘Not Friendly Do Not Touch’ Shirt Is a Warning Label With No Failure Mode

Three elements, read left to right: a yellow caution triangle, a hand with a diagonal slash through it, and the words NOT FRIENDLY stacked above DO NOT TOUCH. The triangle is the standard-issue hazard shape — the one that means something here can hurt you. The crossed-out hand is the standard-issue prohibition glyph — the one that means do not put your hand here. The lettering is blunt, all caps, no punctuation, no please.

What interests me is not the joke. It is the grammar. This is a shirt that borrows the visual contract of industrial signage and applies it to a person. And that contract, read closely, is broken — not in a way that ruins the joke, but in a way that makes the joke work. The shirt is a warning label with no failure mode specified.

What the sign promises, and what it doesn’t

A real caution triangle is a contract. It says: a specific hazard exists in this area, and here is the class of harm. Wet floor. High voltage. Hot surface. The triangle is meaningless without the thing it points at. The crossed-out hand is the same: it prohibits a specific interaction with a specific object. Do not touch the moving parts. Do not touch the hot element. The prohibition is only legible because the object behind it is defined.

On this shirt, the object is a person. The hazard is not friendly. The prohibited action is touch. But not friendly is not a hazard class. It is a disposition. It does not tell you what will happen if you proceed; it tells you what the wearer is. The sign has the shape of a warning and the content of a mood.

That mismatch is the entire design. The caution triangle and the crossed-out hand do the work of making the message look official, and the words undercut the officialness by being about a personality rather than a physical risk. It is a category error performed in Helvetica-adjacent caps, and the category error is the punchline.

The difference between a slogan and a usable promise

I spend a lot of working hours thinking about contracts — the kind that hold between a hook and a caller, a filter and its return value, a table and the code that reads it. A contract is usable when it specifies what happens at the boundary. This function returns a string or false. This endpoint requires authentication. This column is nullable. The value of a contract is that it lets you predict behavior without reading the implementation.

A warning sign is a contract in the same sense. Do not touch is usable because it tells you what to do at the boundary: keep your hand on your side of it. The hazard class tells you why. Together they let a stranger navigate the object without knowing anything about it.

NOT FRIENDLY / DO NOT TOUCH is not that. It is a slogan wearing a contract’s clothes. It tells you the boundary exists but not what crossing it does. Will the wearer be rude? Silent? Leave? Glare? The sign does not say. It asserts a disposition and prohibits an action, and leaves the causal link between them as an exercise for the reader.

That is fine for a shirt. It would be a disaster for an API. The reason the shirt is funny is precisely the reason the sign would fail as documentation: it has the form of a specification and the content of a preference.

Why the crossed-out hand is the load-bearing element

Strip the hand away and you have a yellow triangle with NOT FRIENDLY in it. That is a mood. It is a statement about the wearer, and it is roughly as informative as a status message that says busy. It tells you something is true but not what to do about it.

The crossed-out hand converts the mood into an instruction. It is the only element on the shirt that specifies an action. Do not touch. The triangle frames it as a hazard; the hand makes it a rule. Without the hand, the shirt is a personality claim. With the hand, it is a boundary.

That is the part I find genuinely well-constructed. The design does not rely on the words to carry the boundary. The words carry the attitude; the glyph carries the instruction. The two are doing different jobs, and the joke lives in the gap between them — the gap where a real sign would have specified the hazard and this one has specified a temperament instead.

What the shirt is actually useful for

I am not going to pretend this is a productivity tool or a communication breakthrough. It is a shirt with a joke on it. But the joke is doing something specific that a lot of workplace communication fails to do: it states a boundary in the imperative and lets the reader decide whether to take it seriously.

Most boundary language in offices is hedged into uselessness. I’m heads-down today. I might be slow to respond. Let me know if it’s urgent. That is a preference dressed as a status, and it invites negotiation. The shirt does the opposite. It uses the imperative mood and the visual vocabulary of a hazard sign, and it does not apologize. Whether that is a good way to run a team is a separate question. Whether it is a legible way to state a boundary is not: it is.

The shirt is available as a standard t-shirt from Quirky Cotton Collective — the listing is here — and the design is exactly what the observation records: the warning-sign lettering, the yellow caution triangle, the crossed-out hand. I am describing the artwork, not a wearing experience. I have not worn it, and I am not going to invent a scene where I did.

The category error is the point

Good signage is boring. It specifies the hazard, prohibits the action, and gets out of the way. The Not Friendly Do Not Touch shirt takes that boring, load-bearing structure and fills it with a personality claim, which is the one thing a warning sign is never supposed to contain. The result is a design that reads as official at a glance and as a joke on the second look, and the second look is where the whole thing pays off.

I would not ship a spec that worked this way. I would absolutely wear a shirt that does.

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

The ‘There Is Motion At Your Front Door’ Shirt Is a Notification That Forgot Its Payload

The shirt prints a white rounded notification banner with a bell icon. Inside the banner, in plain sentence case: There is motion at your front door. Below the banner, a circular, green-tinted view — the fisheye crop of a doorbell camera — holds 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 reaction shot. The joke is structural: a system generated an alert, and the alert is technically accurate and completely useless. The cat is the motion. The motion is the cat. The notification has delivered its payload and the payload is the sender.

I keep coming back to this because it is the cleanest visual argument I have seen for a distinction that matters in production WordPress work: the difference between a message that fires and a message that informs. A hook that runs is not the same as a hook that tells you anything. A cron event that completes is not the same as a cron event that did its job. The shirt is a diagram of a notification with no discriminating information, and it is funny because every one of us has shipped one.

What the artwork actually shows

Literal observation first, because the retail title and the printed design are not the same artifact. The printed elements are: a bell glyph, a rounded white banner, the sentence There is motion at your front door, and a circular green-tinted camera view containing an orange tabby at close range with porch architecture behind it. The retail listing calls it a funny cat doorbell meme. The shirt itself does not label itself a meme; it presents the alert and the camera frame and lets the viewer complete the circuit.

The green tint is doing specific work. It reads as night-vision or low-light camera processing, the color cast you associate with a consumer doorbell unit deciding that the scene is dim and switching modes. I am not making a claim about any particular camera product or its firmware. I am reading the color as a visual cue: this is a machine’s view of the porch, not a person’s. The fisheye distortion and the circular crop reinforce it. We are looking through the device, not at it.

The cat’s eyes are wide and forward-facing. The framing puts the animal essentially against the lens, which is what actually happens when a cat investigates a doorbell camera — the motion sensor triggers on the approach, and by the time the clip is captured the subject has closed the distance. The design compresses that sequence into a single frame. The alert and the cause of the alert are presented simultaneously, and the alert still says nothing useful.

The notification is a contract with no terms

In systems terms, a notification is a promise: if you attend to this, you will learn something that changes your next action. That is the contract. A doorbell alert that says there is motion at your front door technically satisfies the delivery half of the contract and fails the information half. You know something happened. You do not know whether it was a delivery, a raccoon, a gust of wind moving a branch, or a cat with its face against the glass. The alert has fired; the decision it was supposed to support is still unmade.

This is the same failure mode as a WordPress hook that logs init ran and nothing else. The event fired. The log line exists. The operator is no better off than before the log line was written. The shirt is a portrait of that log line, wearing a bell icon.

The design is careful about this. It does not show a person reacting to the alert. It does not show the phone screen, the homeowner’s face, the decision. It shows only the alert and its cause, side by side, with no resolution. The joke is that the resolution is obvious to us and unavailable to the system. The camera did its job. The notification did its job. The information did not travel.

Why the cat is the right subject

A cat is the ideal occupant of this frame because a cat is a motion source that generates alerts without generating events. The cat approaches the door, the sensor triggers, the clip records, the notification fires, and nothing has happened that requires a human decision. The cat is not a package. The cat is not a visitor. The cat is, from the system’s perspective, indistinguishable from a branch. From the human perspective, the cat is the entire point of owning a doorbell camera, which is the second layer of the joke: the alert is useless and also the best thing that will happen on that porch all day.

I read the wide eyes as the cat’s equivalent of a system state: I have detected a sensor and I am investigating it. The cat is running its own notification loop. The camera is running its. Neither loop produces a decision. The shirt is two state machines staring at each other through a fisheye lens.

The wording is the tell

There is motion at your front door. Not someone is at your door. Not a delivery has arrived. Not your cat would like to come in. The sentence is deliberately minimal, and the minimalism is the joke. It is the exact register of a system that has been configured to report the lowest-level event it can detect, because the higher-level classification is hard and the low-level event is cheap.

Anyone who has written a webhook payload knows this register. You start with { "event": "motion" } and you ship it because the classification layer is a later ticket. The later ticket never comes. The alert stays at the lowest level of abstraction forever, and every consumer of the alert learns to ignore it. The shirt is what that decision looks like when it is printed on cotton and worn to a barbecue.

I am not claiming the design was conceived as a critique of webhook payload design. I am claiming that the design works because it reproduces the exact texture of a low-information alert, and that texture is recognizable to anyone who has maintained a system that talks to humans.

The difference between a slogan and a usable promise

This is where the shirt earns its place in a work-culture column rather than a meme roundup. A slogan is a sentence that sounds like it means something. A usable promise is a sentence that changes what the reader does next. There is motion at your front door is a slogan. It has the grammar of a notification and the information content of a weather vane.

Teams ship slogans constantly. Status pages that say investigating for six hours. Error messages that say something went wrong. Cron monitors that alert on job did not complete without saying which job, which run, or what the last successful timestamp was. Each of these is a bell icon with no camera feed. Each of them fires. None of them informs.

The fix is not more alerts. The fix is payload discipline: every notification should carry the discriminating information that lets the recipient choose an action. Which door. What kind of motion. What the classifier thought it was. What the confidence was. What the last three events at this sensor looked like. The shirt is funny because it shows the alternative: a system that reports the event and withholds the meaning, and a cat that has become the meaning by default.

Reading the object

The shirt is available as a standard t-shirt from the Amazon listing, and the printed design is the notification banner and the camera view described above. I am reading the artwork, not reviewing a wearing experience; the observations here are about what is printed, not about fit, fabric, or how it holds up after a wash.

What I find worth keeping is the design’s refusal to resolve. The alert and the cause sit in the same frame, and the frame does not tell you what to do. That is the honest portrait of most monitoring systems I have inherited: the sensor works, the pipeline works, the notification works, and the human on the other end still has to walk to the door and look. The shirt does not pretend otherwise. It just puts the cat in the frame and lets you draw the conclusion the system could not.

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

Why wp_get_attachment_image_src() Returns a URL to a Scaled Image That Isn’t on Disk

The symptom: a URL that resolves to nothing

After a migration, a featured image or inline block image renders as a broken image. The browser requests a URL ending in -scaled.jpg and gets a 404. You open the Media Library, and the attachment looks fine: the thumbnail renders, the dimensions are listed, the attachment page loads. You check the uploads directory over SSH and the original file is there. The scaled copy is not.

The instinct is to blame wp_get_attachment_image_src(). It is not the culprit. The function is doing exactly what its source says it does: reading a filename out of post meta and substituting it into the attachment URL. It never touches the filesystem. The bug is a divergence between _wp_attachment_metadata in wp_postmeta and the files actually present under wp-content/uploads. The URL is the symptom; the metadata record is the fault.

Trace: the call chain from function to filename

The documented return value of wp_get_attachment_image_src() is an array whose element 0 is the image source URL, or false if no image is available. The function gets that array by calling image_downsize():

// wp-includes/media.php, wp_get_attachment_image_src()
$image = image_downsize( $attachment_id, $size );

image_downsize() is where the filename substitution happens. The function reference is explicit that it will not create a new resized copy: it returns an already resized one if it exists. The relevant lines:

// wp-includes/media.php, image_downsize()
$img_url = wp_get_attachment_url( $id );
$meta    = wp_get_attachment_metadata( $id );
$img_url_basename = wp_basename( $img_url );

$intermediate = image_get_intermediate_size( $id, $size );
if ( $intermediate ) {
    $img_url = str_replace( $img_url_basename, $intermediate['file'], $img_url );
    $width   = $intermediate['width'];
    $height  = $intermediate['height'];
    $is_intermediate = true;
}

Two things matter here. First, $meta comes from wp_get_attachment_metadata(), which reads the _wp_attachment_metadata post meta key. Second, the filename used in the URL comes from $intermediate['file'], which is a value inside that metadata array. There is no file_exists() call between the metadata read and the URL construction. The function trusts the record.

The metadata reference describes the shape: a sizes array keyed by size slug, each value containing file, width, height, and mime-type. The top-level file is a path relative to wp-content/uploads. The sizes entries are bare filenames that sit alongside that top-level file in the same year/month directory.

So the URL is assembled by string replacement: take the attachment URL (which ends in the top-level file basename), swap that basename for the size’s file value, and return the result. If the metadata says photo-1024x683.jpg exists, the function emits a URL ending in photo-1024x683.jpg. Whether that file is on disk is not part of the calculation.

Why migration breaks the pairing

The database and the uploads directory are two separate artifacts. A migration that copies one without the other, or copies both with different filters, leaves them out of sync. The metadata record survives because it lives in wp_postmeta; the file it names does not survive because it was excluded, renamed, or never copied.

The -scaled convention makes this worse. Since WordPress 5.3, an image whose width or height exceeds 2560 pixels is scaled down, the scaled copy is saved with -scaled appended to the filename, and that scaled copy becomes the file WordPress serves as the full-size image. The original is retained alongside it. According to SmartWP’s writeup of the feature, the original filename is stored in attachment metadata under original_image, and wp_get_original_image_path() / wp_get_original_image_url() return the unsuffixed file. ShortPixel’s explanation adds the detail that matters for this failure: once a scaled copy exists, WordPress rewrites _wp_attached_file to point at it, so get_attached_file() and wp_get_attachment_url() return the -scaled path, not the original.

That means a single large upload has at least two files on disk that the database references: the original (via original_image in metadata) and the scaled copy (via _wp_attached_file and the top-level file in metadata). A migration that copies only one of them produces exactly this class of mismatch. The metadata still names the scaled file; the scaled file is not there; wp_get_attachment_image_src($id, 'full') returns a URL to a missing file.

The same mechanism applies to sub-sizes. If the migration excluded intermediate sizes, or if a thumbnail regeneration ran against a different source than the one the metadata expects, the sizes array can name files that were never written. The function does not know the difference.

An illustrative scenario

This is a constructed example, not a case record. Suppose a migration script rsyncs uploads/ with --exclude='*-scaled.*'. Every large upload’s _wp_attached_file still points at a -scaled filename that no longer exists on the destination. wp_get_attachment_image_src($id, 'full') returns that URL. The browser 404s. The Media Library thumbnail still renders because a smaller sub-size did copy, which is why the attachment looks healthy in admin. The failure is invisible until a template requests the full size.

Diagnose the pair, not the URL

The correct diagnostic unit is the pair (attachment ID, size slug). For each pair, compare the filename in metadata against the actual directory listing. The URL is downstream of that comparison; fixing the URL without fixing the record leaves every other consumer broken.

Start with a single attachment. Dump the metadata and the resolved paths:

wp eval '
$id = 12345; // replace with the attachment ID
$meta = wp_get_attachment_metadata( $id );
$uploads = wp_upload_dir();
$dir = trailingslashit( $uploads["basedir"] ) . dirname( $meta["file"] );

printf( "top-level file: %s\n", $meta["file"] );
printf( "resolved dir:  %s\n", $dir );
printf( "top-level exists: %s\n", file_exists( $dir . "/" . basename( $meta["file"] ) ) ? "yes" : "NO" );

foreach ( $meta["sizes"] as $slug => $size ) {
    $path = $dir . "/" . $size["file"];
    printf( "%-20s %-40s %s\n", $slug, $size["file"], file_exists( $path ) ? "ok" : "MISSING" );
}
'

If the top-level file is missing, the attachment is broken at the root and no sub-size can be trusted. If only some sizes entries are missing, the metadata is stale for those slugs. Either way, the output tells you which files the database expects and which ones the filesystem has.

For a library-wide sweep, run the same comparison across all image attachments and write the mismatches to a log. This is a read-only pass; it does not modify anything:

wp eval '
$ids = get_posts( array(
    "post_type"      => "attachment",
    "post_mime_type" => "image",
    "post_status"    => "inherit",
    "posts_per_page" => -1,
    "fields"         => "ids",
) );
$uploads = wp_upload_dir();
$missing = 0;

foreach ( $ids as $id ) {
    $meta = wp_get_attachment_metadata( $id );
    if ( ! is_array( $meta ) || empty( $meta["file"] ) ) {
        continue;
    }
    $dir = trailingslashit( $uploads["basedir"] ) . dirname( $meta["file"] );
    $top = $dir . "/" . basename( $meta["file"] );
    if ( ! file_exists( $top ) ) {
        printf( "%d top-level missing: %s\n", $id, $meta["file"] );
        $missing++;
    }
    foreach ( (array) ( $meta["sizes"] ?? array() ) as $slug => $size ) {
        if ( ! file_exists( $dir . "/" . $size["file"] ) ) {
            printf( "%d %s missing: %s\n", $id, $slug, $size["file"] );
            $missing++;
        }
    }
}
printf( "total mismatches: %d\n", $missing );
'

Run this in a screen session on a large library. It reads every image attachment and stats every referenced file; on a site with tens of thousands of images it will take a while, and you do not want it dying halfway through because your SSH session dropped.

Fix the record, not the return value

The temptation is to add a filter on wp_get_attachment_image_src that returns false when the file is missing. Do not do this. The filter reference shows the hook receives the image array, the attachment ID, the size, and the icon flag. The same filter result is consumed by wp_get_attachment_image_srcset(), wp_get_attachment_image_sizes(), the REST attachments controller, and oEmbed. Returning false there degrades every consumer instead of repairing the record. It also hides the mismatch from the diagnostic pass, which means the next migration will reproduce it.

The repair is a metadata-vs-disk reconciliation. The shape of the fix depends on what is actually missing:

  • Top-level file missing, original present. The metadata points at a -scaled file that did not survive, but the original did. Point _wp_attached_file back at the original and rebuild metadata from it. This is the same operation the unscale.php snippet in the SmartWP writeup performs for scaled attachments: it calls update_attached_file() with the original path, then wp_update_attachment_metadata() with the result of wp_generate_attachment_metadata() against that original.
  • Top-level file missing, original also missing. The attachment is unrecoverable from disk. Either restore the file from backup or delete the attachment record. Regenerating against a missing source will fail per-attachment; it will not conjure the file.
  • Sub-sizes missing, top-level present. The metadata is stale for those slugs. Regeneration is the right tool, but only after confirming the source file exists at the path wp_get_original_image_path() returns. If the original is present, wp media regenerate --yes will rebuild the sub-sizes from it. If the original is missing and only the scaled copy survives, regeneration will rebuild from the scaled copy, which caps the maximum available resolution at the scaled dimensions and may permanently lose the reference to the true original.

Before running regeneration on any attachment, check the source path:

wp eval '
$id = 12345;
$original = wp_get_original_image_path( $id );
printf( "original path: %s\n", $original );
printf( "exists: %s\n", $original && file_exists( $original ) ? "yes" : "NO" );
'

If that prints NO, do not regenerate. Restore the file first. The metadata reference notes that wp_get_original_image_path() is among the functions that consume wp_get_attachment_metadata(), which is why the original_image key matters: it is the record of which file is the master copy. Lose it and regeneration has no correct source.

Verification

After reconciliation, re-run the diagnostic sweep. The mismatch count should be zero for the attachments you repaired. Then verify the specific URL that was failing:

wp eval '
$id = 12345;
$src = wp_get_attachment_image_src( $id, "full" );
if ( ! $src ) {
    echo "no image\n";
    exit;
}
printf( "url:    %s\n", $src[0] );
printf( "width:  %d\n", $src[1] );
printf( "height: %d\n", $src[2] );
printf( "resized: %s\n", $src[3] ? "yes" : "no" );

$path = wp_get_original_image_path( $id );
printf( "original exists: %s\n", $path && file_exists( $path ) ? "yes" : "NO" );
'

Fetch the URL with curl -I and confirm a 200. Then check the consumers that share the metadata: the REST attachment endpoint (/wp-json/wp/v2/media/12345) should return a source_url that resolves, and the block editor’s image block should render without a broken-image placeholder. If the REST response still points at a missing file, the reconciliation did not update the record that the REST controller reads; re-check that wp_update_attachment_metadata() actually wrote the new array.

Finally, fix the migration runbook. The database and the uploads tree are a single atomic unit. Copying wp_postmeta without the full uploads tree, including -scaled and -rotated variants, guarantees this failure class. Copying uploads without the database produces the inverse: orphan files with no metadata. Either way, the next migration will reproduce the problem unless the runbook treats them together.

FAQ

Does wp_get_attachment_image_src() check whether the file exists?

No. The function source delegates to image_downsize(), which reads the filename from _wp_attachment_metadata and substitutes it into the attachment URL. There is no filesystem check in that path. Adding one would stat a file on every image render, which is why core does not do it.

Why does the Media Library thumbnail still render when the full-size URL 404s?

The thumbnail is a separate sub-size with its own file entry in the sizes array. If that file copied during the migration and the full-size file did not, the thumbnail renders and the full-size request fails. The attachment looks healthy in admin because admin requests the thumbnail, not the full size.

Can I fix this by running wp media regenerate?

Only if the source file exists at the path wp_get_original_image_path() returns. Regeneration rebuilds sub-sizes from that source. If the source is missing and only the scaled copy survives, regeneration will rebuild from the scaled copy, which caps the maximum resolution and may lose the original_image reference. Check the source path first.

What is the -scaled suffix and why does it matter here?

Since WordPress 5.3, images over 2560 pixels on either edge are scaled down, the scaled copy gets -scaled appended to its filename, and that copy becomes the file WordPress serves as the full-size image. The original is retained alongside it and recorded in metadata under original_image. A migration that copies one but not the other produces exactly the metadata/filesystem divergence described here.

Should I add a filter to return false when the file is missing?

No. The wp_get_attachment_image_src filter result is consumed by srcset, sizes, the REST attachments controller, and oEmbed. Returning false degrades every consumer and hides the mismatch from the diagnostic pass. Repair the metadata record instead.

The ‘I Had Potential’ Shirt Is a Diagram of a Ball That Already Left the Ledge

White capitals, all the same weight: I HAD POTENTIAL. Below them, a white curved ramp descends from left to right. On the upper left ledge sits a dashed empty circle. On the lower right flat ledge rests a solid white ball. That is the whole design. No caption, no arrow, no equation. The shirt states a claim and then draws a diagram that quietly contradicts it.

Most slogan shirts stop at the sentence. This one keeps going, and the second half is where the argument lives. The dashed circle is the interesting object. A dashed outline in a physics diagram conventionally marks a position that is no longer occupied — a ghost, a before-state, the place where the thing used to be. The solid ball is where the thing actually is. Read together, the drawing says: the potential was up there, the ball is down here, and the gap between them is the joke.

What the drawing actually shows

The ramp is curved, not a straight diagonal. That matters for how you read the motion. A straight incline suggests a simple slide; a curve suggests acceleration, a path with changing slope, something that picks up speed as it goes. The ball did not fall off the top ledge and land directly below. It traveled. The dashed circle at the upper left is the origin point, and the solid ball at the lower right is the destination, and the curve between them is the distance covered.

I want to be careful here, because it would be easy to overclaim. The design does not label the curve as a specific function. It does not print an axis, a unit, or a coefficient of friction. It is a cartoon of a physical situation, not a worked problem. What I can say from looking at it is structural: there are two ledges at different heights, a curved connector, an empty marker at the start, and a filled marker at the end. The visual grammar is descent. Whatever the ball had at the top, it spent getting to the bottom.

The phrase I had potential is past tense. That is the load-bearing word. Present tense would be a boast; future tense would be a promise. Past tense is a post-mortem. The shirt is not saying the wearer is currently full of unrealized capacity. It is saying the capacity was there, at the upper ledge, and the ball is now at the lower one. The diagram and the sentence agree on the timeline even as they disagree on the tone.

The double meaning is the whole mechanism

Potential is one of those words that does two jobs. In ordinary speech it means latent capacity — the smart kid who never applied himself, the project that could have shipped. In physics it refers to potential energy, the energy an object has by virtue of its position in a field. A ball on a high ledge has more of it than a ball on a low ledge. The shirt puts both meanings in the same frame and lets them collide.

The collision is not subtle, but it is well built. If you read the sentence alone, you get a self-deprecating joke about wasted talent. If you read the diagram alone, you get a ball that rolled downhill. Put them together and the joke sharpens: the potential was real, it was measurable, it was stored in the ball’s position — and then the ball moved, and the potential converted into something else. Motion, heat, noise, the general friction of getting from one ledge to the other. The shirt does not say what the potential became. It just shows that it is no longer sitting at the top.

That is a more interesting joke than the standard sarcastic slogan, because it requires the reader to do a small amount of work. You have to notice the dashed circle. You have to notice that the ball is solid and the circle is not. You have to connect the curve to the word potential and realize the design is not decorating the sentence but arguing with it. A lesser shirt would have printed the phrase and a frowning emoji. This one printed a free-body diagram with the labels filed off.

Why the minimalism is doing real work

The palette is white on the garment, and the composition is sparse. There is no border, no background shape, no secondary text. That restraint is not just aesthetic preference; it is what makes the diagram legible as a diagram. Physics figures are sparse by convention. Axes, vectors, and position markers are drawn in thin lines against empty space so the relationships read cleanly. The shirt borrows that convention. The white capitals sit above the drawing like a figure caption, and the drawing sits below like the figure itself.

The capitalization reinforces it. I HAD POTENTIAL in uniform capitals reads as a label, not a confession. It has the flat affect of a chart title. That flatness is what keeps the shirt from tipping into self-pity. A lowercase, handwritten version of the same sentence would be maudlin. All-caps sans-serif is clinical. The wearer is not asking for sympathy; the wearer is presenting a result.

I would not claim the design is scientifically rigorous, and it does not need to be. The curve is a cartoon curve. The ledges are cartoon ledges. But the visual logic is internally consistent, and that consistency is what makes the joke land. The dashed circle is empty because the ball left. The ball is solid because it arrived. The ramp is curved because the trip was not a straight line. Every element earns its place.

The work-culture reading, held loosely

There is an obvious adjacent reading here for anyone who has sat in a performance review or a sprint retrospective. I had potential is the sentence that hangs over a project that got deprioritized, a hire that did not work out, a quarter that got eaten by maintenance. The diagram supplies the missing explanation: the ball did not vanish, it rolled. The potential did not disappear, it converted. That is a more honest account of most organizational underperformance than the word failure usually carries.

But I want to hold that reading loosely, because the shirt does not name a workplace, a manager, or a process. It is a physics pun first. The work-culture resonance is available to the reader, not asserted by the design. What the design does assert is narrower and more durable: that potential is a function of position, and that position changes. You can hang a whole philosophy of career disappointment on that if you want to. The shirt will not stop you. It also will not help you, which is part of its charm.

The object itself is a standard t-shirt from Quirky Cotton Collective, listed under the title I Had Potential Funny Physics Pun Sarcastic Minimalist Quote. The design is the argument; the garment is the substrate. If you are going to wear a diagram, it helps that the diagram is correct on its own terms.

What makes it a usable object rather than a slogan

The difference between a slogan and a usable message is whether the second half rewards a second look. A slogan is exhausted on first read. This design is not. The first read gives you the self-deprecating sentence. The second read gives you the dashed circle, the solid ball, the curved ramp, and the realization that the drawing is making a separate claim. The third read — the one where you notice the past tense and the position-dependent definition of potential — is where the shirt becomes something you could actually wear to a meeting without it reading as a cry for help.

That is a narrow achievement, but it is a real one. Most novelty shirts are one joke deep. This one is two, and the second joke is drawn rather than written. The dashed circle is the tell. Once you see it, the shirt stops being a sentence with a picture under it and becomes a diagram with a caption over it. The caption is the wearer’s voice. The diagram is the evidence. They do not quite agree, and that disagreement is the point.

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

pre_render_block Is the Wrong Hook for Term-Driven Template Part Swaps

pre_render_block Is the Wrong Hook for Term-Driven Template Part Swaps

Symptom. You add a pre_render_block callback that inspects the current post’s terms and returns a template part when a category matches. On the front end, the block renders the template part, but the terms are wrong, the block context is empty, and any downstream render_block filter you rely on for markup cleanup never runs. Nothing errors. The page just renders the wrong variant, or the right variant with the wrong data.

Trace. The callback fires. get_the_terms() returns something. The template part loads. The failure is not in the term lookup or the template loader. It is in the hook’s position in the render pipeline.

Root cause. pre_render_block is a short-circuit, not a render-stage filter. It runs before render_block_data and render_block_context, and a non-null return bypasses both plus the block’s own render callback and the render_block_{namespace/block} filter. For term-dependent template-part replacement, that is the wrong tool. The correct hook is render_block_data on core/template-part.

Fix. Use pre_render_block only for narrow, self-contained short-circuits keyed on $parsed_block['attrs'] and the global $post. Use render_block_data to swap a template part’s slug based on assigned terms. Use render_block or render_block_{namespace/block} for markup post-processing.

Verification. A Query Monitor hook trace, a WP-CLI term check, and a small REST request against the block renderer will show which hook fired, what it received, and whether the template part slug changed before rendering.

What pre_render_block actually receives and returns

The hook signature is documented as:

apply_filters( 'pre_render_block', string|null $pre_render, array $parsed_block, WP_Block|null $parent_block )

The first argument is $pre_render, default null. The second is the parsed block array: blockName, attrs, innerBlocks, innerHTML, innerContent. The third is the parent WP_Block instance for nested blocks, or null at the top level. The documentation states the purpose plainly: it “allows render_block() to be short-circuited, by returning a non-null value” (WordPress Developer Reference: pre_render_block).

That is the whole contract. It is not a filter for modifying block output. It is a filter for replacing the render call.

The ordering problem, in source order

The render_block() source makes the sequence unambiguous:

$pre_render = apply_filters( 'pre_render_block', null, $parsed_block, $parent_block );
if ( ! is_null( $pre_render ) ) {
    return $pre_render;
}

$source_block = $parsed_block;
$parsed_block = apply_filters( 'render_block_data', $parsed_block, $source_block, $parent_block );

$context = array();
if ( $post instanceof WP_Post ) {
    $context['postId']   = $post->ID;
    $context['postType'] = $post->post_type;
}
$context = apply_filters( 'render_block_context', $context, $parsed_block, $parent_block );

$block = new WP_Block( $parsed_block, $context );
return $block->render();

Three consequences follow directly from that order:

  1. If your pre_render_block callback returns a string, render_block_data never runs for that block.
  2. render_block_context never runs, so the block’s context (including postId and postType) is never assembled.
  3. The WP_Block instance is never constructed, so the block’s own render_callback and the render_block_{namespace/block} filter never execute.

This is not an inference from reading the docs. It is the literal control flow of render_block() as published in the function reference. The Gutenberg issue tracker has the same observation from a different angle: “pre_render_block happens before you have access to render_block_context context or any modifications to the block via render_block_data” and “pre_render_block output also does not go through the render_block_${blockname} filter” (WordPress/gutenberg issue #68665).

If your term-dependent replacement depends on block context, or on a render_block_data modification made by another plugin, pre_render_block cannot see it. If your replacement depends on a downstream render_block filter to add classes, rewrite attributes, or sanitize markup, that filter will not run on the string you returned.

Why term lookup inside pre_render_block is fragile

get_the_terms() itself is not the problem. It is cached, and the documentation notes that it “won’t hit the database every time it’s called” (get_the_terms() reference). The problem is what “the current post” means at the moment pre_render_block fires.

The hook runs inside render_block(), which is called from do_blocks() during the_content processing, from the REST block renderer, from ServerSideRender requests in the editor, and from excerpt generation. In some of those contexts the global $post is the queried post. In others it is the post that owns the template, or a post inside a Query Loop, or nothing at all. A callback that calls get_the_terms( get_the_ID(), 'category' ) without checking the global will sometimes read the right post and sometimes read a different one, and it will not warn you.

The return contract is also easy to get wrong. get_the_terms() returns WP_Term[] on success, false if there are no terms or the post does not exist, and WP_Error on failure. A guard sequence that assumes an array will throw a warning on false and a fatal on WP_Error in PHP 8+. The safe pattern is:

$terms = get_the_terms( $post_id, 'category' );
if ( is_wp_error( $terms ) || empty( $terms ) ) {
    return $pre_render; // leave rendering alone
}
foreach ( $terms as $term ) {
    // inspect $term->slug
}

That guard is necessary in any hook. It does not make pre_render_block the right place for the decision.

The template-part loading primitive

locate_template() searches the stylesheet directory, then the template directory, then wp-includes/theme-compat, and returns the template filename if one is located (locate_template() reference). It returns an empty string when nothing matches, so a non-empty return is the existence check you want before assigning a slug.

Two cautions from the same reference. First, locate_template() “does not prevent directory traversal attacks,” so never pass unsanitized user input as a template name. Second, for block themes the template part directory is not always parts; the WordPress developer news tutorial on dynamic template parts uses get_block_theme_folders()['wp_template_part'] to resolve it (Dynamically loading template parts in block themes).

The correct pattern: render_block_data on core/template-part

For term-dependent template-part replacement, the hook you want is render_block_data. It fires just before a block is rendered, receives the parsed block array, and lets you modify it before WordPress does anything with it. For core/template-part, the slug attribute tells WordPress which template part to load; change the slug and a different part loads. The WordPress news tutorial documents this pattern directly.

A minimal implementation for a single-post sidebar that varies by category:

add_filter( 'render_block_data', 'jv_render_template_part_data' );

function jv_render_template_part_data( array $parsed_block ): array {
    if ( ( $parsed_block['blockName'] ?? '' ) !== 'core/template-part' ) {
        return $parsed_block;
    }
    if ( ( $parsed_block['attrs']['slug'] ?? '' ) !== 'sidebar-post' ) {
        return $parsed_block;
    }
    if ( ! is_singular( 'post' ) ) {
        return $parsed_block;
    }

    $post = get_queried_object();
    if ( ! $post instanceof WP_Post ) {
        return $parsed_block;
    }

    $terms = get_the_terms( $post->ID, 'category' );
    if ( is_wp_error( $terms ) || empty( $terms ) ) {
        return $parsed_block;
    }

    $parts_dir = get_block_theme_folders()['wp_template_part'];

    foreach ( $terms as $term ) {
        $candidate = "sidebar-post-{$term->slug}";
        if ( locate_template( "{$parts_dir}/{$candidate}.html" ) ) {
            $parsed_block['attrs']['slug'] = $candidate;
            return $parsed_block;
        }
    }

    return $parsed_block;
}

Three properties make this the right hook rather than a workaround:

  • The callback always returns $parsed_block, modified or not. The tutorial states this as the key rule, because the filter runs for every block on the page.
  • The early returns bail on block name, slug, and query context before any term lookup. That keeps the cost of the filter low on pages with many blocks.
  • If no candidate template part exists, the original slug is left in place, so the default part loads. The fallback is free.

Because render_block_data runs before render_block_context and before WP_Block::render(), the modified slug is what the Template Part block actually uses. The block’s own render callback still runs, and downstream render_block filters still see the output.

What pre_render_block is legitimately good for

There is a narrow case where pre_render_block is the correct tool: a self-contained short-circuit for a specific core block, where the decision depends only on $parsed_block['attrs'] and the global $post, and where bypassing render_block_data, render_block_context, and render_block_{namespace/block} is acceptable because nothing else in the stack needs to touch that block.

An example is replacing a core/embed YouTube variant with a lightweight facade, where the decision is driven entirely by $parsed_block['attrs']['providerNameSlug'] and the replacement markup is generated from the block’s own attributes. The 10up Gutenberg guide demonstrates a facade replacement for the YouTube embed, though it uses render_block_core/embed rather than pre_render_block; the latter would skip the block’s own render callback and any downstream filters, which is a tradeoff you should make deliberately, not by accident (10up Gutenberg guide: Modifying the markup of a core block).

That recommendation is my own reading of the source order and the documented contract, not a pattern the WordPress documentation endorses. The documentation describes pre_render_block as a short-circuit and leaves the choice of when to short-circuit to the implementer.

Failure-mode checklist

Before shipping a render-hook callback, check each of these against the actual code path:

  • Returning a string from pre_render_block skips render_block_data, render_block_context, and render_block_{namespace/block}. If any of those need to run, use a different hook.
  • get_the_terms() can return WP_Error or false. Check is_wp_error() first, then empty(), then iterate. Do not assume an array.
  • locate_template() returns '' when nothing matches. Check the return before assigning a slug, or you will set an empty slug and the Template Part block will fall back or render nothing depending on version.
  • Template part slugs must exist in the theme’s parts directory. Use get_block_theme_folders()['wp_template_part'] rather than hardcoding parts, because block themes can use a different folder.
  • The global $post is not always the queried post. Inside a Query Loop, in REST block-renderer requests, and in excerpt generation, it may be something else. Use get_queried_object() with an instanceof WP_Post check when the decision is about the page being viewed.
  • Editor previews use a different path. render_block filters “have no impact on the behavior of blocks in the Editor” per the block filters reference, and ServerSideRender requests go through the REST block renderer. Test the front end and the editor separately.

Verification

Three checks will tell you which hook fired and what it saw.

1. Hook trace. With Query Monitor active, open the Hooks panel on a single post that has a category-specific template part. You should see render_block_data fire for core/template-part before the block renders, and you should not see your callback under pre_render_block if you moved it. If you left the callback on pre_render_block, the trace will show it firing before render_block_data and the block’s own render callback will be absent from the trace for that block.

2. Term check. Confirm the post actually has the term you expect, and that the term slug matches the template part filename:

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

If the slug in the output does not match the filename suffix in parts/sidebar-post-{slug}.html, the loop in the callback will not find a candidate and the default part will load. That is the intended fallback, but it looks like a bug if you expected the variant.

3. REST block renderer. Request the rendered block through the REST API to see what the server produces outside the theme’s template context:

curl -s -u user:app-password \
  'https://example.com/wp-json/wp/v2/block-renderer/core/template-part?context=edit&attributes%5Bslug%5D=sidebar-post'

The response shows the rendered HTML for that block in isolation. If the slug swap depends on is_singular( 'post' ) or get_queried_object(), the REST response will show the default part, because those conditions are not true in a block-renderer request. That is expected; it is also why the callback should bail early rather than assume the front-end context.

Decision rule

Pick the hook by what the decision depends on and what must run afterward:

  • pre_render_block — attribute-only short-circuit for a specific core block, where skipping render_block_data, render_block_context, and render_block_{namespace/block} is acceptable.
  • render_block_data — term-dependent template-part slug swaps, where the modified block data must reach WP_Block::render() and downstream filters must still run.
  • render_block or render_block_{namespace/block} — markup post-processing after rendering, where the block’s own output is the input.

The failure mode in the opening paragraph is not a bug in pre_render_block. It is a hook chosen for a job the hook was not designed to do. The source order is the specification; read it before choosing the filter.

FAQ

Can I use pre_render_block to replace a core block’s output with a template part at all?

Yes, mechanically: return a non-null string and render_block() returns it immediately. But the replacement will not pass through render_block_data, render_block_context, or render_block_{namespace/block}, and the block’s own render callback will not run. If any of those matter to your stack, use render_block_data for slug swaps or render_block for markup changes.

Why are the terms wrong inside my pre_render_block callback?

Most likely the global $post is not the post you think it is. pre_render_block fires inside render_block(), which is called from several contexts: the_content, the REST block renderer, ServerSideRender in the editor, and excerpt generation. Use get_queried_object() with an instanceof WP_Post check when the decision is about the page being viewed, and bail early when the context is not the front end.

Does render_block_data run for every block on the page?

Yes. The WordPress news tutorial states that the filter runs for every block, which is why the first thing the callback should do is bail early on block name, slug, and query context. The cost of the filter on a page with many blocks is dominated by those early returns, not by the term lookup, which only runs for the matching template part.

What happens if no category-specific template part exists?

Nothing changes. The callback leaves $parsed_block['attrs']['slug'] at its original value, and the default template part loads. That fallback is built into the pattern: you only create the parts you actually need, and the loop skips candidates whose files do not exist.

Is get_the_terms() safe to call inside a render hook?

It is cached, so repeated calls do not hit the database every time. The risk is the return type: WP_Term[], false, or WP_Error. Check is_wp_error() first, then empty(), then iterate. A callback that assumes an array will warn on false and fatal on WP_Error in PHP 8+.

Can I pass a user-supplied template name to locate_template()?

No. The function reference states that locate_template() does not prevent directory traversal attacks. If the template name comes from user input, validate that the resolved path is inside the active theme, parent theme, or wp-includes/theme-compat before loading it. In the pattern above, the candidate slug is built from a term slug returned by get_the_terms(), not from raw request input, but the same rule applies if you extend it.

The ‘Let’s Root For Each Other’ Shirt Is a Growth Curve With a Boundary Problem

The artwork reads LET’S ROOT FOR EACH OTHER AND WATCH EACH OTHER GROW, set in a ring around four smiling root vegetables: a carrot, a radish, a beet, and an onion, each with its roots visible in soil. The phrase is a pun on two senses of root — to cheer for someone, and the underground structure that feeds a plant. The design leans on that double meaning without resolving it. That unresolved tension is the interesting part, and it is also where the shirt’s promise starts to fray.

Read the ring literally. The words form a closed loop around the vegetables. The vegetables are not arranged in a hierarchy; they are peers in a bed. The roots are drawn, not hidden. The smiles are uniform. This is a diagram of mutual support, and as a piece of visual rhetoric it works: the loop suggests reciprocity, the visible roots suggest that the support is structural rather than decorative, and the four distinct vegetables suggest that the participants are not interchangeable. A carrot does not grow into a radish. The design acknowledges difference while insisting on shared conditions.

Now read the second clause. Watch each other grow is not the same as help each other grow. Watching is passive. It implies observation, maybe admiration, maybe surveillance. The shirt does not say help. It says watch. That is a small word with a large load. In a work culture context — and this is the context in which a slogan like this tends to circulate — watch each other grow can mean mentorship, or it can mean performance review. The design does not distinguish. The smiling vegetables do not help.

This is the boundary problem. A slogan is a compressed promise, and the compression hides the terms. Let’s root for each other is a commitment to support. And watch each other grow is a commitment to observe outcomes. The two commitments are not the same, and they can conflict. If I root for you, I am on your side regardless of your growth curve. If I watch you grow, I am measuring. The shirt puts both in the same ring, as if they were a single act. They are not. The ring is a visual trick that makes a compound promise look like a simple one.

I am not arguing the shirt is cynical. I am arguing it is underspecified, and that underspecification is what makes it useful as an object to think with. The design gives you the vocabulary of mutual support and the vocabulary of growth, and it leaves the relationship between them to the wearer. That is a feature for a t-shirt and a bug for a team charter. A shirt can carry an unresolved tension because it is not a contract. A team cannot.

The root vegetables themselves are doing more work than they appear to. Each one is drawn with its root system visible below the soil line. That is an unusual choice for a cartoon vegetable, which usually stops at the leaves. Showing the roots makes the metaphor literal: the part that feeds the plant is underground, invisible in ordinary view, and shared with the other plants in the bed. The design is saying that growth is supported by structures you cannot see from above. That is a systems idea, and it is the strongest thing in the artwork. The smiles are the weak part — they flatten the difference between the four vegetables into a single expression — but the roots are the argument.

If you are the kind of reader who maintains production systems, you will recognize the pattern. A slogan is an interface. It advertises a contract. The contract here is something like: we will support each other, and we will pay attention to each other’s development. That is a reasonable contract. But an interface without a specification is a liability. The shirt does not tell you what counts as growth, who watches, or what happens when rooting for someone and watching them grow point in different directions. Those are the questions a team has to answer for itself. The shirt is a prompt, not a policy.

The phrase let’s root for each other shirt is the kind of query that surfaces this object, and it is worth being precise about what the object is. It is a standard t-shirt from Quirky Cotton Collective with the phrase and the four vegetables printed on it. The visual observation is the design description above; the retail listing is the source for the object’s existence. Nothing about the shirt’s construction, fit, or wearing experience is established by the artwork, and I am not going to pretend otherwise. The argument here is about the design’s rhetoric, not its fabric.

The strongest reading of the shirt is that it is a diagram of a growth environment, not a growth mandate. The roots are shared. The soil is shared. The vegetables are different. The loop of words is a boundary that contains all four without ranking them. If you wear it, you are wearing a small argument that support and observation are the same act. They are not, but the shirt makes a case for trying to hold them together. That is a more interesting position than either half alone, and it is the reason the design is worth reading closely rather than just smiling at.

Disclosure: This publication and Quirky Cotton Collective share an owner.

The ‘Meh’ Shirt Is a Typographic Volume Knob, Not a Mood

The native garment preview shows large, bold, white lowercase meh. lettering on a dark shirt. No animal illustration is present. The period is part of the artwork, and it does more work than the word.

Most slogan shirts treat typography as a delivery vehicle: pick a font, set the joke, ship it. This one treats typography as the joke’s counterweight. The word meh is a shrug — a verbal downgrade, a refusal to escalate. The lettering is the opposite: heavy, declarative, impossible to miss across a room. That mismatch is the entire design argument, and it’s worth reading closely because it’s the kind of visual contradiction that technical readers tend to notice before they can explain why.

I’m not going to pretend this shirt demonstrates anything about software, security, or engineering outcomes. It doesn’t. But it does sit in a recognizable category for people who spend their days writing terse messages — commit subjects, incident summaries, boundary-setting Slack replies — and it’s worth asking what the design is actually saying about that habit.

The period is the load-bearing element

Lowercase meh without punctuation is a sound. It’s the noise you make when someone asks how the deploy went and the answer is technically fine. Add the period and it becomes a sentence: a complete, closed statement with a subject implied and a verdict delivered. The period is what turns a verbal tic into a position.

That’s a small typographic decision with a large rhetorical effect. In prose, a period after a single word is often read as curt — even hostile. Here it reads as final. The word says I decline to have a strong opinion; the period says and that is my final answer. The two together produce a kind of deadpan authority that a bare meh can’t reach.

This is the same move technical writers make when they replace a paragraph of hedging with a one-line status. Brevity plus punctuation equals closure. The shirt is wearing that habit on its chest.

Visual loudness against a dismissive word

The lettering is large and bold. On a dark shirt, white type at that weight reads as a label — the kind of thing you’d put on a shipping container or a warning placard. The word inside the label is a refusal to care. That’s the tension: the form is assertive, the content is indifferent.

I read this as a deliberate joke about the difference between saying you don’t care and announcing it. A quiet meh is a mood. A billboard-sized meh. is a policy. The shirt doesn’t resolve the contradiction; it displays it. That’s why it works as an object rather than a punchline — the visual volume is doing the comedic labor, not the word.

There’s a useful distinction here for anyone who writes terse messages for a living: a slogan is a claim, but a usable promise is a claim someone can act on. Meh. is not a promise. It’s a boundary dressed as a non-statement. The shirt is funny because it pretends the boundary is casual while the typography makes it impossible to ignore.

What the design doesn’t do

The preview shows no animal illustration, no secondary graphic, no decorative frame. The word and the period are the whole composition. That restraint matters: it keeps the joke in the typography rather than splitting it across a mascot and a caption. A design like this either lands on the lettering or it doesn’t land at all, and the bold weight is what makes it land.

I’m describing what the preview shows, not claiming anything about how the shirt wears, how it’s printed in person, or how anyone has reacted to it. The observation is the artwork: large bold white lowercase meh. on a dark ground, no animal, no extra ornament.

Why this belongs in a work-culture column

Technical teams run on terse messages. A commit subject, a status line, a one-word reply in a thread that has gone on too long — these are the load-bearing units of coordination, and they carry the same tension this shirt displays. The form is often louder than the content. A one-word reply in bold can read as a verdict even when the sender meant it as a shrug.

The meh shirt is a useful object to think with because it makes that tension visible. It’s not a manifesto and it’s not a mood board. It’s a typographic volume knob turned all the way up on a word that claims the volume doesn’t matter. If you’ve ever sent a terse message and watched it land harder than you intended, the design will read as familiar.

If you want the object itself, the listing is here: Meh Funny Sarcastic Saying Introvert Dry Humor.

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

The ‘Meh’ Shirt Is a Typographic State Machine, Not a Slogan

The garment preview shows a dark shirt with three lowercase letters centered on the chest: meh. The period is part of the mark. The type is small — small enough that the shirt reads as blank from conversational distance and resolves into text only when someone is close enough to be reading it. There is no animal, no mascot, no secondary graphic. The entire design is a word, a period, and a lot of dark fabric.

That scale is the argument. A slogan shirt shouts; this one mutters. The meh. is set at a size that assumes a viewer who has already chosen to look, which is a different social contract than the one a chest-sized joke proposes. I want to take the typography seriously as a piece of interface design, because that is what it is: a three-character status indicator with a deliberate contrast ratio and a deliberate viewing distance.

The period does the work the word refuses to do

Strip the period and you have meh — an interjection, open-ended, still mid-sentence. Add the period and the utterance closes. The period is the terminal state. In state-machine terms, meh is a transition; meh. is a resting state with no outgoing edges. The design’s whole claim is that the resting state is the point.

That is a more precise joke than “sarcastic introvert” retail copy suggests. The shirt is not advertising a personality; it is displaying a settled condition. The lowercase setting reinforces it — no capital letter to signal emphasis or arrival, just three letters at the same weight, ending. If you have ever written a status field that returns idle rather than active, you already know the register.

Small type is a permission structure

The most consequential design decision here is scale. A large MEH across the chest is a performance; it recruits the room. A small centered meh. is closer to a lapel pin or a terminal prompt: legible to the person in front of you, invisible to everyone else. The shirt does not start conversations. It permits them, if the other party is close enough and inclined to read.

I read that as a boundary rendered in typography rather than in words. The message is not “talk to me” or “don’t talk to me”; it is a low-amplitude signal that rewards attention without demanding it. Whether that reads as introversion, dry humor, or simple fatigue is left to the viewer, and the design is honest enough not to resolve it. The period closes the sentence, not the person.

What the design is not

The retail title stacks descriptors — funny, sarcastic, introvert, minimalist — and the temptation is to treat those as specifications. They are not. The observed artwork supports exactly one claim: very small, centered, lowercase meh. lettering on a dark shirt, with no animal illustration. There is no pride variant, no mascot, no secondary text in the preview. If you are shopping for a graphic, this is a typographic object and nothing more.

That restraint is what makes it usable as an off-duty object rather than a costume. A shirt that says one small thing can be worn to more places than a shirt that says a large thing. The design’s minimalism is not an aesthetic preference layered on top of the joke; it is the mechanism by which the joke stays wearable.

The difference between a slogan and a usable promise

Most message shirts fail because they promise more than the wearer can deliver. A shirt that declares a mood obligates you to perform it all day. meh. promises almost nothing, which is why it holds up. It is closer to a default value than a commitment — the state a system returns to when no input has arrived. That is a defensible thing to print on cotton, and a rare one.

If you want the object described here, it is the Meh Funny Sarcastic Introvert Minimalist Saying shirt from Quirky Cotton Collective. Read the listing for sizing and availability; read the preview for the design, because the preview is the design.

Disclosure: this publication and Quirky Cotton Collective share an owner.

A Read-Only REST Endpoint for wp_postmeta meta_key Distribution (and Why You Need the Orphan Column)

Symptom: the prefix DELETE looked safe until it wasn’t

You decide to clean up wp_postmeta. You pick a key prefix left behind by a plugin you removed two years ago, run DELETE FROM wp_postmeta WHERE meta_key LIKE '_elementor_%', and move on. The query returns a large affected-rows count, which feels like progress.

What it actually did was remove every row matching that prefix, including rows attached to posts that still exist and are still being edited. The prefix is a string match, not a liveness test. A DELETE ... WHERE meta_key LIKE 'example_key_%' is exactly the shape recommended in cleanup write-ups, and it is exactly the shape that cannot tell an abandoned key from a key still in use on a live post (Anchor Host).

The failure is not the SQL. It is that a key-level question (“is this meta_key still written?”) and a row-level question (“do these rows still have a parent post?”) were collapsed into one decision. This article builds a read-only REST endpoint that reports both numbers per meta_key, so the dangerous middle — keys that are partly orphaned — is visible before anyone types DELETE.

Trace: what the two questions actually look like in SQL

The key-level question is a grouped count. The canonical shape is a GROUP BY meta_key with COUNT(*), ordered descending, which is the query most people paste into phpMyAdmin first (nicomollet gist):

SELECT meta_key, COUNT(*) AS total
FROM wp_postmeta
GROUP BY meta_key
ORDER BY total DESC;

The row-level question is a LEFT JOIN against wp_posts where the joined ID is null. That is the standard orphan check (Anchor Host):

SELECT pm.meta_key, COUNT(*) AS orphans
FROM wp_postmeta pm
LEFT JOIN wp_posts p ON p.ID = pm.post_id
WHERE p.ID IS NULL
GROUP BY pm.meta_key
ORDER BY orphans DESC;

Run separately, each answers half the question. Run together, they answer the one that matters: for a given key, how many rows exist, and how many of those rows are attached to nothing.

Root cause: the partial-orphan fraction is the dangerous case

Three states fall out of the two columns:

  • Total > 0, orphans = 0. The key is live. Every row has a parent. Deleting by key name destroys data.
  • Total = orphans. The key is entirely dead. Every row is parentless. Deleting by key name is safe in the narrow sense that no live post loses metadata.
  • 0 < orphans < total. The key is partly dead. Some rows belong to deleted posts; some belong to live ones. A prefix DELETE removes both. This is the case the endpoint exists to surface.

As a hypothetical illustration: a site where _elementor_ keys show 40,000 total rows and 9,000 orphans. A prefix delete would remove 31,000 rows still attached to live pages. The endpoint’s two-column output is what makes that visible before the write runs. The numbers are illustrative, not a measurement of any particular install.

Fix: register a read-only route on rest_api_init

Custom routes are registered with register_rest_route(), and the documentation is explicit that it should be called in a callback on rest_api_init to avoid doing extra work when the API is not loaded (Adding Custom Endpoints). Calling it earlier triggers a _doing_it_wrong notice; the source checks did_action( 'rest_api_init' ) and complains if the action has not fired (register_rest_route()).

Since WordPress 5.5, a permission_callback is required. Omitting it produces a _doing_it_wrong notice telling you to use __return_true for public routes (register_rest_route()). This endpoint is not public; it reads site-wide metadata, so it gets a real capability check.

add_action( 'rest_api_init', function () {
    register_rest_route(
        'jv-meta-audit/v1',
        '/meta-keys',
        array(
            'methods'             => 'GET',
            'callback'            => 'jv_meta_audit_get_keys',
            'permission_callback' => 'jv_meta_audit_permissions',
            'args'                => array(
                'min_total' => array(
                    'type'              => 'integer',
                    'default'           => 1,
                    'sanitize_callback' => 'absint',
                    'validate_callback' => 'rest_validate_request_arg',
                ),
                'key_like' => array(
                    'type'              => 'string',
                    'required'          => false,
                    'sanitize_callback' => 'sanitize_text_field',
                    'validate_callback' => 'rest_validate_request_arg',
                ),
            ),
        )
    );
} );

The namespace follows the vendor/v1 convention the handbook recommends to prevent clashes between plugins (Adding Custom Endpoints). The args map gives you sanitization and validation before the callback runs, so the callback can assume its inputs are clean.

The permission callback

The permissions callback runs after remote authentication, which sets the current user, so current_user_can() is the right tool (Adding Custom Endpoints). The handbook recommends checking a capability rather than merely checking that a user is logged in.

function jv_meta_audit_permissions( WP_REST_Request $request ) {
    if ( ! current_user_can( 'manage_options' ) ) {
        return new WP_Error(
            'rest_forbidden',
            'You cannot read site-wide postmeta distribution.',
            array( 'status' => 403 )
        );
    }
    return true;
}

manage_options is a defensible default for a diagnostic that exposes the shape of the database. If your editorial team should see it without full admin, register a custom capability and grant it deliberately; the choice is yours, but name it explicitly rather than falling back to read.

One authentication detail that bites people testing with curl: cookie authentication requires the wp_rest nonce, passed as X-WP-Nonce or the _wpnonce parameter. Without it, the API sets the current user to 0 and treats the request as unauthenticated even if you are logged in (Authentication). For command-line testing, Application Passwords over HTTPS are the documented path.

The query: one statement, two counts, prepared

All untrusted values in an SQL statement must be escaped, and $wpdb->prepare() is the mechanism WordPress provides (wpdb). The table name comes from $wpdb->postmeta, not from user input. The LIKE pattern and the threshold are the only variables, and both go through placeholders.

function jv_meta_audit_get_keys( WP_REST_Request $request ) {
    global $wpdb;

    $min_total = (int) $request->get_param( 'min_total' );
    $key_like  = $request->get_param( 'key_like' );

    $sql = "SELECT pm.meta_key,
                   COUNT(*) AS total,
                   SUM( CASE WHEN p.ID IS NULL THEN 1 ELSE 0 END ) AS orphans
            FROM {$wpdb->postmeta} pm
            LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id";

    $where  = array();
    $params = array();

    if ( $key_like ) {
        $where[]  = 'pm.meta_key LIKE %s';
        $params[] = '%' . $wpdb->esc_like( $key_like ) . '%';
    }

    if ( $where ) {
        $sql .= ' WHERE ' . implode( ' AND ', $where );
    }

    $sql .= ' GROUP BY pm.meta_key';
    $sql .= ' HAVING total >= %d';
    $params[] = $min_total;

    $sql .= ' ORDER BY total DESC';

    $prepared = $wpdb->prepare( $sql, $params );
    $rows     = $wpdb->get_results( $prepared, ARRAY_A );

    if ( null === $rows ) {
        return new WP_Error(
            'meta_audit_query_failed',
            'The distribution query failed.',
            array( 'status' => 500 )
        );
    }

    $out = array();
    foreach ( $rows as $row ) {
        $total   = (int) $row['total'];
        $orphans = (int) $row['orphans'];
        $out[]   = array(
            'meta_key'        => $row['meta_key'],
            'total'           => $total,
            'orphans'         => $orphans,
            'live'            => $total - $orphans,
            'orphan_fraction' => $total > 0 ? round( $orphans / $total, 4 ) : 0.0,
        );
    }

    return new WP_REST_Response( $out, 200 );
}

Two details worth naming. First, esc_like() escapes the wildcard characters in the user-supplied pattern before they are wrapped in %; without it, a key_like of _ would match any single character. Second, HAVING is used rather than WHERE because the threshold applies to the aggregate, not to individual rows.

Return a response, do not emit one

The handbook is direct: a REST route’s callback should always return data and should not attempt to send the response body itself. Calling wp_send_json() or die( wp_json_encode( $data ) ) inside a REST callback bypasses the server’s handling of links, embedding, and headers, and since WordPress 5.5 triggers a _doing_it_wrong notice (Adding Custom Endpoints). Return WP_REST_Response or WP_Error and let the server serialize.

Reading the output

Request the endpoint with a nonce or an Application Password:

curl --user "USERNAME:APP_PASSWORD" \
  "https://example.com/wp-json/jv-meta-audit/v1/meta-keys?min_total=100"

A response row looks like this:

{
  "meta_key": "_elementor_data",
  "total": 40000,
  "orphans": 9000,
  "live": 31000,
  "orphan_fraction": 0.225
}

Sort by orphan_fraction descending to find the dangerous middle. A fraction of 1.0 is a fully dead key; a fraction of 0.0 is a live key; anything between is where a prefix delete would hit live posts. The live column is the one to quote in a cleanup ticket, because it is the number of rows a key-level delete would destroy.

For a quick sanity check against the endpoint, run the same aggregate in WP-CLI:

wp db query "SELECT pm.meta_key, COUNT(*) AS total,
  SUM(CASE WHEN p.ID IS NULL THEN 1 ELSE 0 END) AS orphans
  FROM wp_postmeta pm
  LEFT JOIN wp_posts p ON p.ID = pm.post_id
  GROUP BY pm.meta_key
  ORDER BY total DESC
  LIMIT 20;"

If the endpoint and the CLI disagree, the endpoint is filtering by min_total or key_like and the CLI is not. Check the query string before assuming a bug.

Optional: wrap it in a controller

If you expect to add per-key drill-down later — say, /meta-keys/{key}/orphans returning the post IDs — the controller pattern is the documented way to structure that. Subclass WP_REST_Controller, implement register_routes(), get_items(), and get_items_permissions_check(), and instantiate the class inside the rest_api_init callback (Controller Classes). The base class supplies prepare_response_for_collection(), get_collection_params(), and schema helpers you would otherwise reimplement. For a single read-only route, the closure above is less machinery; for a family of routes, the controller pays for itself.

Verification: prove the endpoint before trusting it

Three checks, in order:

  1. Route is registered. Visit /wp-json/jv-meta-audit/v1 while authenticated. The index should list the route. If it 404s, the rest_api_init callback did not run — check that the code is in a plugin or mu-plugin, not in a theme file loaded after the REST server initializes.
  2. Permission is enforced. Request the endpoint without credentials. You should get a rest_forbidden error, not data. If you get data, the permission_callback is returning true unconditionally.
  3. Numbers match a known key. Pick a meta_key you know is live on a specific post, request the endpoint with key_like set to that key, and confirm orphans is 0 and total is at least 1. Then pick a key you know belongs to a deleted post and confirm orphan_fraction is 1.0.

If you use Query Monitor, the endpoint’s query appears in the REST API request panel with the prepared SQL and the elapsed time. That is the place to confirm prepare() substituted the expected values rather than leaving a literal %s in the statement.

What this endpoint does not do

It reports. It does not delete. That separation is deliberate: mixing reporting and deletion in one route means a mis-scoped permission_callback or a stale nonce turns a diagnostic into a destructive action. With the endpoint read-only, the worst outcome of a bad request is a wrong number.

Deletion stays a separate, backed-up, batched operation. Export the table first (wp db export), delete in batches sized to your host, and re-run the endpoint afterward to confirm the orphan counts moved as expected. The endpoint tells you which keys are candidates; it does not tell you that a given key is safe to remove, because “safe” depends on whether the plugin that wrote it is coming back.

One more boundary: the endpoint reports the distribution of meta_key values in wp_postmeta. It says nothing about wp_usermeta, wp_termmeta, or wp_commentmeta, each of which has its own orphan problem and its own join target. If you find yourself wanting a unified view, that is a different endpoint with a different permission story.

FAQ

Why not just run the SQL in phpMyAdmin?

You can, and for a one-off audit you should. The endpoint earns its keep when the audit is recurring, when more than one person needs to see it without database credentials, or when you want the output in a shape a script can consume. It also keeps the query in version control, which a phpMyAdmin session does not.

Does the endpoint slow down the site?

It runs only when requested, and only for users with the capability you chose. It does not hook into front-end requests. The aggregate itself scans wp_postmeta, so on a very large table it will take time proportional to the table size; that is a property of the query, not of the endpoint. Run it during a quiet window if the table is large.

Can I filter to a single key?

Yes. Pass key_like as a query parameter. The value is escaped with esc_like() and wrapped in %, so it matches as a substring. For an exact match, add a separate key argument with an = comparison rather than overloading the LIKE.

What capability should I use?

There is no single correct answer. manage_options is the conservative default because the output describes the shape of the database. If you want editors to see it, register a custom capability such as read_postmeta_distribution and grant it to the roles that need it. The handbook’s guidance is to check a capability rather than merely checking login state (Adding Custom Endpoints).

Why does my curl request return rest_forbidden even with a valid login?

Cookie authentication requires the wp_rest nonce. Without it, the API treats the request as unauthenticated and sets the current user to 0 (Authentication). Use Application Passwords over HTTPS for command-line testing, or pass X-WP-Nonce from a page where the nonce is localized.