Opens in a new tab

WordPress PHP 8 count() TypeError: Causes and Safe Fixes

WordPress PHP 8 count() TypeError? Trace invalid null, false or string inputs to the plugin or theme and verify a safe, tested fix.

FREE WORDPRESS PLUGIN

PHP Upgrade Risk Audit

Before switching PHP, scan installed plugins and themes for known PHP 8 compatibility risks—without changing your server runtime.

  1. Install the plugin
  2. Choose your target PHP version
  3. Review the scan findings
Get the free plugin See how the scan works

Read-only risk scan, not a repair. If your site is down, restore access first. Test on staging; the official WordPress.org URL remains unchanged after the brand update.

Illustration: WordPress PHP 8 count() TypeError: Causes and Safe Fixes

Does WordPress show Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, null given after you move to PHP 8? A plugin, theme or custom function passed a value that PHP cannot count. You need two pieces of evidence: where the call happened and why that variable contained the unexpected value. Fixing only the visible count() line can hide a failed API request or broken product data.

Fast path: preserve the exact exception and stack trace; identify the owning plugin or theme and the triggering action; trace the value that reached count(); update the responsible component or repair its input contract; then reproduce the same workflow on staging. For a site that is entirely offline after a runtime switch, first use our WordPress critical-error recovery guide to regain access without losing the evidence. This guide is specifically about the countable argument error, not every possible PHP 8 fatal.

What the error means, exactly

Fatal message suffix What actually reached count() First investigative question
null given No value (null) instead of an array/Countable object Did a setting, lookup or conditional path return no usable data?
bool given A boolean such as false Did an API, database function, cache read or parser return a failure sentinel?
string given A string, not a list Was a single value stored where an array was expected, or did a format change?
stdClass given (or another ordinary class) An object that does not implement Countable Does the caller expect an array but now receive a different object contract?
These are examples of invalid input classes, not a diagnosis of your specific plugin. A Traversable value is not necessarily Countable; verify the actual type.

The PHP count() manual defines the accepted input as an array or an object implementing Countable. On PHP 7.2–7.4, an invalid argument caused a warning; PHP 8.0 and later throw a TypeError. The official PHP 8 incompatibility reference lists this specific warning-to-exception conversion. The runtime changed its error handling; it did not turn a correctly shaped array into an invalid value.

Real WordPress cases: why the same error has different owners

A WordPress.org support report for Customer Reviews for WooCommerce included the exact count() TypeError with false given under PHP 8.4, pointing into that plugin’s review-image code. The response discussed its uploaded-review-image behavior. That is evidence that a concrete plugin workflow can expose a bad value—not a finding that currently updated versions of the plugin are universally broken.

A separate TranslatePress WordPress.org support report described null given inside the plugin’s editor API code on PHP 8.1. The examples have different input types and feature triggers, which is why a shared PHP error message does not identify a universal code fix. You should not copy a patch from one into an unrelated site simply because the same PHP function appears in the error.

1. Recover access and preserve the original exception

If the site went down immediately after changing the server PHP version, verify that you can return to the last known working configuration using your host’s supported PHP selector and tested recovery point. A temporary rollback can restore access while you fix the problem; it is not a permanent reason to run obsolete PHP. Record the actual web-serving PHP version, not merely what php -v reports for the command-line interpreter.

WordPress can send a Recovery Mode email naming the component for certain fatal failures. If available, use it to investigate the named extension, but do not expect Recovery Mode to catch every background, REST, AJAX or bootstrap failure. Your host’s PHP-FPM/web-server error log may be the most complete record.

The WordPress debugging handbook documents WP_DEBUG_LOG and warns about exposing errors. Enable logging only through an authorized, reviewed configuration when necessary, retain it for the shortest useful period, and keep WP_DEBUG_DISPLAY disabled for public traffic. A public stack trace may expose filesystem paths or sensitive context. For a payment or membership website, avoid reproducing failures through real customer actions; use a properly isolated test.

2. Find the failing call and its actual owner

Keep the exception message, file and line, and several relevant stack frames. A typical trace may name wp-content/plugins/example-plugin/includes/handler.php, wp-content/themes/example-theme/functions.php, an MU-plugin, or custom snippet code. Those paths identify where the invalid value reached the failing call. They do not by themselves prove whether the plugin wrote the bad value or received it from another component.

Location in trace What it suggests What to inspect
wp-content/plugins/name/... Plugin’s code executed the failing call Installed version, relevant feature and any vendor fix; earlier frames and input source
wp-content/themes/name/... Theme or its integrated component is involved Theme version, template data and custom overrides
wp-content/mu-plugins/... Must-use code may be involved Source ownership, deployment history and site-specific contracts
wp-includes/... Core appears in the call stack Trace farther to the caller supplying the wrong argument; do not edit Core as a first response

