Skip to main content

25 posts tagged with "WordPress"

View all tags

WordPress same-name upload overwrites media? Disk-only dedup

Β· 11 min read

On a production site whose media library is offloaded to object storage in cloud-only mode (local copies deleted), an editor re-uploaded a cover image under a name that already existed months ago. The upload succeeded with no warning. That afternoon the site's theme vendor reported that a batch of older posts was showing the new image. The media library listed two separate attachments with different IDs; only readers noticed the pictures had changed.

TL;DR​

  1. WordPress core's same-name dedup, wp_unique_filename(), only scans the local upload directory. It never queries the database β€” the function body contains zero $wpdb calls β€” and it knows nothing about your bucket. With local files deleted, the disk is always empty, so dedup always approves the name, the upload reuses the same object key, and putObject overwrites the old object.
  2. The fix: hook wp_unique_filename (priority 999) and add three checks β€” a disk directory family-name scan, a _wp_attached_file family-prefix query, and per-key HEAD requests against the bucket (base / -scaled / -rotated Γ— extension set). If any face is occupied, increment WordPress-native -N names up to 20 rounds; if a dedup source errors out, fall back to a random suffix and upload unblocked.
  3. A pitfall worth copying: the object key equals the uploads-relative path, so the check set must carry the directory prefix. Our first version built keys from the bare basename, and a test fixture with a subdirectory immediately caught "bucket-face dedup misses every subdirectory upload" β€” 2026/11/hero.jpg and hero.jpg are unrelated strings to object storage.

URL Rewrites Miss JSON Images? Escape Forms Are the Reason

Β· 8 min read

During the final verification pass of a CDN migration for a client site, the homepage slider's large images and a 47MB background video were still serving from the origin domain, hogging a 5Mbps shared uplink β€” while the noscript fallback inside the very same element already pointed at the CDN domain. Half the element migrated, half didn't.

TL;DR​

  1. URLs don't only live in src="...". Slider plugins store image paths inside inline JSON ("src":"..." β€” colon form), often further escaped into https:\/\/ byte streams. An attribute-grammar rewrite surface (src=/srcset=/href= with a whitespace-required prefix) misses all of these, and a plain str_replace misses the escaped forms too.
  2. Close it with a storage-side three-form replace: inspect the stored form first, then replace plain, single-escaped, and double-escaped variants separately. We closed 204 occurrences across the three slides/slides7 tables of Slider Revolution. PHP serialized fields must go through the serialization engine; JSON fields can be replaced byte-for-byte.
  3. Then run a two-hop save fixpoint: two consecutive editor saves that leave the stored byte stream unchanged prove the save path writes back no old domain.

wp eval Works but REST 500s? Three WordPress Context Traps

Β· 9 min read

Three quiet WordPress plugin behaviors surfaced while building CCLEE B2B β€” a WooCommerce B2B plugin covering user management, differential pricing, quoting, and bulk ordering. The entry point was its PDF catalog download: on production the button returned the generic fatal-error page while the very same logic ran via wp eval; fixing the first layer exposed the second, and the second the third. The three root causes live on three different layers β€” deploy, context, filesystem β€” and they fit in one post.

TL;DR​

  1. Deploy layer: CI/rsync deploys never run composer install. If the plugin's vendor/ is hidden by stacked .gitignore rules (plugin-level /vendor/ plus repo-level vendor/ and plugins/), it never enters git, and the first new after require autoload is a Fatal. Fix: remove the ignore chain, commit vendor, smoke-test with class_exists after deploy.
  2. Context layer: REST requests never load wp-admin/includes/, so admin-only functions like wp_tempnam() throw Call to undefined function. wp eval works because CLI loads full WordPress β€” "it works in CLI" proves nothing about the REST context. Fix: function_exists guard plus a tempnam(sys_get_temp_dir(), ...) fallback.
  3. Filesystem layer: mPDF's default temp directory sits at vendor/mpdf/mpdf/tmp/. In the container, rsync preserved owner UID 1001 while PHP-FPM runs as www-data (UID 82), is_writable returns false, and chown fails on the volume-mounted filesystem. Fix: pass an explicit tempDir under the system temp directory at construction.

Yoast og:image Not Following CDN? The indexable Cache Bypass

Β· 8 min read

While doing the final verification pass on a CDN migration for a client site, a full crawl of 233 pages turned up 95 files whose og:image still pointed at the pre-migration domain and returned 404 β€” on the same pages where twitter:image and JSON-LD images were already serving the CDN domain. The rewrite pipeline covered the attachment output path, yet the social card image slipped through alone. This post records the diagnosis and the fix.

