WP_Error::__construct( string|int $code = '', string $message = '', mixed $data = '' )
- Since
- 2.1.0
- Source
wp-includes/class-wp-error.php:61
Populates a new WP_Error object with an initial error code, message, and optional data by internally calling add(). Passing an empty string (or any falsey value) as the code makes the constructor return immediately, so the message and data arguments are silently ignored and the resulting object holds no errors. Use add() afterward on the same instance to attach further codes and messages.
Description
If $code is empty, the other parameters will be ignored.
When $code is not empty, $message will be used even if it is empty. The $data parameter will be used only if it is not empty.
Though the class is constructed with a single error code and message, multiple codes can be added using the add() method.
Compatibility
- WordPress
- since 2.1.0
- PHP
- 7.4–8.6-dev
- 6.7.7
- 6.8.8
- 6.9.7
- 7.0.4
- 7.1.0
Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.
Parameters
$codestring|intoptional- Error code.Default:
'' $messagestringoptional- Error message.Default:
'' $datamixedoptional- Error data. Default empty string.Default:
''
Code examples
Every example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.
Build a WP_Error when a post meta value fails validation
Check the numeric price meta on post 2 and construct a WP_Error describing the outcome.
$post_id = 2;
$price = get_post_meta( $post_id, 'price', true );
if ( ! is_numeric( $price ) ) {
$error = new WP_Error(
'invalid_price',
sprintf( 'The price meta value "%s" for post %d is not numeric.', $price, $post_id )
);
} else {
$error = new WP_Error(
'valid_price',
sprintf( 'Post %d has a numeric price of %s.', $post_id, $price )
);
}
echo esc_html( $error->get_error_code() . ': ' . $error->get_error_message() );The branch that runs depends on whatever value the price meta key holds in your sandbox.
See what happens when the error code is empty
Compare an instance constructed with an empty code against one constructed with a real code.
$empty_error = new WP_Error();
$populated_error = new WP_Error( 'missing_price', 'No price meta was found for this post.' );
echo 'Codes on empty-code instance: [' . esc_html( implode( ', ', $empty_error->get_error_codes() ) ) . ']<br>';
echo 'Codes on populated instance: [' . esc_html( implode( ', ', $populated_error->get_error_codes() ) ) . ']<br>';
echo 'Populated message: ' . esc_html( $populated_error->get_error_message() );new WP_Error() with no arguments produces an object with zero error codes, not an error with an empty code.
Common problems and fixes · 4
- Why does my WP_Error object show no errors at all?
- How do I add a second error code to the same WP_Error instance?
- Why is get_error_message() returning an empty string?
- Why doesn't get_error_data() return the value I passed in $data?
Why does my WP_Error object show no errors at all?
How do I add a second error code to the same WP_Error instance?
Why is get_error_message() returning an empty string?
Why doesn't get_error_data() return the value I passed in $data?
Alternatives and related functions
WP_Error::add- When you already have a WP_Error instance and need to attach an additional code and message to it.
WP_Error::add_data- When you need to attach or update data for an error code without constructing a whole new WP_Error object.
is_wp_error- When you need to check whether a value returned from a function is a WP_Error before reading its message or code.
WP_Error::get_error_message- When you already have a WP_Error object and just need to read the message for its first or a specific code.
Performance profile
How much work a call to WP_Error::__construct() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.
- Cost class
- Trivial
- Scaling
- Constant
- Instructions
- 6–11
- Plugin surface
- None
- Called by
- 50
Touches nothing outside its own arguments.
No loop in the body: the same number of instructions runs whatever you pass in.
Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 12.
Nothing here hands control to plugin code.
50 places in core call this, so the cost is paid more often than your own code shows.
What one call costs · 2 distinct outcomes
One number would be a lie: the work depends on which branch runs. These are every distinct cost WP_Error::__construct() can have, taken from its control-flow graph on PHP 8.5.
| When | Instructions | Calls it makes |
|---|---|---|
empty($code) | 6 | none |
!empty($code) | 11 | ->add() |
Across PHP versions
Compiles the same on PHP 7.4, 8.1, 8.2, 8.3, 8.4, 8.5 and 8.6-dev: 12 instructions, 6–11 executed per call, 1 branch. The work does not change between versions.
An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.
Uses · 1
- WP_Error::add()Adds an error or appends an additional message to an existing error.
Used by · 50
- Core_Upgrader::upgrade()Upgrades WordPress core.
- Language_Pack_Upgrader::bulk_upgrade()Upgrades several language packs at once.
- Language_Pack_Upgrader::check_package()Checks that the package source contains .mo and .po files.
- Language_Pack_Upgrader::clear_destination()Clears existing translations where this item is going to be installed into.
- Plugin_Upgrader::bulk_upgrade()Upgrades several plugins at once.
- Plugin_Upgrader::check_package()Checks that the source package contains a valid plugin.
- Plugin_Upgrader::deactivate_plugin_before_upgrade()Deactivates a plugin before it is upgraded.
- Plugin_Upgrader::delete_old_plugin()Deletes the old plugin during an upgrade.
- Theme_Upgrader::bulk_upgrade()Upgrades several themes at once.
- Theme_Upgrader::check_package()Checks that the package source contains a valid theme.
- WP_AI_Client_Prompt_Builder::__call()Magic method to proxy snake_case method calls to their PHP AI Client camelCase counterparts.
- WP_AI_Client_Prompt_Builder::exception_to_wp_error()Converts an exception into a WP_Error with a structured error code and message.
Show all 50
- WP_Ability::check_permissions()Checks whether the ability has the necessary permissions.
- WP_Ability::do_execute()Executes the ability callback.
- WP_Ability::execute()Executes the ability after input validation and running a permission check.
- WP_Ability::invoke_callback()Invokes a callable, ensuring the input is passed through only if the input schema is defined.
- WP_Ability::validate_input()Validates input data against the input schema.
- WP_Ability::validate_output()Validates output data against the output schema.
- WP_Ajax_Upgrader_Skin::__construct()Constructor.
- WP_Application_Passwords::create_new_application_password()Creates a new application password.
- WP_Application_Passwords::delete_all_application_passwords()Deletes all application passwords for the given user.
- WP_Application_Passwords::delete_application_password()Deletes an application password.
- WP_Application_Passwords::record_application_password_usage()Records that an application password has been used.
- WP_Application_Passwords::update_application_password()Updates an application password.
- WP_Automatic_Updater::update()Updates an item, if appropriate.
- WP_Block_Templates_Registry::register()Registers a template.
- WP_Block_Templates_Registry::unregister()Unregisters a template.
- WP_Classic_To_Block_Menu_Converter::convert()Converts a Classic Menu to blocks.
- WP_Community_Events::get_events()Gets data about events near a particular location.
- WP_Customize_Custom_CSS_Setting::validate()Validate a received value for being valid CSS.
- WP_Customize_Manager::_sanitize_background_setting()Callback for validating a background setting value.
- WP_Customize_Manager::get_changeset_post_data()Gets the data stored in a changeset post.
- WP_Customize_Manager::save()Handles customize_save WP Ajax request to save/update a changeset.
- WP_Customize_Manager::save_changeset_post()Saves the post for the loaded changeset.
- WP_Customize_Manager::validate_setting_values()Validates setting values.
- WP_Customize_Nav_Menu_Item_Setting::sanitize()Sanitize an input.
- WP_Customize_Nav_Menu_Item_Setting::update()Creates/updates the nav_menu_item post for this setting.
- WP_Customize_Nav_Menus::insert_auto_draft_post()Adds a new `auto-draft` post.
- WP_Customize_Nav_Menus::load_available_items_query()Performs the post_type and taxonomy queries for loading available menu items.
- WP_Customize_Setting::validate()Validates an input.
- WP_Customize_Widgets::call_widget_update()Finds and invokes the widget update and control callbacks.
- WP_Customize_Widgets::parse_widget_setting_id()Converts a widget setting ID (option path) to its id_base and number components.
- WP_Fatal_Error_Handler::display_default_error_template()Displays the default PHP error template.
- WP_Filesystem_Direct::__construct()Constructor.
- WP_Filesystem_FTPext::__construct()Constructor.
- WP_Filesystem_SSH2::__construct()Constructor.
- WP_Filesystem_ftpsockets::__construct()Constructor.
- WP_Font_Collection::load_from_file()Loads the font collection data from a JSON file path.
- WP_Font_Collection::load_from_json()Loads font collection data from a JSON file or URL.
- WP_Font_Collection::load_from_url()Loads the font collection data from a JSON file URL.
Source code
public function __construct( $code = '', $message = '', $data = '' ) { if ( empty( $code ) ) { return; } $this->add( $code, $message, $data ); }Changelog
Introduced in 2.1.0. Unchanged from 6.7.7 through 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
About this page
- Parsed data
- Generated from the wordpress-develop 7.0.4 tag, from
src/wp-includes/class-wp-error.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it. - Corrections
- Something wrong on this page? Report it and it gets fixed in the next regeneration.