Do not assume a site-wide crash: the error might appear only when viewing reviews, loading a translation editor, saving a form, calculating a product offer, or running a scheduled job. Record the exact operation that triggered it. If your exception instead says call_user_func_array(): Argument #1 ($callback) must be a valid callback, use our invalid WordPress hook callback guide; that is a different failure. If the message says Call to undefined function create_function(), see our removed create_function() guide.

3. Follow the variable backward, not just the line number

When you have a reproducible case on staging and permission to inspect the owning source, look at the value passed to count(). Trace it back to its producer: a setting retrieved with get_option(), an API response, a decoded JSON payload, a taxonomy lookup, a callback argument, a data-store read, or a transformed array. This is the actual repair decision.

For example, a custom component expects an array of configuration values. But if the option was never created, WordPress get_option() can return a default or a falsey missing-value sentinel depending on how it was called. Similarly, an external request that failed should not be reinterpreted as “zero items successfully fetched.”

// Illustrative custom-code example; do not paste into production blindly.
$items = get_option( 'example_items', array() );

// This is reasonable only if "missing option" truly means "no items"
// AND any previously stored data is validated before counting.
if ( ! is_array( $items ) ) {
    // Log or report unexpected stored data instead of silently erasing it.
    throw new UnexpectedValueException( 'example_items must be an array' );
}

$item_count = count( $items );

The above is a contract check in code you own, not a recommendation to modify another vendor’s plugin files. If a missing option should be treated as empty, the default is meaningful. If a database or network error produced false, the correct response may be to report the failure or retry a controlled operation—not silently continue with zero and falsely claim that an order, sync or report was complete.

4. Choose the correct fix for null, false, string or object input

Confirmed input contract Appropriate engineering direction Unsafe shortcut
Missing data legitimately means an empty list Initialize an empty array at the producer or explicitly document an empty result Turn all errors, including retrieval failures, into an empty list
Repository or API returns a failure sentinel Handle that failure state and restore the underlying dependency Convert false to zero and mark the business task successful
String represents one item, but the consumer requires a list Normalize and validate at the contract boundary where its meaning is known Cast every string into an array without checking schema
Object implements Countable Use count() if its defined count semantics fit the task Assume all objects or all iterable objects implement Countable
Unexpected object, null, or mixed data Trace the source and fail explicitly or apply an authorized business fallback Suppress the error, force (array) or unconditionally return 0

is_countable() was introduced in PHP 7.3 and returns true for arrays and objects implementing Countable. It can help when your intended contract genuinely permits those types:

Guide content map: What the error means, exactly; Real WordPress cases: why the same error has different owners; 1. Recover access and preserve the original exception; 2. Find the failing call and its actual owner
Overview of major sections; not a chronological workflow.
// Useful only when the documented business rule permits
// a non-countable value to mean "no items".
$number_of_items = is_countable( $items ) ? count( $items ) : 0;

Do not apply that fallback universally. It would also turn unexpected data corruption, failed retrievals and invalid API responses into a normal-looking zero. In a booking, checkout, inventory or financial workflow this can be materially wrong. Prefer fixing the producer or explicitly rejecting invalid values when correctness depends on them. For a PHP 7.2-or-earlier runtime, is_countable() is unavailable; consider the supported runtime contract before using this syntax in older shared code.

5. Prefer vendor-supported updates to hot-patching live plugins

If the trace points into a maintained third-party extension or theme, check its installed version, release notes, issue tracker and current compatibility statement. A later release may have corrected the input contract or implemented explicit guards. Test the vendor update on a faithful staging environment and reproduce the exact original request with representative data.

For custom code you own, a targeted fix should include a test for the valid data shape, missing-but-legitimate empty values, genuine retrieval failure, and any known legacy stored formats. Do not suppress TypeError in a catch-all handler simply to keep the homepage responsive while leaving a background business process silently incomplete. Avoid modifying the WordPress Core files or editing vendor files in place; those changes will be overwritten by updates and complicate attribution.

6. Verify the real workflow on staging

A passing homepage is not enough if the original failure appeared only in an admin screen, REST request, scheduled action or WooCommerce feature. Recreate the failing path on staging using the same target PHP minor version, relevant plugin/theme versions, and sanitized representative data.

  1. Reproduce and preserve: capture the original failing input type and stack location before applying a fix.
  2. Apply one change: upgrade the owning component or repair its documented producer/consumer contract.
  3. Test valid input: a normal array or intended Countable value produces a correct count and correct downstream result.
  4. Test empty input: a legitimately empty list yields the intended behavior without swallowing unrelated failures.
  5. Test failed retrieval and legacy input: the operation reports an error or handles the known representation explicitly instead of inventing zero.
  6. Check business effects: the original product review, translation editor, checkout, inventory, or background task actually completes correctly and leaves no new PHP fatal.