TL;DR​

  1. Yoast SEO (verified on 28.2) picks og:image through add_from_indexable, which consumes the open_graph_image_meta cache string first. The old domain lives inside that cached string and is returned verbatim β€” the WP attachment API is never touched, so URL rewrites attached to the attachment layer cannot intercept it.
  2. Two-step fix: hook a domain-swap callback on the wpseo_opengraph_image filter (shipped as 0.5.0 and deployed to both sites), then clear the cache with echo y | wp yoast index --reindex. Verification: all 95 affected files now return 200 (95/95), and a re-crawl of 233 pages shows zero og/twitter old-domain references.

WPML Switcher Not Changing? do_shortcode_tag Never Fires

Β· 8 min read

While reworking the header of a WordPress site β€” replacing the WPML language switcher with a single text link β€” the do_shortcode_tag filter I hooked changed nothing on the page: no error, no log entry, no cache to clear.

Ran into this while providing managed hosting for a WordPress site in China β€” full-site migration, image CDN offload, daily backups and automated patrols.

TL;DR​

The WPML 4.9.x language switcher never touches the WordPress shortcode pipeline: its shortcode_actions slot has no add_shortcode registration, and the HTML is rendered directly by the theme's header builder, so do_shortcode_tag never fires for it. To change the rendered output, the only place that works regardless of render path is the output buffer β€” hook ob_start on template_redirect and run bounded, anchor-based replacements. Every page ends up with exactly one header link, and rolling back means deleting one mu-plugin file.

Symptoms: the filter is hooked, the page ignores it​

Once the mu-plugin lands, the page renders the switcher exactly as before β€” no error, no log entry, no cache to clear.

The code looks unimpeachable β€” hook the filter, match the tag, replace the output:

add_filter( 'do_shortcode_tag', function ( $output, $tag ) {
if ( 'wpml_language_switcher' === $tag ) {
// replace switcher markup
return my_replace_switcher( $output );
}
return $output;
}, 10, 2 );

Searching "do_shortcode_tag not working" or "filter has no effect" mostly surfaces priority and argument-count advice; none of it helps.

Two usual suspects drop out quickly: there is no page-cache layer (origin responds with no-cache, and the public HTML is byte-identical to the origin), and the filter function itself is fine β€” calling it directly under wp eval returns the expected replacement markup. The function works, no cache exists, the page ignores it β€” the problem has to be further upstream.

Root cause: the WPML switcher bypasses the shortcode pipeline​

do_shortcode_tag lives in the core shortcode parsing loop; it only fires for markup that actually goes through do_shortcode().

Reading WPML 4.9.6 source: the switcher's shortcode_actions slot (classes/language-switcher/slots/class-wpml-ls-shortcode-actions-slot.php) never registers an add_shortcode, and its render method is invoked directly by the theme's header builder. On the other side, the theme (Impreza) contains zero do_shortcode references to this slot. With both ends disconnected, the shortcode pipeline simply isn't part of this HTML's birth path β€” and a filter on that pipeline waits forever.

Not a cache issue, not a priority issue, not a callback-signature issue: the filter is never called at all. The wp eval test produced a false signal precisely because it tests the function, not the pipeline.

Four false leads​

Cache first. CDN and page-cache layers checked β€” origin no-cache, public bytes identical to origin. Not a wrong direction, but it cost a round; confirming whether shortcodes participate in the render path should have come first.

The wp eval false positive. Calling the filter function directly returned the correct replacement markup, so "the function works" steered the hunt toward caching and priorities. In hindsight, a unit test proves nothing about the request path β€” same lesson as the plugin PDF download 500: the context wp eval loads is not the context a real request walks.

Zero hits on a full-database search. The handover notes said the switcher's host element carried the class ush_html_1; a wp db search across every table found 0 hits for that literal β€” one step from declaring the notes wrong. Reality: Impreza assembles element classes at runtime as ush_ + type + index, and the literal is never written to the database. To decide whether an element exists, read the rendered HTML; don't grep the database.

The "three flags" illusion. The requirement spoke of three language flags in the header; the WPML switcher renders only two (EN/BR). Grabbing every img tag on the page revealed the third "Chinese flag" as an independent media-library image element β€” a redundant self-link back to the site's own Chinese homepage, nowhere near the switcher block. When auditing header elements, dump the full img list first and classify second; don't stay trapped inside one component's markup.

Side pit: hand-calling apply_filters takes all 4 arguments​

A test fixture calling apply_filters( 'do_shortcode_tag', $out, $tag ) with 2 arguments died with ArgumentCountError on the spot. Reason: the instagram-feed plugin hooks the same filter with a callback requiring exactly 4 arguments (a cron status check), and an under-argued invocation fatals.

Production never trips this β€” core always passes 4 arguments. Only wp eval-style fixtures do, so fixtures should use the full form:

apply_filters( 'do_shortcode_tag', $out, $tag, '', '' );

Fix: bounded anchor replacement in the output buffer​

If the render layer can't be changed, change the final HTML after rendering: hook ob_start on template_redirect and run anchor-based regex replacements in the callback. The output buffer is indifferent to render paths β€” directly-rendered HTML passes through it too, which is exactly why this works.

Four design constraints:

  1. Front-end only: admin, ajax, cron and REST all bypass
  2. HTML guard: output without <html or <!doctype (feeds, JSON) is never touched
  3. Anchors must be stable features of the rendered markup (image filenames, aria-labels); bounded regex consumes only the anchor's block
  4. Idempotence: replacement output never contains its own anchors, so repeated runs don't stack
<?php
/**
* Plugin Name: Header Link Replace
* Description: Replace header language elements with a single text link via output buffering. Rollback = delete this file.
* Version: 1.0.0
*/

defined( 'ABSPATH' ) || exit;

function hlrep_link_html() {
return '<a href="https://example.com/en/" hreflang="en" lang="en" aria-label="English site" style="text-decoration:none;color:inherit">EN</a>';
}

function hlrep_buffer_start() {
if ( is_admin() || wp_doing_ajax() || wp_doing_cron() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
return;
}
ob_start( 'hlrep_buffer_flush' );
}

function hlrep_buffer_flush( $html ) {
if ( ! is_string( $html ) || '' === $html ) {
return $html;
}
if ( false === stripos( $html, '<html' ) && false === stripos( $html, '<!doctype html' ) ) {
return $html; // feeds/JSON etc. stay untouched.
}
$en = hlrep_link_html();
$done = 0;
if ( false !== stripos( $html, 'flag-cn.png' ) ) {
// (1) Swap the flag element in place: replace only the <a><img></a> anchor, keep the wrapper div.
$html = (string) preg_replace(
'#<a[^>]*>\s*<img[^>]*flag-cn\.png[^>]*/?>(?:\s*</a>)#is',
$en,
$html,
1,
$done
);
}
if ( false === stripos( $html, 'aria-label="Language Switcher"' ) ) {
return $html;
}
// (2) Switcher block: with (1) present, blank it to avoid a double link; otherwise fall back to the link.
$html = (string) preg_replace(
'#<div[^>]*aria-label="Language Switcher"[^>]*>.*?</div>#is',
$done ? '' : $en,
$html,
1
);
return $html;
}
add_action( 'template_redirect', 'hlrep_buffer_start', 1 );

Division of labor between the two anchors: on pages with a flag image, the link lands in the flag's original spot (only the <a><img></a> anchor is replaced; the wrapper div stays, so the position holds) and the switcher block is blanked to prevent a duplicate; on pages without a flag, the fallback branch puts the link where the switcher was. Together, every page ends up with exactly one header link.

This went through three iterations: v1.0 was a single-anchor replacement of the switcher β€” through the very filter pipeline that got falsified, so it failed outright; v1.1 moved to the output buffer but only handled the flag image, leaving flag-less pages without the link; v1.2 added the dual-anchor fallback and closed the loop. The single-anchor version passed functional checks; its gap was page coverage β€” acceptance lists must include the flag-less pages.

Deployment and verification: pass php -l before the file lands in wp-content/mu-plugins/; the verification metric is anchor counting on rendered HTML β€” flag 0, switcher marker 0, target link 1. Rollback equals renaming the file, zero database changes. The site also runs a sibling ob mu-plugin (font-domain rewrite); the two layers stack and regress cleanly β€” output buffers nest, and each handles its own anchors.

Note

Anchors must come from measured rendered markup (grab the HTML and confirm), never guessed from theme templates or the database β€” classes may be runtime-assembled, and database greps will always return 0 hits. The .*? plus "first closing tag ends the block" pattern assumes no nested same-name structure inside; verify, or switch to a safer anchor and a bounded match. Replacement output must not contain its own anchors, or stacked runs will replace twice. And since the ob layer edits final HTML, search engines and structured data see the replaced markup too β€” confirm that is what you want.

FAQ​

How do I customize the WPML language switcher output?​

Check your version's source first: the 4.9.6 shortcode_actions slot has no add_shortcode registration and renders directly from the header builder, so every hook on the shortcode pipeline misses it. The fallback is output buffering β€” hook ob_start on template_redirect and replace anchors in the final HTML.

Why doesn't the do_shortcode_tag filter fire in WordPress?​

The filter only runs for markup produced by do_shortcode(). WPML 4.9.6 registers no shortcode for its switcher slot and the theme never calls do_shortcode on it either, so the filter is simply never invoked β€” verify against rendered HTML, not function-level unit tests.

Why does hand-calling apply_filters('do_shortcode_tag') throw ArgumentCountError?​

Other plugins hook the same filter β€” instagram-feed registers a callback requiring exactly 4 arguments, so a 2-argument test call fatals. Production never hits this because core always passes 4; fixtures should call it with the full 4-argument form.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