For the broader release process, link this incident to our WordPress PHP upgrade staging checklist and pre-upgrade compatibility inventory. Those articles address change management; this one identifies one specific runtime value-contract violation.

What can a static PHP compatibility scan tell you?

ModelGain PHP Upgrade Risk Audit is a separate, read-only preflight for a WordPress installation that can still run the plugin. The current WordPress.org release of ModelGain PHP Upgrade Risk Audit requires WordPress 6.9 or later and PHP 7.4 or later. It can scan readable installed plugin/theme source against a selected PHP 8 target, report known compatibility patterns by component/file/line, and help prioritize staging tests.

It does not change PHP, repair plugin code or inspect every runtime data value. A source statement such as count( $value ) can be completely correct for an array and fail only when a particular request supplies false or null. A green/static Ready result is therefore not evidence that the specific Countable TypeError will never occur. If your site has already failed, use the actual stack trace and Recovery Mode/error log first; use a compatibility scan later for broader preventive review rather than presenting it as a direct fix.

Which case matches your WordPress exception?

This on-page diagnostic selector helps route your next observation. It does not inspect server logs or modify your WordPress installation.

Find the next check for a PHP 8 count() TypeError

Applies when: The site reports count(): Argument #1 must be Countable|array, with an unexpected null, false, string or ordinary object.

Quick answer

Identify the exact failing file and operation, then trace why the passed value is not an array or Countable object. Static scanner findings may support preflight but cannot determine the runtime input.

What to do

  1. Record PHP runtime version, full stack and which WordPress action failed. Keep logs private and avoid changing multiple components at once.

  2. Inspect the value producer (setting, query, API, callback) and distinguish legitimate empty state from failed retrieval.

  3. Update the owning extension or fix your custom code contract. Test valid, empty, failed and legacy data, then confirm the original business workflow.

What did PHP say was passed into count()?

All paths are listed below. Select a symptom to focus on the most relevant path.

Distinguish missing data from failed retrieval

Trace the original function return. If no items is a legitimate documented state, an empty list may be correct. If false means the operation failed, expose and resolve that failure instead of silently returning 0.

Find the expected schema and component owner

Locate where the value was decoded, retrieved or transformed. Verify the source contract and choose an explicit normalization or validation only when the business meaning is known.

Preserve the full stack before editing

Check Recovery Mode and the host PHP log. Identify the wp-content plugin/theme/mu-plugin and exact failing operation. Do not change WordPress Core or disable every plugin as a first step.

Frequently asked questions

Why did count() work on PHP 7.4 but stop on PHP 8?

PHP 7.2–7.4 warned about invalid countable inputs, whereas PHP 8.0+ throws a TypeError. The variable’s invalid type should still be investigated; the exception exposes a previously tolerated code/data mismatch.

Is null given always just an empty array?

No. Null can mean no data, but it can also signal missing configuration, incomplete initialization or an earlier failed operation. Establish the producer’s contract before deciding whether replacing null with an empty array is correct.

Is is_iterable() enough to decide whether I may use count()?

No. An iterable object need not implement Countable. The relevant test for count() is is_countable() (PHP 7.3+) or the underlying documented type.

Should I disable every plugin to find the cause?

No. Start with the exact trace, responsible operation and the component owning the failing call. An indiscriminate shutdown can interfere with payments, caching, security, translations and scheduled tasks, and it can destroy the ability to reproduce the original failure.

Will PHP Upgrade Risk Audit guarantee this specific problem is caught before upgrade?

No. It performs static source checks. A data-dependent failure may not be inferable from source alone, and only real staging execution with representative data can verify this particular path.

Can the error occur without taking down the entire website?

Yes. It may occur only in a specific admin AJAX call, API request, review renderer, batch action or other path. Verify the original symptom and its business outcome—not only that the public homepage still loads.

Primary references and related guides

Bottom line: PHP 8 did not forbid counting arrays. It made incorrect arguments to count() a fatal, visible contract failure. Identify the call and its data source, repair the owning code or vendor dependency, and verify the original WordPress workflow with both normal and failure inputs. Do not treat a quiet homepage or a static scan as proof the issue is resolved.

This article is maintained as a practical reference. Check the linked official documentation for version-specific behavior and validate changes in a safe test environment.
More WordPress guides ↗