WooCommerce Checkout Template Not Applied? Plugin Override

Β· 5 min read

After assigning the theme's checkout template to the Checkout page, the front end still renders WooCommerce's own structure β€” the theme template's heading and footer are nowhere in the output, while the body class reports the assignment as active.

Ran into this while building a minimal FSE WordPress theme for a client β€” a full-site-editing theme for corporate sites and lightweight e-commerce, with WooCommerce compatibility kept intentionally thin.

TL;DR​

WooCommerce hooks page_template_hierarchy at priority 1 and unshifts its own template slugs (checkout, cart) to the front of the hierarchy array, so the plugin template outranks nearly every candidate. Manually setting _wp_page_template on the page at that point only creates a second, conflicting signal β€” the body class reads the meta while the render follows the filter. The fix: delete the manually set _wp_page_template and let the hierarchy filter resolve.

Symptom: Body Class Says Theme Template, Render Is the Plugin's​

The template assignment in the page editor clearly names the theme's checkout template, and the body class faithfully shows page-template-checkout; the front-end output, however, is WooCommerce's page-content-wrapper β€” store notices and product content only, none of the heading and footer structure from the theme template.

The diagnostic marker is a single attribute: check whether the page's <main> element carries data-block-name="woocommerce/page-content-wrapper". If it does, WooCommerce's plugin template is what actually renders β€” the theme template has been sidelined, confirmed.

A symptom as self-contradictory as "body class says A, render shows B" almost always means two signal sources that never sync β€” and this machine has exactly one such pair.

Root Cause: page_template_hierarchy Cuts In at Priority 1​

WooCommerce's AbstractPageTemplate registers the filter in init():

add_filter( 'page_template_hierarchy', array( $this, 'page_template_hierarchy' ), 1 );

The callback is a one-line array_unshift: when the page matches the Checkout/Cart scenario, its own template slug goes to the front of the candidate array. The source comments state it plainly β€” priority 1 is deliberate, to run first; extensions using the default priority 10 line up behind it.

WordPress resolves templates by walking the array and taking the first file that exists. With checkout at the front: if the theme ships a template file of that name, the theme's wins; if not, resolution lands on WooCommerce's registered plugin template of the same slug (page-checkout.html, containing the woocommerce/page-content-wrapper structure).

Why does manually setting _wp_page_template backfire? That meta only feeds the body class and the editor display β€” it never enters the filter's resolution order. Its signal and the filter's result travel on separate tracks, producing the stalemate "assignment shows active, render doesn't move".

Fix: Delete _wp_page_template and Let the Hierarchy Filter Resolve​

Delete the manually set template meta and let WooCommerce's resolution mechanism run:

wp post meta delete <page_id> _wp_page_template

After deletion, body class and render agree again: whatever the filter resolves is what renders, and the body class reflects it. No template meta should be set explicitly on pages WooCommerce owns β€” the hierarchy filter is the authoritative signal.

A separate structural pitfall of the Cart template (placeholders and SSR rendering) lives at the same template layer and is worth checking alongside Checkout.

Caution

When verifying the fix, do not set _wp_page_template back "just to test" β€” that is the very source of the conflicting signal. The Cart page runs the same mechanism; if it shows the same assignment-ignored behavior, treat it identically, diagnosing with the same data-block-name="woocommerce/page-content-wrapper" marker.

FAQ​

How does WooCommerce win template resolution?​

It hooks page_template_hierarchy at priority 1, earlier than consumers at the default priority 10, and unshifts its template slug to the front of the hierarchy array. The WooCommerce source comments state this priority is intentional.

Why do the body class and the actual render disagree?​

Two separate signal sources: the body class is generated directly from the _wp_page_template meta, while the rendered template is decided by the hierarchy filter's array order. A manually set meta falls out of sync with the filter's result.

How do I confirm the plugin template is the one rendering?​

There is exactly one reliable marker: the data-block-name attribute on the main element. data-block-name="woocommerce/page-content-wrapper" means the plugin template renders; a theme-template main is built from the theme's own blocks and carries no such marker.

Is the Cart page taken over the same way?​

Yes. The same AbstractPageTemplate mechanism has two implementations, CartTemplate and CheckoutTemplate, covering both the Cart and Checkout pages β€” the same data-block-name marker diagnoses them.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

WooCommerce Gallery Images Not Loading? FlexSlider Conflict

Β· 6 min read

Flipping through the product gallery thumbnails on a WooCommerce product page, everything works until slide seven β€” from there the main image stays blank, and the DevTools Network panel shows no request was ever sent.

Ran into this while building a minimal FSE WordPress theme for a client β€” a full-site-editing theme for corporate sites and lightweight e-commerce, with WooCommerce compatibility kept intentionally thin. The issue was ultimately fixed inside the theme with a single filter.

TL;DR​

WordPress 5.5+ automatically injects loading="lazy" into content images, while WooCommerce's FlexSlider gallery moves non-active slides out of the viewport with CSS transforms. Together, the IntersectionObserver that native lazy loading depends on never sees those images enter its trigger range β€” no request is ever sent. The fix: a wp_get_attachment_image_attributes filter that removes the loading attribute for the woocommerce_single size only.

The first few gallery images render fine; from a certain slide onward the main image area stays blank. The same problem surfaces under searches like "gallery images not showing" or "product images won't load".

DevTools shows three facts at once:

  1. The <img> node exists with a valid src attribute;
  2. The <img> carries loading="lazy";
  3. The Network panel has no matching request β€” not a failed load, the browser never started the download.

"A src but no request" is the dividing line between this problem and image 404s or broken paths: those show requests and errors, this one is completely silent.

Root Cause: Native Lazy Loading Stacked on Slider Off-Screen Layout​

Every gallery image sits in the state "has a src, not visible, waiting for the browser to decide" β€” and FlexSlider's layout makes the "visible" condition permanently unreachable. The mechanism has three layers:

Layer 1: WordPress injects lazy loading automatically. Since WordPress 5.5, images output by wp_get_attachment_image() carry loading="lazy" by default (the first image excepted). Product gallery main images use the woocommerce_single size, so all of them match this rule. The intent is bandwidth savings: only load images near the viewport.

Layer 2: FlexSlider moves non-active frames off-screen. FlexSlider arranges all slides in one horizontal strip; slides outside the current frame sit beyond the viewport and swap positions via CSS transforms.

Layer 3: IntersectionObserver's trigger condition is never met. Browser lazy loading is not "load when visible" but "preload when within a threshold" β€” about 1250px for images on desktop Chrome, expanding to 2500px on slow connections. In a horizontal slider, the distance between slide N and the viewport grows linearly with its index; past the threshold, IntersectionObserver never fires. In practice, from slide seven onward not a single request goes out.

The entire chain throws no error: the img has a src, the page logs no JS exception, the server log is clean β€” the browser simply classified those images as "not needed yet". That is what makes this expensive to diagnose: each component behaves exactly as documented, and the combination deadlocks.

A wp_get_attachment_image_attributes filter that unsets loading for woocommerce_single images returns gallery images to default eager loading, and the problem disappears.

add_filter(
'wp_get_attachment_image_attributes',
function ( $attr, $attachment, $size ) {
if ( 'woocommerce_single' === $size ) {
unset( $attr['loading'] );
}
return $attr;
},
10,
3
);

Drop it into the theme's functions.php or an inc module; child theme users should put it in the child's functions.php without touching the parent.

Why it works: once the loading attribute is gone, the browser falls back to immediate loading β€” requests fire during HTML parsing, and FlexSlider's positioning only affects display from then on, never loading. Ordinary content images never pass through a slider, so their lazy loading works and should stay; gallery images have their visibility managed by the slider, so the loading decision goes back to the browser default.

CCLEE Theme ships this filter built in (inc/woocommerce.php) β€” update the theme and you are covered.

If you are also chasing other WooCommerce block theme rendering issues, gallery problems tend to appear alongside template structure issues, so it is worth reviewing both.

Caution

Do not remove loading globally for convenience β€” immediate loading for everything below the fold slows the page down, and lazy loading is a pure win for body images. Keep the condition locked to the woocommerce_single size. If you switch sliders (e.g. Swiper), check whether the new slider ships its own lazy-loading module first to avoid stacking two mechanisms.

FAQ​

Why do images with a src attribute never trigger a network request?​

loading="lazy" hands the timing to the browser: when an image sits beyond the preload threshold (about 1250px on desktop Chrome), IntersectionObserver never fires and the request is never sent. A src value only means the DOM is ready β€” loading depends on the visibility check.

Can I just remove all loading="lazy" attributes site-wide?​

It fixes the gallery, but every image below the fold switches to immediate loading, costing bandwidth and competing with LCP resources. Keep global lazy loading and strip the attribute only for the woocommerce_single size with a filter.

Which slider libraries cause the same problem?​

Any horizontal slider that moves non-active frames out of the viewport: FlexSlider, Swiper, Slick, and similar. If the slider ships its own lazy-loading module (like Swiper's lazy option), use that and remove the native loading attribute to avoid conflicting mechanisms.

Since which WordPress version does this problem exist?​

WordPress 5.5 (2020) introduced native lazy loading, and since 5.9 every content image except the first gets loading="lazy" by default. The problem appears whenever a product gallery uses a translating slider, regardless of WooCommerce or slider version.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

WooCommerce PayPal Buttons Not Showing? Missing form.cart

Β· 5 min read

Scrolling down to the payment area on a WooCommerce variable product page, the PayPal button spot is completely blank β€” the container is there, the button is gone, and the browser console shows no error at all.

Ran into this while building CCLEE B2B, a WooCommerce B2B enhancement plugin covering customer group management, tiered pricing, and bulk ordering β€” and stepped on an undocumented behavior of PayPal Complete Payments (PPCP).

TL;DR​

The first thing PPCP's button script does in init() is document.querySelector("form.cart") β€” if nothing matches, it returns silently with no log. Customizations like a B2B variation matrix remove the standard add-to-cart form with remove_action, form.cart disappears with it, and PayPal buttons never render again. The fix: wrap the PayPal container in a minimal form.cart, with onsubmit="return false" to block real submissions.

Symptom: Empty PayPal Button Spot, Clean Console​

Everything else on the product page works; the standard add-to-cart button is gone by design, but the PayPal buttons that should appear simply don't render. Searches for "PayPal button not showing" or "PayPal button not rendering" all describe this same situation.

DevTools shows three facts:

  1. The page HTML contains PPCP's button container #ppc-button-ppcp-gateway;
  2. The container is empty β€” not half-rendered, an empty div;
  3. The console has no errors or warnings, and the ppcp-button script itself loads fine.

"Script loaded, container present, button missing, zero logs" means the problem is not in the network or error layer β€” it is inside the script's own logic branch.

Root Cause: PPCP's form.cart Precondition Check and Silent Skip​

The ppcp-button script (ppcp-button-js-button.js) starts its init() with document.querySelector("form.cart") β€” no match, no render, no message. This behavior is absent from PPCP's official documentation; you confirm it by reading the source or comparing against a working product page.

Why would form.cart disappear? WooCommerce's standard add-to-cart form is output by woocommerce_template_single_add_to_cart. B2B variation matrices, quote flows, and price-hiding customizations commonly remove it outright:

remove_action(
'woocommerce_single_product_summary',
'woocommerce_template_single_add_to_cart',
10
);

That one cut removes more than the add-to-cart button β€” it also removes the form.cart that PPCP requires before rendering. The custom purchase UI works flawlessly, the page logs nothing β€” only the PayPal button vanishes.

The silence is what makes this expensive to diagnose: the script reasons "no form, no render target" and quietly exits. You can watch ppcp-button JS download and execute in the Network panel, you can see the button container in the DOM, and not a single line tells you why it chose to do nothing.

Fix: Wrap the PayPal Container in a Minimal form.cart​

Wrap the PayPal container in a minimal form.cart at the spot where it renders, and PPCP's precondition check passes β€” buttons come back.

add_action( 'woocommerce_single_product_summary', function () {
echo '<form class="cart" onsubmit="return false;">';
echo '<div id="ppc-button-ppcp-gateway" class="ppc-button-wrapper"></div>';
echo '</form>';
}, 25 );

Each part has one job:

  • class="cart" β€” PPCP checks this class, not an id; keep it verbatim;
  • onsubmit="return false;" β€” the form is real in the DOM, so a submit triggered by the Enter key or other scripts would reload the page and lose the selected variation; this blocks them all;
  • The container div's id ppc-button-ppcp-gateway is PPCP's convention β€” match the actual container id on your page.

The full version in CCLEE B2B also fires PPCP's own render action, for reference:

do_action( 'woocommerce_paypal_payments_single_product_button_render' );

If you are deep into customizing WooCommerce templates and purchase flows, the block theme troubleshooting guide covers other common pitfalls at the template layer.

Caution

PPCP is not the only component watching form.cart β€” third-party add-to-cart enhancers and tracking plugins may listen to it too. After adding the form, walk through a full order in a private window and confirm no script double-fires because of it; do not omit onsubmit="return false", or the Enter key alone will reload the page.

FAQ​

Why does removing the standard add-to-cart form make PayPal buttons disappear?​

The standard form is output by woocommerce_template_single_add_to_cart on the woocommerce_single_product_summary hook at default priority 10. Once remove_action takes it away, the PPCP button script finds no form.cart at init and skips rendering entirely.

How do I quickly confirm the missing form.cart is the cause?​

Check two things: a clean console, and a ppc-button-ppcp-gateway container in the DOM that exists but stays empty. Then temporarily insert an empty <form class="cart"></form> on the product page and reload β€” if buttons appear, that is the cause.

Can I inject the form.cart with JavaScript on the frontend?​

No. PPCP's init() runs its check once during script initialization; a form inserted afterwards never triggers a re-check. The form.cart must be rendered server-side so it exists before the script runs.

Is onsubmit="return false" required?​

Yes. The wrapper form.cart is a real form β€” a submit triggered by the Enter key or other scripts reloads the page and loses the selected variation. PPCP's dependency on the form actually submitting is zero; return false blocks every submission path.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

WooCommerce Variable Product Price Not Changing? Parent Only

Β· 5 min read

Running regular_price updates against a Variable product via WP-CLI completes with a success message and the admin shows the new price β€” yet the product page and the JSON-LD keep displaying the old one.

Ran into this while building Cross-border Product Listing Assistant β€” one-click product sourcing with AI-generated descriptions and pricing, published to WooCommerce after review β€” and stepped on a quiet WooCommerce behavior.

TL;DR​

wp wc product update on a Variable product writes the parent product's meta only β€” no iteration, no cascade, no hint. The storefront price and the JSON-LD schema both read the variation's _price, while the parent price serves only the admin display, and the wc_product_meta_lookup table keeps the old value too. The fix: list every variation under the parent, then update them one by one with wp wc product_variation update.

Symptom: Command Succeeds, Storefront Price Doesn't Move​

wp wc product update 187 --regular_price="16.00" --user=admin --allow-root
# Success: Updated product 187.

Three observations make up the full picture:

  1. The command returns success, without any warning;
  2. In the admin, the parent product's price field already shows the new value;
  3. The product page, price filters, and JSON-LD structured data all still show the old price.

Searches like "price not updating" or "changed price but storefront unchanged" all describe this path. The confusing part is the success message β€” it truthfully reports "parent updated", it just never claims the parent is where the storefront price comes from.

Root Cause: The Parent Price Is Admin Display, the Real Price Lives in Variations​

A Variable product's price storage is layered: the parent's regular_price in meta serves the admin edit screen; the product page display, cart calculations, and the JSON-LD schema all read each variation's own _price.

wp wc product update stops exactly at the parent layer β€” it does not iterate variations, does not cascade, and does not warn. After it writes the parent meta:

  • Every variation's _price is untouched;
  • WooCommerce's performance lookup table wc_product_meta_lookup (created in its class-wc-install.php) also keeps the old value, so read paths going through the lookup table return the old price as well.

Of a three-layer read system, only the least important layer got updated. Nothing along the chain ever says "variations not synced" β€” which is what makes this expensive to diagnose: every step looks like success.

A cache layer holding stale values and bypassing the normal update chain is not unique to WooCommerce β€” Yoast SEO's og:image serves an indexable cache string directly, bypassing the attachment API; same-shaped root cause, see Yoast og:image Not Following CDN.

Fix: Update the Variations One by One​

First list every variation under the parent:

wp wc product list --parent=187 --fields=id,sku,regular_price --user=admin --allow-root

Then update them individually (wp wc product_variation update accepts one VID per call):

wp wc product_variation update 187 1201 --regular_price="16.00" --user=admin --allow-root
wp wc product_variation update 187 1202 --regular_price="16.00" --user=admin --allow-root

Updating through the variation endpoint goes through WooCommerce's CRUD: the variation meta and the wc_product_meta_lookup table get synced by WooCommerce itself, so the storefront, JSON-LD, and filters all read one consistent new price. For products with many variations, a loop script handles it β€” one VID per call.

All commands here run inside a Docker container; see Running WP-CLI in Docker for the containerized setup.

Caution

The wp wc command family requires an authenticated user β€” never drop --user; and do not take the shortcut of a raw database UPDATE β€” bypassing CRUD desyncs the wc_product_meta_lookup table from the meta, and the storefront can still read the old price.

FAQ​

Why does the admin show the new price while the storefront keeps the old one?​

Two separate read paths: the parent product's edit screen reads the parent's own meta, while the storefront price and JSON-LD both come from the variation's _price. Updating the parent only refreshes the admin-facing copy; the storefront path never moves.

Can I just UPDATE the _price rows in the database?​

Not recommended. Writing to wp_postmeta directly leaves the wc_product_meta_lookup table out of sync, and some read paths keep returning the old price. Use wp wc product_variation update so WooCommerce's CRUD syncs both stores.

Is there a way to update all variations in bulk?​

wp wc product_variation update accepts one VID per call, so bulk updates need a script loop: list every variation ID with --parent first, then run the update for each.

Do Simple products have this problem too?​

No. Simple products have no variations, so the price wp wc product update writes is the storefront price. The non-cascading update is a structural issue unique to Variable products.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

WordPress PDF Download 500? Vendor, REST Context, tempDir

Β· 5 min read

Clicking the PDF catalog download on a product page first produces WordPress's "There has been a critical error on this website"; after the missing-library problem is fixed, the same endpoint switches to HTTP 500 β€” three independent pits, stacked into one failure chain.

Ran into this while building CCLEE B2B, a WooCommerce B2B enhancement plugin covering customer group management, tiered pricing, and bulk ordering β€” the PDF catalog feature walked through all three.

TL;DR​

PitRoot CauseFix
Critical errorvendor never entered git, rsync deployed without libraries.gitignore exception + force-commit vendor
REST endpoint 500admin-only functions absent in REST contextfunction_exists guard + tempnam() fallback
Still 500 after fixesmPDF's default temp dir unwritable in containerpoint tempDir at sys_get_temp_dir()

All three share one backdrop: a CI + rsync containerized deployment pipeline. None of them reproduces on a standard LAMP host β€” they are almost pure products of the container-plus-REST combination.

Pit 1: "There has been a critical error" β€” vendor never reached the server​

Symptom: everything works locally; after deployment, clicking download yields WordPress's generic fatal error page.

Root cause: vendor/ (the mPDF library) never reached the server. The chain is doubled: the plugin's own .gitignore excludes /vendor/, and the repo root .gitignore carries both vendor/ and plugins/ rules, masking tracked files at the top level. CI checkout skips untracked files, rsync faithfully mirrors a library-less directory, and on the server require_once vendor/autoload.php fatals immediately.

Fix: remove /vendor/ from the plugin .gitignore, add an exception at the repo root, then force-commit:

git add -f wp/plugins/cclee-b2b/vendor/

When a WordPress plugin ships via CI + rsync, the server never runs composer install β€” vendor must go into git as part of the source.

Pit 2: wp eval Works, REST Endpoint 500 β€” Admin Functions Missing​

Symptom: with vendor in place, calling the PDF generation method through wp eval works; the REST endpoint /wp-json/cclee-b2b/v1/pdf-catalog returns 500.

Root cause: two calls incompatible with the REST context. wp_tempnam() is defined in wp-admin/includes/file.php β€” REST requests never load that directory, so the call fatals. WC()->shop_management is not a public WooCommerce property either, and the fallback path fatals the same way. wp eval avoids all of this precisely because the CLI loads full WordPress including admin files.

Fix: guard admin functions with an existence check and fall back to PHP native:

$tmp = function_exists( 'wp_tempnam' )
? wp_tempnam( $filename )
: tempnam( sys_get_temp_dir(), 'pdf' );

The shop name moves to the public API: get_bloginfo( 'name' ). Inside REST, treat everything under wp-admin/includes/ as nonexistent.

Pit 3: Dependencies in Place, Still 500 β€” mPDF Temp Dir Unwritable​

Symptom: the class loads, no more fatals, yet REST still returns 500. The server access log keeps a single 858-byte response.

Root cause: mPDF defaults to vendor/mpdf/mpdf/tmp/ as its temp directory; rsync preserves the source owner UID 1001 while PHP-FPM inside the container runs as www-data (UID 82). The directory is unwritable and the mPDF constructor throws. Attempting chown inside the container fails too β€” the volume-mounted filesystem doesn't allow it.

Fix: point the temp directory at the system /tmp explicitly:

$mpdf_tmp = sys_get_temp_dir() . '/mpdf';
if ( ! is_dir( $mpdf_tmp ) ) {
wp_mkdir_p( $mpdf_tmp );
}

$mpdf = new \Mpdf\Mpdf( array(
'mode' => 'utf-8',
'format' => 'A4',
'tempDir' => $mpdf_tmp,
) );

There is a shortcut for diagnosing this class of 500: wp eval-file calls the internal method directly, bypassing the REST route and permission checks, and the exception stack arrives in one step. Silent skips of this kind are not unique to PDF generation β€” PPCP buttons silently skipping render is another example.

Caution

Verify the three fixes in order: vendor lands first, then test the REST context, and only then the temp directory β€” skipping steps misattributes which fix killed the 500. Also, the function_exists guard is not a long-term shape; if the plugin claims to run outside admin contexts, its temp-file logic should never touch wp-admin/includes/ at all.

FAQ​

Why does wp eval work while the REST endpoint returns 500?​

The CLI environment loads full WordPress including wp-admin/includes/, while REST requests never load that directory. Code depending on admin-only functions like wp_tempnam runs fine under wp eval and Fatal Errors inside REST β€” the two contexts load different file sets.

How do I find the actual exception behind a REST 500?​

Call the plugin's internal method directly with wp eval-file, bypassing the REST route and permission checks β€” the exception stack arrives in one step, far more useful than an 858-byte 500 page.

Should a containerized WordPress plugin deployment run composer install on the server?​

Don't count on it β€” in a CI plus rsync pipeline the server never runs composer install. The vendor directory must be committed to git and land on the server through rsync; a plugin .gitignore that excludes /vendor/ ships a broken plugin.

Why is a library's built-in temp dir unwritable inside a container?​

rsync preserves the source machine's owner UID (say 1001) while PHP-FPM inside the container runs as another identity (www-data, UID 82), so the default temp dir under vendor/ becomes unwritable β€” and volume-mounted filesystems often refuse chown. Point tempDir at sys_get_temp_dir() explicitly.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me