code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
wordpress WP_REST_Sidebars_Controller::prepare_item_for_response( array $item, WP_REST_Request $request ): WP_REST_Response WP\_REST\_Sidebars\_Controller::prepare\_item\_for\_response( array $item, WP\_REST\_Request $request ): WP\_REST\_Response
===========================================================================================================================
Prepares a single sidebar output for response.
`$item` array Required Sidebar instance. `$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response) Prepared response object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
public function prepare_item_for_response( $item, $request ) {
global $wp_registered_sidebars, $wp_registered_widgets;
// Restores the more descriptive, specific name for use within this method.
$raw_sidebar = $item;
$id = $raw_sidebar['id'];
$sidebar = array( 'id' => $id );
if ( isset( $wp_registered_sidebars[ $id ] ) ) {
$registered_sidebar = $wp_registered_sidebars[ $id ];
$sidebar['status'] = 'active';
$sidebar['name'] = isset( $registered_sidebar['name'] ) ? $registered_sidebar['name'] : '';
$sidebar['description'] = isset( $registered_sidebar['description'] ) ? wp_sidebar_description( $id ) : '';
$sidebar['class'] = isset( $registered_sidebar['class'] ) ? $registered_sidebar['class'] : '';
$sidebar['before_widget'] = isset( $registered_sidebar['before_widget'] ) ? $registered_sidebar['before_widget'] : '';
$sidebar['after_widget'] = isset( $registered_sidebar['after_widget'] ) ? $registered_sidebar['after_widget'] : '';
$sidebar['before_title'] = isset( $registered_sidebar['before_title'] ) ? $registered_sidebar['before_title'] : '';
$sidebar['after_title'] = isset( $registered_sidebar['after_title'] ) ? $registered_sidebar['after_title'] : '';
} else {
$sidebar['status'] = 'inactive';
$sidebar['name'] = $raw_sidebar['name'];
$sidebar['description'] = '';
$sidebar['class'] = '';
}
$fields = $this->get_fields_for_response( $request );
if ( rest_is_field_included( 'widgets', $fields ) ) {
$sidebars = wp_get_sidebars_widgets();
$widgets = array_filter(
isset( $sidebars[ $sidebar['id'] ] ) ? $sidebars[ $sidebar['id'] ] : array(),
static function ( $widget_id ) use ( $wp_registered_widgets ) {
return isset( $wp_registered_widgets[ $widget_id ] );
}
);
$sidebar['widgets'] = array_values( $widgets );
}
$schema = $this->get_item_schema();
$data = array();
foreach ( $schema['properties'] as $property_id => $property ) {
if ( isset( $sidebar[ $property_id ] ) && true === rest_validate_value_from_schema( $sidebar[ $property_id ], $property ) ) {
$data[ $property_id ] = $sidebar[ $property_id ];
} elseif ( isset( $property['default'] ) ) {
$data[ $property_id ] = $property['default'];
}
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
$response = rest_ensure_response( $data );
if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
$response->add_links( $this->prepare_links( $sidebar ) );
}
/**
* Filters the REST API response for a sidebar.
*
* @since 5.8.0
*
* @param WP_REST_Response $response The response object.
* @param array $raw_sidebar The raw sidebar data.
* @param WP_REST_Request $request The request object.
*/
return apply_filters( 'rest_prepare_sidebar', $response, $raw_sidebar, $request );
}
```
[apply\_filters( 'rest\_prepare\_sidebar', WP\_REST\_Response $response, array $raw\_sidebar, WP\_REST\_Request $request )](../../hooks/rest_prepare_sidebar)
Filters the REST API response for a sidebar.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Sidebars\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves the block type’ schema, conforming to JSON Schema. |
| [WP\_REST\_Sidebars\_Controller::prepare\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Prepares links for the sidebar. |
| [rest\_is\_field\_included()](../../functions/rest_is_field_included) wp-includes/rest-api.php | Given an array of fields to include in a response, some of which may be `nested.fields`, determine whether the provided field should be included in the response body. |
| [rest\_validate\_value\_from\_schema()](../../functions/rest_validate_value_from_schema) wp-includes/rest-api.php | Validate a value based on a schema. |
| [wp\_get\_sidebars\_widgets()](../../functions/wp_get_sidebars_widgets) wp-includes/widgets.php | Retrieve full list of sidebars and their widget instance IDs. |
| [wp\_sidebar\_description()](../../functions/wp_sidebar_description) wp-includes/widgets.php | Retrieve description for a sidebar. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Sidebars\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves the list of sidebars (active or inactive). |
| [WP\_REST\_Sidebars\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves one sidebar from the collection. |
| [WP\_REST\_Sidebars\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Updates a sidebar. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$raw_sidebar` to `$item` to match parent class for PHP 8 named parameter support. |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Sidebars_Controller::prepare_links( array $sidebar ): array WP\_REST\_Sidebars\_Controller::prepare\_links( array $sidebar ): array
=======================================================================
Prepares links for the sidebar.
`$sidebar` array Required Sidebar. array Links for the given widget.
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
protected function prepare_links( $sidebar ) {
return array(
'collection' => array(
'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
),
'self' => array(
'href' => rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $sidebar['id'] ) ),
),
'https://api.w.org/widget' => array(
'href' => add_query_arg( 'sidebar', $sidebar['id'], rest_url( '/wp/v2/widgets' ) ),
'embeddable' => true,
),
);
}
```
| Uses | Description |
| --- | --- |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Sidebars\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Prepares a single sidebar output for response. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Sidebars_Controller::get_items( WP_REST_Request $request ): WP_REST_Response WP\_REST\_Sidebars\_Controller::get\_items( WP\_REST\_Request $request ): WP\_REST\_Response
============================================================================================
Retrieves the list of sidebars (active or inactive).
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response) Response object on success.
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
public function get_items( $request ) {
$this->retrieve_widgets();
$data = array();
$permissions_check = $this->do_permissions_check();
foreach ( wp_get_sidebars_widgets() as $id => $widgets ) {
$sidebar = $this->get_sidebar( $id );
if ( ! $sidebar ) {
continue;
}
if ( is_wp_error( $permissions_check ) && ! $this->check_read_permission( $sidebar ) ) {
continue;
}
$data[] = $this->prepare_response_for_collection(
$this->prepare_item_for_response( $sidebar, $request )
);
}
return rest_ensure_response( $data );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Sidebars\_Controller::retrieve\_widgets()](retrieve_widgets) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Looks for “lost” widgets once per request. |
| [WP\_REST\_Sidebars\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if a sidebar can be read publicly. |
| [WP\_REST\_Sidebars\_Controller::do\_permissions\_check()](do_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if the user has permissions to make the request. |
| [WP\_REST\_Sidebars\_Controller::get\_sidebar()](get_sidebar) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves the registered sidebar with the given id. |
| [WP\_REST\_Sidebars\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Prepares a single sidebar output for response. |
| [wp\_get\_sidebars\_widgets()](../../functions/wp_get_sidebars_widgets) wp-includes/widgets.php | Retrieve full list of sidebars and their widget instance IDs. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Sidebars_Controller::get_sidebar( string|int $id ): array|null WP\_REST\_Sidebars\_Controller::get\_sidebar( string|int $id ): array|null
==========================================================================
Retrieves the registered sidebar with the given id.
`$id` string|int Required ID of the sidebar. array|null The discovered sidebar, or null if it is not registered.
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
protected function get_sidebar( $id ) {
return wp_get_sidebar( $id );
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_sidebar()](../../functions/wp_get_sidebar) wp-includes/widgets.php | Retrieves the registered sidebar with the given ID. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Sidebars\_Controller::get\_items\_permissions\_check()](get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if a given request has access to get sidebars. |
| [WP\_REST\_Sidebars\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves the list of sidebars (active or inactive). |
| [WP\_REST\_Sidebars\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if a given request has access to get a single sidebar. |
| [WP\_REST\_Sidebars\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves one sidebar from the collection. |
| [WP\_REST\_Sidebars\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Updates a sidebar. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Sidebars_Controller::update_item( WP_REST_Request $request ): WP_REST_Response WP\_REST\_Sidebars\_Controller::update\_item( WP\_REST\_Request $request ): WP\_REST\_Response
==============================================================================================
Updates a sidebar.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
public function update_item( $request ) {
if ( isset( $request['widgets'] ) ) {
$sidebars = wp_get_sidebars_widgets();
foreach ( $sidebars as $sidebar_id => $widgets ) {
foreach ( $widgets as $i => $widget_id ) {
// This automatically removes the passed widget IDs from any other sidebars in use.
if ( $sidebar_id !== $request['id'] && in_array( $widget_id, $request['widgets'], true ) ) {
unset( $sidebars[ $sidebar_id ][ $i ] );
}
// This automatically removes omitted widget IDs to the inactive sidebar.
if ( $sidebar_id === $request['id'] && ! in_array( $widget_id, $request['widgets'], true ) ) {
$sidebars['wp_inactive_widgets'][] = $widget_id;
}
}
}
$sidebars[ $request['id'] ] = $request['widgets'];
wp_set_sidebars_widgets( $sidebars );
}
$request['context'] = 'edit';
$sidebar = $this->get_sidebar( $request['id'] );
/**
* Fires after a sidebar is updated via the REST API.
*
* @since 5.8.0
*
* @param array $sidebar The updated sidebar.
* @param WP_REST_Request $request Request object.
*/
do_action( 'rest_save_sidebar', $sidebar, $request );
return $this->prepare_item_for_response( $sidebar, $request );
}
```
[do\_action( 'rest\_save\_sidebar', array $sidebar, WP\_REST\_Request $request )](../../hooks/rest_save_sidebar)
Fires after a sidebar is updated via the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Sidebars\_Controller::get\_sidebar()](get_sidebar) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves the registered sidebar with the given id. |
| [WP\_REST\_Sidebars\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Prepares a single sidebar output for response. |
| [wp\_get\_sidebars\_widgets()](../../functions/wp_get_sidebars_widgets) wp-includes/widgets.php | Retrieve full list of sidebars and their widget instance IDs. |
| [wp\_set\_sidebars\_widgets()](../../functions/wp_set_sidebars_widgets) wp-includes/widgets.php | Set the sidebar widget option to update sidebars. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Sidebars_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Sidebars\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
============================================================================================================
Checks if a given request has access to get sidebars.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
public function get_items_permissions_check( $request ) {
$this->retrieve_widgets();
foreach ( wp_get_sidebars_widgets() as $id => $widgets ) {
$sidebar = $this->get_sidebar( $id );
if ( ! $sidebar ) {
continue;
}
if ( $this->check_read_permission( $sidebar ) ) {
return true;
}
}
return $this->do_permissions_check();
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Sidebars\_Controller::retrieve\_widgets()](retrieve_widgets) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Looks for “lost” widgets once per request. |
| [WP\_REST\_Sidebars\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if a sidebar can be read publicly. |
| [WP\_REST\_Sidebars\_Controller::get\_sidebar()](get_sidebar) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves the registered sidebar with the given id. |
| [WP\_REST\_Sidebars\_Controller::do\_permissions\_check()](do_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if the user has permissions to make the request. |
| [wp\_get\_sidebars\_widgets()](../../functions/wp_get_sidebars_widgets) wp-includes/widgets.php | Retrieve full list of sidebars and their widget instance IDs. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Sidebars_Controller::update_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Sidebars\_Controller::update\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
==============================================================================================================
Checks if a given request has access to update sidebars.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
public function update_item_permissions_check( $request ) {
return $this->do_permissions_check();
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Sidebars\_Controller::do\_permissions\_check()](do_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if the user has permissions to make the request. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Sidebars_Controller::register_routes() WP\_REST\_Sidebars\_Controller::register\_routes()
==================================================
Registers the controllers routes.
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base,
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => array(
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/(?P<id>[\w-]+)',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this, 'get_item_permissions_check' ),
'args' => array(
'id' => array(
'description' => __( 'The id of a registered sidebar' ),
'type' => 'string',
),
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'update_item' ),
'permission_callback' => array( $this, 'update_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [register\_rest\_route()](../../functions/register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Sidebars_Controller::check_read_permission( array $sidebar ): bool WP\_REST\_Sidebars\_Controller::check\_read\_permission( array $sidebar ): bool
===============================================================================
Checks if a sidebar can be read publicly.
`$sidebar` array Required The registered sidebar configuration. bool Whether the side can be read.
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
protected function check_read_permission( $sidebar ) {
return ! empty( $sidebar['show_in_rest'] );
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Sidebars\_Controller::get\_items\_permissions\_check()](get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if a given request has access to get sidebars. |
| [WP\_REST\_Sidebars\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves the list of sidebars (active or inactive). |
| [WP\_REST\_Sidebars\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if a given request has access to get a single sidebar. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Sidebars_Controller::__construct() WP\_REST\_Sidebars\_Controller::\_\_construct()
===============================================
Sidebars controller constructor.
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'sidebars';
}
```
| Used By | Description |
| --- | --- |
| [create\_initial\_rest\_routes()](../../functions/create_initial_rest_routes) wp-includes/rest-api.php | Registers default REST API routes. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Sidebars_Controller::get_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Sidebars\_Controller::get\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
===========================================================================================================
Checks if a given request has access to get a single sidebar.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
public function get_item_permissions_check( $request ) {
$this->retrieve_widgets();
$sidebar = $this->get_sidebar( $request['id'] );
if ( $sidebar && $this->check_read_permission( $sidebar ) ) {
return true;
}
return $this->do_permissions_check();
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Sidebars\_Controller::retrieve\_widgets()](retrieve_widgets) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Looks for “lost” widgets once per request. |
| [WP\_REST\_Sidebars\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if a sidebar can be read publicly. |
| [WP\_REST\_Sidebars\_Controller::get\_sidebar()](get_sidebar) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves the registered sidebar with the given id. |
| [WP\_REST\_Sidebars\_Controller::do\_permissions\_check()](do_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if the user has permissions to make the request. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Sidebars_Controller::get_item_schema(): array WP\_REST\_Sidebars\_Controller::get\_item\_schema(): array
==========================================================
Retrieves the block type’ schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
public function get_item_schema() {
if ( $this->schema ) {
return $this->add_additional_fields_schema( $this->schema );
}
$schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'sidebar',
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'ID of sidebar.' ),
'type' => 'string',
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
'name' => array(
'description' => __( 'Unique name identifying the sidebar.' ),
'type' => 'string',
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
'description' => array(
'description' => __( 'Description of sidebar.' ),
'type' => 'string',
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
'class' => array(
'description' => __( 'Extra CSS class to assign to the sidebar in the Widgets interface.' ),
'type' => 'string',
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
'before_widget' => array(
'description' => __( 'HTML content to prepend to each widget\'s HTML output when assigned to this sidebar. Default is an opening list item element.' ),
'type' => 'string',
'default' => '',
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
'after_widget' => array(
'description' => __( 'HTML content to append to each widget\'s HTML output when assigned to this sidebar. Default is a closing list item element.' ),
'type' => 'string',
'default' => '',
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
'before_title' => array(
'description' => __( 'HTML content to prepend to the sidebar title when displayed. Default is an opening h2 element.' ),
'type' => 'string',
'default' => '',
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
'after_title' => array(
'description' => __( 'HTML content to append to the sidebar title when displayed. Default is a closing h2 element.' ),
'type' => 'string',
'default' => '',
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
'status' => array(
'description' => __( 'Status of sidebar.' ),
'type' => 'string',
'enum' => array( 'active', 'inactive' ),
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
'widgets' => array(
'description' => __( 'Nested widgets.' ),
'type' => 'array',
'items' => array(
'type' => array( 'object', 'string' ),
),
'default' => array(),
'context' => array( 'embed', 'view', 'edit' ),
),
),
);
$this->schema = $schema;
return $this->add_additional_fields_schema( $this->schema );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Sidebars\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Prepares a single sidebar output for response. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Sidebars_Controller::retrieve_widgets() WP\_REST\_Sidebars\_Controller::retrieve\_widgets()
===================================================
Looks for “lost” widgets once per request.
* [retrieve\_widgets()](../../functions/retrieve_widgets)
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
protected function retrieve_widgets() {
if ( ! $this->widgets_retrieved ) {
retrieve_widgets();
$this->widgets_retrieved = true;
}
}
```
| Uses | Description |
| --- | --- |
| [retrieve\_widgets()](../../functions/retrieve_widgets) wp-includes/widgets.php | Validates and remaps any “orphaned” widgets to wp\_inactive\_widgets sidebar, and saves the widget settings. This has to run at least on each theme change. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Sidebars\_Controller::get\_items\_permissions\_check()](get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if a given request has access to get sidebars. |
| [WP\_REST\_Sidebars\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves the list of sidebars (active or inactive). |
| [WP\_REST\_Sidebars\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if a given request has access to get a single sidebar. |
| [WP\_REST\_Sidebars\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves one sidebar from the collection. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Sidebars_Controller::do_permissions_check(): true|WP_Error WP\_REST\_Sidebars\_Controller::do\_permissions\_check(): true|WP\_Error
========================================================================
Checks if the user has permissions to make the request.
true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php/)
```
protected function do_permissions_check() {
// Verify if the current user has edit_theme_options capability.
// This capability is required to access the widgets screen.
if ( ! current_user_can( 'edit_theme_options' ) ) {
return new WP_Error(
'rest_cannot_manage_widgets',
__( 'Sorry, you are not allowed to manage widgets on this site.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Sidebars\_Controller::get\_items\_permissions\_check()](get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if a given request has access to get sidebars. |
| [WP\_REST\_Sidebars\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves the list of sidebars (active or inactive). |
| [WP\_REST\_Sidebars\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if a given request has access to get a single sidebar. |
| [WP\_REST\_Sidebars\_Controller::update\_item\_permissions\_check()](update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if a given request has access to update sidebars. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_SimplePie_Sanitize_KSES::sanitize( mixed $data, int $type, string $base = '' ): mixed WP\_SimplePie\_Sanitize\_KSES::sanitize( mixed $data, int $type, string $base = '' ): mixed
===========================================================================================
WordPress SimplePie sanitization using KSES.
Sanitizes the incoming data, to ensure that it matches the type of data expected, using KSES.
`$data` mixed Required The data that needs to be sanitized. `$type` int Required The type of data that it's supposed to be. `$base` string Optional The `xml:base` value to use when converting relative URLs to absolute ones. Default: `''`
mixed Sanitized data.
File: `wp-includes/class-wp-simplepie-sanitize-kses.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-simplepie-sanitize-kses.php/)
```
public function sanitize( $data, $type, $base = '' ) {
$data = trim( $data );
if ( $type & SIMPLEPIE_CONSTRUCT_MAYBE_HTML ) {
if ( preg_match( '/(&(#(x[0-9a-fA-F]+|[0-9]+)|[a-zA-Z0-9]+)|<\/[A-Za-z][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E]*' . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . '>)/', $data ) ) {
$type |= SIMPLEPIE_CONSTRUCT_HTML;
} else {
$type |= SIMPLEPIE_CONSTRUCT_TEXT;
}
}
if ( $type & SIMPLEPIE_CONSTRUCT_BASE64 ) {
$data = base64_decode( $data );
}
if ( $type & ( SIMPLEPIE_CONSTRUCT_HTML | SIMPLEPIE_CONSTRUCT_XHTML ) ) {
$data = wp_kses_post( $data );
if ( 'UTF-8' !== $this->output_encoding ) {
$data = $this->registry->call( 'Misc', 'change_encoding', array( $data, 'UTF-8', $this->output_encoding ) );
}
return $data;
} else {
return parent::sanitize( $data, $type, $base );
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_kses\_post()](../../functions/wp_kses_post) wp-includes/kses.php | Sanitizes content for allowed HTML tags for post content. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Auto_Add_Control::content_template() WP\_Customize\_Nav\_Menu\_Auto\_Add\_Control::content\_template()
=================================================================
Render the Underscore template for this control.
File: `wp-includes/customize/class-wp-customize-nav-menu-auto-add-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-auto-add-control.php/)
```
protected function content_template() {
?>
<# var elementId = _.uniqueId( 'customize-nav-menu-auto-add-control-' ); #>
<span class="customize-control-title"><?php _e( 'Menu Options' ); ?></span>
<span class="customize-inside-control-row">
<input id="{{ elementId }}" type="checkbox" class="auto_add" />
<label for="{{ elementId }}">
<?php _e( 'Automatically add new top-level pages to this menu' ); ?>
</label>
</span>
<?php
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Auto_Add_Control::render_content() WP\_Customize\_Nav\_Menu\_Auto\_Add\_Control::render\_content()
===============================================================
No-op since we’re using JS template.
File: `wp-includes/customize/class-wp-customize-nav-menu-auto-add-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-auto-add-control.php/)
```
protected function render_content() {}
```
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_HTTP_IXR_Client::query( $args ): bool WP\_HTTP\_IXR\_Client::query( $args ): bool
===========================================
bool
File: `wp-includes/class-wp-http-ixr-client.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-ixr-client.php/)
```
public function query( ...$args ) {
$method = array_shift( $args );
$request = new IXR_Request( $method, $args );
$xml = $request->getXml();
$port = $this->port ? ":$this->port" : '';
$url = $this->scheme . '://' . $this->server . $port . $this->path;
$args = array(
'headers' => array( 'Content-Type' => 'text/xml' ),
'user-agent' => $this->useragent,
'body' => $xml,
);
// Merge Custom headers ala #8145.
foreach ( $this->headers as $header => $value ) {
$args['headers'][ $header ] = $value;
}
/**
* Filters the headers collection to be sent to the XML-RPC server.
*
* @since 4.4.0
*
* @param string[] $headers Associative array of headers to be sent.
*/
$args['headers'] = apply_filters( 'wp_http_ixr_client_headers', $args['headers'] );
if ( false !== $this->timeout ) {
$args['timeout'] = $this->timeout;
}
// Now send the request.
if ( $this->debug ) {
echo '<pre class="ixr_request">' . htmlspecialchars( $xml ) . "\n</pre>\n\n";
}
$response = wp_remote_post( $url, $args );
if ( is_wp_error( $response ) ) {
$errno = $response->get_error_code();
$errorstr = $response->get_error_message();
$this->error = new IXR_Error( -32300, "transport error: $errno $errorstr" );
return false;
}
if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
$this->error = new IXR_Error( -32301, 'transport error - HTTP status code was not 200 (' . wp_remote_retrieve_response_code( $response ) . ')' );
return false;
}
if ( $this->debug ) {
echo '<pre class="ixr_response">' . htmlspecialchars( wp_remote_retrieve_body( $response ) ) . "\n</pre>\n\n";
}
// Now parse what we've got back.
$this->message = new IXR_Message( wp_remote_retrieve_body( $response ) );
if ( ! $this->message->parse() ) {
// XML error.
$this->error = new IXR_Error( -32700, 'parse error. not well formed' );
return false;
}
// Is the message a fault?
if ( 'fault' === $this->message->messageType ) {
$this->error = new IXR_Error( $this->message->faultCode, $this->message->faultString );
return false;
}
// Message must be OK.
return true;
}
```
[apply\_filters( 'wp\_http\_ixr\_client\_headers', string[] $headers )](../../hooks/wp_http_ixr_client_headers)
Filters the headers collection to be sent to the XML-RPC server.
| Uses | Description |
| --- | --- |
| [IXR\_Request::\_\_construct()](../ixr_request/__construct) wp-includes/IXR/class-IXR-request.php | PHP5 constructor. |
| [IXR\_Message::\_\_construct()](../ixr_message/__construct) wp-includes/IXR/class-IXR-message.php | PHP5 constructor. |
| [wp\_remote\_post()](../../functions/wp_remote_post) wp-includes/http.php | Performs an HTTP request using the POST method and returns its response. |
| [wp\_remote\_retrieve\_response\_code()](../../functions/wp_remote_retrieve_response_code) wp-includes/http.php | Retrieve only the response code from the raw response. |
| [wp\_remote\_retrieve\_body()](../../functions/wp_remote_retrieve_body) wp-includes/http.php | Retrieve only the body from the raw response. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Formalized the existing `...$args` parameter by adding it to the function signature. |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
| programming_docs |
wordpress WP_HTTP_IXR_Client::__construct( string $server, string|false $path = false, int|false $port = false, int $timeout = 15 ) WP\_HTTP\_IXR\_Client::\_\_construct( string $server, string|false $path = false, int|false $port = false, int $timeout = 15 )
==============================================================================================================================
`$server` string Required `$path` string|false Optional Default: `false`
`$port` int|false Optional Default: `false`
`$timeout` int Optional Default: `15`
File: `wp-includes/class-wp-http-ixr-client.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-ixr-client.php/)
```
public function __construct( $server, $path = false, $port = false, $timeout = 15 ) {
if ( ! $path ) {
// Assume we have been given a URL instead.
$bits = parse_url( $server );
$this->scheme = $bits['scheme'];
$this->server = $bits['host'];
$this->port = isset( $bits['port'] ) ? $bits['port'] : $port;
$this->path = ! empty( $bits['path'] ) ? $bits['path'] : '/';
// Make absolutely sure we have a path.
if ( ! $this->path ) {
$this->path = '/';
}
if ( ! empty( $bits['query'] ) ) {
$this->path .= '?' . $bits['query'];
}
} else {
$this->scheme = 'http';
$this->server = $server;
$this->path = $path;
$this->port = $port;
}
$this->useragent = 'The Incutio XML-RPC PHP Library';
$this->timeout = $timeout;
}
```
| Used By | Description |
| --- | --- |
| [weblog\_ping()](../../functions/weblog_ping) wp-includes/comment.php | Sends a pingback. |
| [pingback()](../../functions/pingback) wp-includes/comment.php | Pings back the links found in a post. |
wordpress WP_Customize_Section::get_content(): string WP\_Customize\_Section::get\_content(): string
==============================================
Get the section’s content for insertion into the Customizer pane.
string Contents of the section.
File: `wp-includes/class-wp-customize-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-section.php/)
```
final public function get_content() {
ob_start();
$this->maybe_render();
return trim( ob_get_clean() );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Section::maybe\_render()](maybe_render) wp-includes/class-wp-customize-section.php | Check capabilities and render the section. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Section::json()](json) wp-includes/class-wp-customize-section.php | Gather the parameters passed to client JavaScript via JSON. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Section::json(): array WP\_Customize\_Section::json(): array
=====================================
Gather the parameters passed to client JavaScript via JSON.
array The array to be exported to the client as JSON.
File: `wp-includes/class-wp-customize-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-section.php/)
```
public function json() {
$array = wp_array_slice_assoc( (array) $this, array( 'id', 'description', 'priority', 'panel', 'type', 'description_hidden' ) );
$array['title'] = html_entity_decode( $this->title, ENT_QUOTES, get_bloginfo( 'charset' ) );
$array['content'] = $this->get_content();
$array['active'] = $this->active();
$array['instanceNumber'] = $this->instance_number;
if ( $this->panel ) {
/* translators: ▸ is the unicode right-pointing triangle. %s: Section title in the Customizer. */
$array['customizeAction'] = sprintf( __( 'Customizing ▸ %s' ), esc_html( $this->manager->get_panel( $this->panel )->title ) );
} else {
$array['customizeAction'] = __( 'Customizing' );
}
return $array;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Section::get\_content()](get_content) wp-includes/class-wp-customize-section.php | Get the section’s content for insertion into the Customizer pane. |
| [WP\_Customize\_Section::active()](active) wp-includes/class-wp-customize-section.php | Check whether section is active to current Customizer preview. |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Themes\_Section::json()](../wp_customize_themes_section/json) wp-includes/customize/class-wp-customize-themes-section.php | Get section parameters for JS. |
| [WP\_Customize\_Nav\_Menu\_Section::json()](../wp_customize_nav_menu_section/json) wp-includes/customize/class-wp-customize-nav-menu-section.php | Get section parameters for JS. |
| [WP\_Customize\_Sidebar\_Section::json()](../wp_customize_sidebar_section/json) wp-includes/customize/class-wp-customize-sidebar-section.php | Gather the parameters passed to client JavaScript via JSON. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Section::active_callback(): true WP\_Customize\_Section::active\_callback(): true
================================================
Default callback used when invoking [WP\_Customize\_Section::active()](active).
Subclasses can override this with their specific logic, or they may provide an ‘active\_callback’ argument to the constructor.
true Always true.
File: `wp-includes/class-wp-customize-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-section.php/)
```
public function active_callback() {
return true;
}
```
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Section::render_template() WP\_Customize\_Section::render\_template()
==========================================
An Underscore (JS) template for rendering this section.
Class variables for this section class are available in the `data` JS object; export custom variables by overriding [WP\_Customize\_Section::json()](json).
* [WP\_Customize\_Section::print\_template()](../wp_customize_section/print_template)
File: `wp-includes/class-wp-customize-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-section.php/)
```
protected function render_template() {
?>
<li id="accordion-section-{{ data.id }}" class="accordion-section control-section control-section-{{ data.type }}">
<h3 class="accordion-section-title" tabindex="0">
{{ data.title }}
<span class="screen-reader-text"><?php _e( 'Press return or enter to open this section' ); ?></span>
</h3>
<ul class="accordion-section-content">
<li class="customize-section-description-container section-meta <# if ( data.description_hidden ) { #>customize-info<# } #>">
<div class="customize-section-title">
<button class="customize-section-back" tabindex="-1">
<span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
</button>
<h3>
<span class="customize-action">
{{{ data.customizeAction }}}
</span>
{{ data.title }}
</h3>
<# if ( data.description && data.description_hidden ) { #>
<button type="button" class="customize-help-toggle dashicons dashicons-editor-help" aria-expanded="false"><span class="screen-reader-text"><?php _e( 'Help' ); ?></span></button>
<div class="description customize-section-description">
{{{ data.description }}}
</div>
<# } #>
<div class="customize-control-notifications-container"></div>
</div>
<# if ( data.description && ! data.description_hidden ) { #>
<div class="description customize-section-description">
{{{ data.description }}}
</div>
<# } #>
</li>
</ul>
</li>
<?php
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Section::print\_template()](print_template) wp-includes/class-wp-customize-section.php | Render the section’s JS template. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Section::active(): bool WP\_Customize\_Section::active(): bool
======================================
Check whether section is active to current Customizer preview.
bool Whether the section is active to the current preview.
File: `wp-includes/class-wp-customize-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-section.php/)
```
final public function active() {
$section = $this;
$active = call_user_func( $this->active_callback, $this );
/**
* Filters response of WP_Customize_Section::active().
*
* @since 4.1.0
*
* @param bool $active Whether the Customizer section is active.
* @param WP_Customize_Section $section WP_Customize_Section instance.
*/
$active = apply_filters( 'customize_section_active', $active, $section );
return $active;
}
```
[apply\_filters( 'customize\_section\_active', bool $active, WP\_Customize\_Section $section )](../../hooks/customize_section_active)
Filters response of [WP\_Customize\_Section::active()](active).
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Section::json()](json) wp-includes/class-wp-customize-section.php | Gather the parameters passed to client JavaScript via JSON. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Section::print_template() WP\_Customize\_Section::print\_template()
=========================================
Render the section’s JS template.
This function is only run for section types that have been registered with [WP\_Customize\_Manager::register\_section\_type()](../wp_customize_manager/register_section_type).
* [WP\_Customize\_Manager::render\_template()](../wp_customize_manager/render_template)
File: `wp-includes/class-wp-customize-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-section.php/)
```
public function print_template() {
?>
<script type="text/html" id="tmpl-customize-section-<?php echo $this->type; ?>">
<?php $this->render_template(); ?>
</script>
<?php
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Section::render\_template()](render_template) wp-includes/class-wp-customize-section.php | An Underscore (JS) template for rendering this section. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Section::__construct( WP_Customize_Manager $manager, string $id, array $args = array() ) WP\_Customize\_Section::\_\_construct( WP\_Customize\_Manager $manager, string $id, array $args = array() )
===========================================================================================================
Constructor.
Any supplied $args override class property defaults.
`$manager` [WP\_Customize\_Manager](../wp_customize_manager) Required Customizer bootstrap instance. `$id` string Required A specific ID of the section. `$args` array Optional Array of properties for the new Section object.
* `priority`intPriority of the section, defining the display order of panels and sections. Default 160.
* `panel`stringThe panel this section belongs to (if any).
* `capability`stringCapability required for the section.
Default `'edit_theme_options'`
* `theme_supports`string|string[]Theme features required to support the section.
* `title`stringTitle of the section to show in UI.
* `description`stringDescription to show in the UI.
* `type`stringType of the section.
* `active_callback`callableActive callback.
* `description_hidden`boolHide the description behind a help icon, instead of inline above the first control.
Default false.
Default: `array()`
File: `wp-includes/class-wp-customize-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-section.php/)
```
public function __construct( $manager, $id, $args = array() ) {
$keys = array_keys( get_object_vars( $this ) );
foreach ( $keys as $key ) {
if ( isset( $args[ $key ] ) ) {
$this->$key = $args[ $key ];
}
}
$this->manager = $manager;
$this->id = $id;
if ( empty( $this->active_callback ) ) {
$this->active_callback = array( $this, 'active_callback' );
}
self::$instance_count += 1;
$this->instance_number = self::$instance_count;
$this->controls = array(); // Users cannot customize the $controls array.
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_New\_Menu\_Section::\_\_construct()](../wp_customize_new_menu_section/__construct) wp-includes/customize/class-wp-customize-new-menu-section.php | Constructor. |
| [WP\_Customize\_Manager::add\_section()](../wp_customize_manager/add_section) wp-includes/class-wp-customize-manager.php | Adds a customize section. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Section::render() WP\_Customize\_Section::render()
================================
Render the section UI in a subclass.
Sections are now rendered in JS by default, see [WP\_Customize\_Section::print\_template()](print_template).
File: `wp-includes/class-wp-customize-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-section.php/)
```
protected function render() {}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Section::maybe\_render()](maybe_render) wp-includes/class-wp-customize-section.php | Check capabilities and render the section. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Section::check_capabilities(): bool WP\_Customize\_Section::check\_capabilities(): bool
===================================================
Checks required user capabilities and whether the theme has the feature support required by the section.
bool False if theme doesn't support the section or user doesn't have the capability.
File: `wp-includes/class-wp-customize-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-section.php/)
```
final public function check_capabilities() {
if ( $this->capability && ! current_user_can( $this->capability ) ) {
return false;
}
if ( $this->theme_supports && ! current_theme_supports( ... (array) $this->theme_supports ) ) {
return false;
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Section::maybe\_render()](maybe_render) wp-includes/class-wp-customize-section.php | Check capabilities and render the section. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Section::maybe_render() WP\_Customize\_Section::maybe\_render()
=======================================
Check capabilities and render the section.
File: `wp-includes/class-wp-customize-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-section.php/)
```
final public function maybe_render() {
if ( ! $this->check_capabilities() ) {
return;
}
/**
* Fires before rendering a Customizer section.
*
* @since 3.4.0
*
* @param WP_Customize_Section $section WP_Customize_Section instance.
*/
do_action( 'customize_render_section', $this );
/**
* Fires before rendering a specific Customizer section.
*
* The dynamic portion of the hook name, `$this->id`, refers to the ID
* of the specific Customizer section to be rendered.
*
* @since 3.4.0
*/
do_action( "customize_render_section_{$this->id}" );
$this->render();
}
```
[do\_action( 'customize\_render\_section', WP\_Customize\_Section $section )](../../hooks/customize_render_section)
Fires before rendering a Customizer section.
[do\_action( "customize\_render\_section\_{$this->id}" )](../../hooks/customize_render_section_this-id)
Fires before rendering a specific Customizer section.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Section::check\_capabilities()](check_capabilities) wp-includes/class-wp-customize-section.php | Checks required user capabilities and whether the theme has the feature support required by the section. |
| [WP\_Customize\_Section::render()](render) wp-includes/class-wp-customize-section.php | Render the section UI in a subclass. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Section::get\_content()](get_content) wp-includes/class-wp-customize-section.php | Get the section’s content for insertion into the Customizer pane. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Paused_Extensions_Storage::get_option_name(): string WP\_Paused\_Extensions\_Storage::get\_option\_name(): string
============================================================
Get the option name for storing paused extensions.
string
File: `wp-includes/class-wp-paused-extensions-storage.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-paused-extensions-storage.php/)
```
protected function get_option_name() {
if ( ! wp_recovery_mode()->is_active() ) {
return '';
}
$session_id = wp_recovery_mode()->get_session_id();
if ( empty( $session_id ) ) {
return '';
}
return "{$session_id}_paused_extensions";
}
```
| Uses | Description |
| --- | --- |
| [WP\_Recovery\_Mode::is\_active()](../wp_recovery_mode/is_active) wp-includes/class-wp-recovery-mode.php | Checks whether recovery mode is active. |
| [WP\_Recovery\_Mode::get\_session\_id()](../wp_recovery_mode/get_session_id) wp-includes/class-wp-recovery-mode.php | Gets the recovery mode session ID. |
| [wp\_recovery\_mode()](../../functions/wp_recovery_mode) wp-includes/error-protection.php | Access the WordPress Recovery Mode instance. |
| Used By | Description |
| --- | --- |
| [WP\_Paused\_Extensions\_Storage::set()](set) wp-includes/class-wp-paused-extensions-storage.php | Records an extension error. |
| [WP\_Paused\_Extensions\_Storage::delete()](delete) wp-includes/class-wp-paused-extensions-storage.php | Forgets a previously recorded extension error. |
| [WP\_Paused\_Extensions\_Storage::get\_all()](get_all) wp-includes/class-wp-paused-extensions-storage.php | Gets the paused extensions with their errors. |
| [WP\_Paused\_Extensions\_Storage::delete\_all()](delete_all) wp-includes/class-wp-paused-extensions-storage.php | Remove all paused extensions. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Paused_Extensions_Storage::get_all(): array WP\_Paused\_Extensions\_Storage::get\_all(): array
==================================================
Gets the paused extensions with their errors.
array Associative array of errors keyed by extension slug.
* `...$0`arrayError information returned by `error_get_last()`.
File: `wp-includes/class-wp-paused-extensions-storage.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-paused-extensions-storage.php/)
```
public function get_all() {
if ( ! $this->is_api_loaded() ) {
return array();
}
$option_name = $this->get_option_name();
if ( ! $option_name ) {
return array();
}
$paused_extensions = (array) get_option( $option_name, array() );
return isset( $paused_extensions[ $this->type ] ) ? $paused_extensions[ $this->type ] : array();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Paused\_Extensions\_Storage::is\_api\_loaded()](is_api_loaded) wp-includes/class-wp-paused-extensions-storage.php | Checks whether the underlying API to store paused extensions is loaded. |
| [WP\_Paused\_Extensions\_Storage::get\_option\_name()](get_option_name) wp-includes/class-wp-paused-extensions-storage.php | Get the option name for storing paused extensions. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Paused\_Extensions\_Storage::get()](get) wp-includes/class-wp-paused-extensions-storage.php | Gets the error for an extension, if paused. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Paused_Extensions_Storage::delete_all(): bool WP\_Paused\_Extensions\_Storage::delete\_all(): bool
====================================================
Remove all paused extensions.
bool
File: `wp-includes/class-wp-paused-extensions-storage.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-paused-extensions-storage.php/)
```
public function delete_all() {
if ( ! $this->is_api_loaded() ) {
return false;
}
$option_name = $this->get_option_name();
if ( ! $option_name ) {
return false;
}
$paused_extensions = (array) get_option( $option_name, array() );
unset( $paused_extensions[ $this->type ] );
if ( ! $paused_extensions ) {
return delete_option( $option_name );
}
return update_option( $option_name, $paused_extensions );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Paused\_Extensions\_Storage::is\_api\_loaded()](is_api_loaded) wp-includes/class-wp-paused-extensions-storage.php | Checks whether the underlying API to store paused extensions is loaded. |
| [WP\_Paused\_Extensions\_Storage::get\_option\_name()](get_option_name) wp-includes/class-wp-paused-extensions-storage.php | Get the option name for storing paused extensions. |
| [delete\_option()](../../functions/delete_option) wp-includes/option.php | Removes option by name. Prevents removal of protected WordPress options. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Paused_Extensions_Storage::is_api_loaded(): bool WP\_Paused\_Extensions\_Storage::is\_api\_loaded(): bool
========================================================
Checks whether the underlying API to store paused extensions is loaded.
bool True if the API is loaded, false otherwise.
File: `wp-includes/class-wp-paused-extensions-storage.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-paused-extensions-storage.php/)
```
protected function is_api_loaded() {
return function_exists( 'get_option' );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Paused\_Extensions\_Storage::set()](set) wp-includes/class-wp-paused-extensions-storage.php | Records an extension error. |
| [WP\_Paused\_Extensions\_Storage::delete()](delete) wp-includes/class-wp-paused-extensions-storage.php | Forgets a previously recorded extension error. |
| [WP\_Paused\_Extensions\_Storage::get()](get) wp-includes/class-wp-paused-extensions-storage.php | Gets the error for an extension, if paused. |
| [WP\_Paused\_Extensions\_Storage::get\_all()](get_all) wp-includes/class-wp-paused-extensions-storage.php | Gets the paused extensions with their errors. |
| [WP\_Paused\_Extensions\_Storage::delete\_all()](delete_all) wp-includes/class-wp-paused-extensions-storage.php | Remove all paused extensions. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Paused_Extensions_Storage::__construct( string $extension_type ) WP\_Paused\_Extensions\_Storage::\_\_construct( string $extension\_type )
=========================================================================
Constructor.
`$extension_type` string Required Extension type. Either `'plugin'` or `'theme'`. File: `wp-includes/class-wp-paused-extensions-storage.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-paused-extensions-storage.php/)
```
public function __construct( $extension_type ) {
$this->type = $extension_type;
}
```
| Used By | Description |
| --- | --- |
| [wp\_paused\_plugins()](../../functions/wp_paused_plugins) wp-includes/error-protection.php | Get the instance for storing paused plugins. |
| [wp\_paused\_themes()](../../functions/wp_paused_themes) wp-includes/error-protection.php | Get the instance for storing paused extensions. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Paused_Extensions_Storage::set( string $extension, array $error ): bool WP\_Paused\_Extensions\_Storage::set( string $extension, array $error ): bool
=============================================================================
Records an extension error.
Only one error is stored per extension, with subsequent errors for the same extension overriding the previously stored error.
`$extension` string Required Plugin or theme directory name. `$error` array Required Error information returned by `error_get_last()`.
* `type`intThe error type.
* `file`stringThe name of the file in which the error occurred.
* `line`intThe line number in which the error occurred.
* `message`stringThe error message.
bool True on success, false on failure.
File: `wp-includes/class-wp-paused-extensions-storage.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-paused-extensions-storage.php/)
```
public function set( $extension, $error ) {
if ( ! $this->is_api_loaded() ) {
return false;
}
$option_name = $this->get_option_name();
if ( ! $option_name ) {
return false;
}
$paused_extensions = (array) get_option( $option_name, array() );
// Do not update if the error is already stored.
if ( isset( $paused_extensions[ $this->type ][ $extension ] ) && $paused_extensions[ $this->type ][ $extension ] === $error ) {
return true;
}
$paused_extensions[ $this->type ][ $extension ] = $error;
return update_option( $option_name, $paused_extensions );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Paused\_Extensions\_Storage::is\_api\_loaded()](is_api_loaded) wp-includes/class-wp-paused-extensions-storage.php | Checks whether the underlying API to store paused extensions is loaded. |
| [WP\_Paused\_Extensions\_Storage::get\_option\_name()](get_option_name) wp-includes/class-wp-paused-extensions-storage.php | Get the option name for storing paused extensions. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Paused_Extensions_Storage::delete( string $extension ): bool WP\_Paused\_Extensions\_Storage::delete( string $extension ): bool
==================================================================
Forgets a previously recorded extension error.
`$extension` string Required Plugin or theme directory name. bool True on success, false on failure.
File: `wp-includes/class-wp-paused-extensions-storage.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-paused-extensions-storage.php/)
```
public function delete( $extension ) {
if ( ! $this->is_api_loaded() ) {
return false;
}
$option_name = $this->get_option_name();
if ( ! $option_name ) {
return false;
}
$paused_extensions = (array) get_option( $option_name, array() );
// Do not delete if no error is stored.
if ( ! isset( $paused_extensions[ $this->type ][ $extension ] ) ) {
return true;
}
unset( $paused_extensions[ $this->type ][ $extension ] );
if ( empty( $paused_extensions[ $this->type ] ) ) {
unset( $paused_extensions[ $this->type ] );
}
// Clean up the entire option if we're removing the only error.
if ( ! $paused_extensions ) {
return delete_option( $option_name );
}
return update_option( $option_name, $paused_extensions );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Paused\_Extensions\_Storage::is\_api\_loaded()](is_api_loaded) wp-includes/class-wp-paused-extensions-storage.php | Checks whether the underlying API to store paused extensions is loaded. |
| [WP\_Paused\_Extensions\_Storage::get\_option\_name()](get_option_name) wp-includes/class-wp-paused-extensions-storage.php | Get the option name for storing paused extensions. |
| [delete\_option()](../../functions/delete_option) wp-includes/option.php | Removes option by name. Prevents removal of protected WordPress options. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Paused_Extensions_Storage::get( string $extension ): array|null WP\_Paused\_Extensions\_Storage::get( string $extension ): array|null
=====================================================================
Gets the error for an extension, if paused.
`$extension` string Required Plugin or theme directory name. array|null Error that is stored, or null if the extension is not paused.
File: `wp-includes/class-wp-paused-extensions-storage.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-paused-extensions-storage.php/)
```
public function get( $extension ) {
if ( ! $this->is_api_loaded() ) {
return null;
}
$paused_extensions = $this->get_all();
if ( ! isset( $paused_extensions[ $extension ] ) ) {
return null;
}
return $paused_extensions[ $extension ];
}
```
| Uses | Description |
| --- | --- |
| [WP\_Paused\_Extensions\_Storage::is\_api\_loaded()](is_api_loaded) wp-includes/class-wp-paused-extensions-storage.php | Checks whether the underlying API to store paused extensions is loaded. |
| [WP\_Paused\_Extensions\_Storage::get\_all()](get_all) wp-includes/class-wp-paused-extensions-storage.php | Gets the paused extensions with their errors. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Block_Supports::apply_block_supports(): string[] WP\_Block\_Supports::apply\_block\_supports(): string[]
=======================================================
Generates an array of HTML attributes, such as classes, by applying to the given block all of the features that the block supports.
string[] Array of HTML attributes.
File: `wp-includes/class-wp-block-supports.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-supports.php/)
```
public function apply_block_supports() {
$block_type = WP_Block_Type_Registry::get_instance()->get_registered(
self::$block_to_render['blockName']
);
// If no render_callback, assume styles have been previously handled.
if ( ! $block_type || empty( $block_type ) ) {
return array();
}
$block_attributes = array_key_exists( 'attrs', self::$block_to_render )
? self::$block_to_render['attrs']
: array();
$output = array();
foreach ( $this->block_supports as $block_support_config ) {
if ( ! isset( $block_support_config['apply'] ) ) {
continue;
}
$new_attributes = call_user_func(
$block_support_config['apply'],
$block_type,
$block_attributes
);
if ( ! empty( $new_attributes ) ) {
foreach ( $new_attributes as $attribute_name => $attribute_value ) {
if ( empty( $output[ $attribute_name ] ) ) {
$output[ $attribute_name ] = $attribute_value;
} else {
$output[ $attribute_name ] .= " $attribute_value";
}
}
}
}
return $output;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_Type\_Registry::get\_instance()](../wp_block_type_registry/get_instance) wp-includes/class-wp-block-type-registry.php | Utility method to retrieve the main instance of the class. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Block_Supports::init() WP\_Block\_Supports::init()
===========================
Initializes the block supports. It registers the block supports block attributes.
File: `wp-includes/class-wp-block-supports.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-supports.php/)
```
public static function init() {
$instance = self::get_instance();
$instance->register_attributes();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_Supports::get\_instance()](get_instance) wp-includes/class-wp-block-supports.php | Utility method to retrieve the main instance of the class. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Block_Supports::register( string $block_support_name, array $block_support_config ) WP\_Block\_Supports::register( string $block\_support\_name, array $block\_support\_config )
============================================================================================
Registers a block support.
`$block_support_name` string Required Block support name. `$block_support_config` array Required Array containing the properties of the block support. File: `wp-includes/class-wp-block-supports.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-supports.php/)
```
public function register( $block_support_name, $block_support_config ) {
$this->block_supports[ $block_support_name ] = array_merge(
$block_support_config,
array( 'name' => $block_support_name )
);
}
```
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Block_Supports::register_attributes() WP\_Block\_Supports::register\_attributes()
===========================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Registers the block attributes required by the different block supports.
File: `wp-includes/class-wp-block-supports.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-supports.php/)
```
private function register_attributes() {
$block_registry = WP_Block_Type_Registry::get_instance();
$registered_block_types = $block_registry->get_all_registered();
foreach ( $registered_block_types as $block_type ) {
if ( ! property_exists( $block_type, 'supports' ) ) {
continue;
}
if ( ! $block_type->attributes ) {
$block_type->attributes = array();
}
foreach ( $this->block_supports as $block_support_config ) {
if ( ! isset( $block_support_config['register_attribute'] ) ) {
continue;
}
call_user_func(
$block_support_config['register_attribute'],
$block_type
);
}
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_Type\_Registry::get\_instance()](../wp_block_type_registry/get_instance) wp-includes/class-wp-block-type-registry.php | Utility method to retrieve the main instance of the class. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Block_Supports::get_instance(): WP_Block_Supports WP\_Block\_Supports::get\_instance(): WP\_Block\_Supports
=========================================================
Utility method to retrieve the main instance of the class.
The instance will be created if it does not exist yet.
[WP\_Block\_Supports](../wp_block_supports) The main instance.
File: `wp-includes/class-wp-block-supports.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-supports.php/)
```
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
```
| Used By | Description |
| --- | --- |
| [get\_block\_wrapper\_attributes()](../../functions/get_block_wrapper_attributes) wp-includes/class-wp-block-supports.php | Generates a string of attributes by applying to the current block being rendered all of the features that the block supports. |
| [WP\_Block\_Supports::init()](init) wp-includes/class-wp-block-supports.php | Initializes the block supports. It registers the block supports block attributes. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Privacy_Requests_Table::single_row( WP_User_Request $item ) WP\_Privacy\_Requests\_Table::single\_row( WP\_User\_Request $item )
====================================================================
Generates content for a single row of the table,
`$item` [WP\_User\_Request](../wp_user_request) Required The current item. File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
public function single_row( $item ) {
$status = $item->status;
echo '<tr id="request-' . esc_attr( $item->ID ) . '" class="status-' . esc_attr( $status ) . '">';
$this->single_row_columns( $item );
echo '</tr>';
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Requests_Table::prepare_items() WP\_Privacy\_Requests\_Table::prepare\_items()
==============================================
Prepare items to output.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
public function prepare_items() {
$this->items = array();
$posts_per_page = $this->get_items_per_page( $this->request_type . '_requests_per_page' );
$args = array(
'post_type' => $this->post_type,
'post_name__in' => array( $this->request_type ),
'posts_per_page' => $posts_per_page,
'offset' => isset( $_REQUEST['paged'] ) ? max( 0, absint( $_REQUEST['paged'] ) - 1 ) * $posts_per_page : 0,
'post_status' => 'any',
's' => isset( $_REQUEST['s'] ) ? sanitize_text_field( $_REQUEST['s'] ) : '',
);
$orderby_mapping = array(
'requester' => 'post_title',
'requested' => 'post_date',
);
if ( isset( $_REQUEST['orderby'] ) && isset( $orderby_mapping[ $_REQUEST['orderby'] ] ) ) {
$args['orderby'] = $orderby_mapping[ $_REQUEST['orderby'] ];
}
if ( isset( $_REQUEST['order'] ) && in_array( strtoupper( $_REQUEST['order'] ), array( 'ASC', 'DESC' ), true ) ) {
$args['order'] = strtoupper( $_REQUEST['order'] );
}
if ( ! empty( $_REQUEST['filter-status'] ) ) {
$filter_status = isset( $_REQUEST['filter-status'] ) ? sanitize_text_field( $_REQUEST['filter-status'] ) : '';
$args['post_status'] = $filter_status;
}
$requests_query = new WP_Query( $args );
$requests = $requests_query->posts;
foreach ( $requests as $request ) {
$this->items[] = wp_get_user_request( $request->ID );
}
$this->items = array_filter( $this->items );
$this->set_pagination_args(
array(
'total_items' => $requests_query->found_posts,
'per_page' => $posts_per_page,
)
);
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_user\_request()](../../functions/wp_get_user_request) wp-includes/user.php | Returns the user request object for the specified request ID. |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [WP\_Query::\_\_construct()](../wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Version | Description |
| --- | --- |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Added support for column sorting. |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
| programming_docs |
wordpress WP_Privacy_Requests_Table::get_default_primary_column_name(): string WP\_Privacy\_Requests\_Table::get\_default\_primary\_column\_name(): string
===========================================================================
Default primary column.
string Default primary column name.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
protected function get_default_primary_column_name() {
return 'email';
}
```
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Requests_Table::get_admin_url(): string WP\_Privacy\_Requests\_Table::get\_admin\_url(): string
=======================================================
Normalize the admin URL to the current page (by request\_type).
string URL to the current admin page.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
protected function get_admin_url() {
$pagenow = str_replace( '_', '-', $this->request_type );
if ( 'remove-personal-data' === $pagenow ) {
$pagenow = 'erase-personal-data';
}
return admin_url( $pagenow . '.php' );
}
```
| Uses | Description |
| --- | --- |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| Used By | Description |
| --- | --- |
| [WP\_Privacy\_Requests\_Table::get\_views()](get_views) wp-admin/includes/class-wp-privacy-requests-table.php | Get an associative array ( id => link ) with the list of views available on this table. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_Privacy_Requests_Table::get_request_counts(): object WP\_Privacy\_Requests\_Table::get\_request\_counts(): object
============================================================
Count number of requests for each status.
object Number of posts for each status.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
protected function get_request_counts() {
global $wpdb;
$cache_key = $this->post_type . '-' . $this->request_type;
$counts = wp_cache_get( $cache_key, 'counts' );
if ( false !== $counts ) {
return $counts;
}
$query = "
SELECT post_status, COUNT( * ) AS num_posts
FROM {$wpdb->posts}
WHERE post_type = %s
AND post_name = %s
GROUP BY post_status";
$results = (array) $wpdb->get_results( $wpdb->prepare( $query, $this->post_type, $this->request_type ), ARRAY_A );
$counts = array_fill_keys( get_post_stati(), 0 );
foreach ( $results as $row ) {
$counts[ $row['post_status'] ] = $row['num_posts'];
}
$counts = (object) $counts;
wp_cache_set( $cache_key, $counts, 'counts' );
return $counts;
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_stati()](../../functions/get_post_stati) wp-includes/post.php | Gets a list of post statuses. |
| [wp\_cache\_set()](../../functions/wp_cache_set) wp-includes/cache.php | Saves the data to the cache. |
| [wp\_cache\_get()](../../functions/wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| [wpdb::get\_results()](../wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_Privacy\_Requests\_Table::get\_views()](get_views) wp-admin/includes/class-wp-privacy-requests-table.php | Get an associative array ( id => link ) with the list of views available on this table. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Requests_Table::column_status( WP_User_Request $item ): string WP\_Privacy\_Requests\_Table::column\_status( WP\_User\_Request $item ): string
===============================================================================
Status column.
`$item` [WP\_User\_Request](../wp_user_request) Required Item being shown. string Status column markup.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
public function column_status( $item ) {
$status = get_post_status( $item->ID );
$status_object = get_post_status_object( $status );
if ( ! $status_object || empty( $status_object->label ) ) {
return '-';
}
$timestamp = false;
switch ( $status ) {
case 'request-confirmed':
$timestamp = $item->confirmed_timestamp;
break;
case 'request-completed':
$timestamp = $item->completed_timestamp;
break;
}
echo '<span class="status-label status-' . esc_attr( $status ) . '">';
echo esc_html( $status_object->label );
if ( $timestamp ) {
echo ' (' . $this->get_timestamp_as_date( $timestamp ) . ')';
}
echo '</span>';
}
```
| Uses | Description |
| --- | --- |
| [WP\_Privacy\_Requests\_Table::get\_timestamp\_as\_date()](get_timestamp_as_date) wp-admin/includes/class-wp-privacy-requests-table.php | Convert timestamp for display. |
| [get\_post\_status()](../../functions/get_post_status) wp-includes/post.php | Retrieves the post status based on the post ID. |
| [get\_post\_status\_object()](../../functions/get_post_status_object) wp-includes/post.php | Retrieves a post status object by name. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Requests_Table::get_views(): string[] WP\_Privacy\_Requests\_Table::get\_views(): string[]
====================================================
Get an associative array ( id => link ) with the list of views available on this table.
string[] An array of HTML links keyed by their view.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
protected function get_views() {
$current_status = isset( $_REQUEST['filter-status'] ) ? sanitize_text_field( $_REQUEST['filter-status'] ) : '';
$statuses = _wp_privacy_statuses();
$views = array();
$counts = $this->get_request_counts();
$total_requests = absint( array_sum( (array) $counts ) );
// Normalized admin URL.
$admin_url = $this->get_admin_url();
$status_label = sprintf(
/* translators: %s: Number of requests. */
_nx(
'All <span class="count">(%s)</span>',
'All <span class="count">(%s)</span>',
$total_requests,
'requests'
),
number_format_i18n( $total_requests )
);
$views['all'] = array(
'url' => esc_url( $admin_url ),
'label' => $status_label,
'current' => empty( $current_status ),
);
foreach ( $statuses as $status => $label ) {
$post_status = get_post_status_object( $status );
if ( ! $post_status ) {
continue;
}
$total_status_requests = absint( $counts->{$status} );
if ( ! $total_status_requests ) {
continue;
}
$status_label = sprintf(
translate_nooped_plural( $post_status->label_count, $total_status_requests ),
number_format_i18n( $total_status_requests )
);
$status_link = add_query_arg( 'filter-status', $status, $admin_url );
$views[ $status ] = array(
'url' => esc_url( $status_link ),
'label' => $status_label,
'current' => $status === $current_status,
);
}
return $this->get_views_links( $views );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Privacy\_Requests\_Table::get\_admin\_url()](get_admin_url) wp-admin/includes/class-wp-privacy-requests-table.php | Normalize the admin URL to the current page (by request\_type). |
| [\_wp\_privacy\_statuses()](../../functions/_wp_privacy_statuses) wp-includes/post.php | Returns statuses for privacy requests. |
| [WP\_Privacy\_Requests\_Table::get\_request\_counts()](get_request_counts) wp-admin/includes/class-wp-privacy-requests-table.php | Count number of requests for each status. |
| [translate\_nooped\_plural()](../../functions/translate_nooped_plural) wp-includes/l10n.php | Translates and returns the singular or plural form of a string that’s been registered with [\_n\_noop()](../../functions/_n_noop) or [\_nx\_noop()](../../functions/_nx_noop) . |
| [\_nx()](../../functions/_nx) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number, with gettext context. |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [get\_post\_status\_object()](../../functions/get_post_status_object) wp-includes/post.php | Retrieves a post status object by name. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Requests_Table::get_sortable_columns(): array WP\_Privacy\_Requests\_Table::get\_sortable\_columns(): array
=============================================================
Get a list of sortable columns.
array Default sortable columns.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
protected function get_sortable_columns() {
/*
* The initial sorting is by 'Requested' (post_date) and descending.
* With initial sorting, the first click on 'Requested' should be ascending.
* With 'Requester' sorting active, the next click on 'Requested' should be descending.
*/
$desc_first = isset( $_GET['orderby'] );
return array(
'email' => 'requester',
'created_timestamp' => array( 'requested', $desc_first ),
);
}
```
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Requests_Table::column_created_timestamp( WP_User_Request $item ): string WP\_Privacy\_Requests\_Table::column\_created\_timestamp( WP\_User\_Request $item ): string
===========================================================================================
Created timestamp column. Overridden by children.
`$item` [WP\_User\_Request](../wp_user_request) Required Item being shown. string Human readable date.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
public function column_created_timestamp( $item ) {
return $this->get_timestamp_as_date( $item->created_timestamp );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Privacy\_Requests\_Table::get\_timestamp\_as\_date()](get_timestamp_as_date) wp-admin/includes/class-wp-privacy-requests-table.php | Convert timestamp for display. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Introduced. |
wordpress WP_Privacy_Requests_Table::column_email( WP_User_Request $item ): string WP\_Privacy\_Requests\_Table::column\_email( WP\_User\_Request $item ): string
==============================================================================
Actions column. Overridden by children.
`$item` [WP\_User\_Request](../wp_user_request) Required Item being shown. string Email column markup.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
public function column_email( $item ) {
return sprintf( '<a href="%1$s">%2$s</a> %3$s', esc_url( 'mailto:' . $item->email ), $item->email, $this->row_actions( array() ) );
}
```
| Uses | Description |
| --- | --- |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Requests_Table::embed_scripts() WP\_Privacy\_Requests\_Table::embed\_scripts()
==============================================
Embed scripts used to perform actions. Overridden by children.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
public function embed_scripts() {}
```
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Requests_Table::column_cb( WP_User_Request $item ): string WP\_Privacy\_Requests\_Table::column\_cb( WP\_User\_Request $item ): string
===========================================================================
Checkbox column.
`$item` [WP\_User\_Request](../wp_user_request) Required Item being shown. string Checkbox column markup.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
public function column_cb( $item ) {
return sprintf( '<input type="checkbox" name="request_id[]" value="%1$s" /><span class="spinner"></span>', esc_attr( $item->ID ) );
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Requests_Table::process_bulk_action() WP\_Privacy\_Requests\_Table::process\_bulk\_action()
=====================================================
Process bulk actions.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
public function process_bulk_action() {
$action = $this->current_action();
$request_ids = isset( $_REQUEST['request_id'] ) ? wp_parse_id_list( wp_unslash( $_REQUEST['request_id'] ) ) : array();
if ( empty( $request_ids ) ) {
return;
}
$count = 0;
$failures = 0;
check_admin_referer( 'bulk-privacy_requests' );
switch ( $action ) {
case 'resend':
foreach ( $request_ids as $request_id ) {
$resend = _wp_privacy_resend_request( $request_id );
if ( $resend && ! is_wp_error( $resend ) ) {
$count++;
} else {
$failures++;
}
}
if ( $failures ) {
add_settings_error(
'bulk_action',
'bulk_action',
sprintf(
/* translators: %d: Number of requests. */
_n(
'%d confirmation request failed to resend.',
'%d confirmation requests failed to resend.',
$failures
),
$failures
),
'error'
);
}
if ( $count ) {
add_settings_error(
'bulk_action',
'bulk_action',
sprintf(
/* translators: %d: Number of requests. */
_n(
'%d confirmation request re-sent successfully.',
'%d confirmation requests re-sent successfully.',
$count
),
$count
),
'success'
);
}
break;
case 'complete':
foreach ( $request_ids as $request_id ) {
$result = _wp_privacy_completed_request( $request_id );
if ( $result && ! is_wp_error( $result ) ) {
$count++;
}
}
add_settings_error(
'bulk_action',
'bulk_action',
sprintf(
/* translators: %d: Number of requests. */
_n(
'%d request marked as complete.',
'%d requests marked as complete.',
$count
),
$count
),
'success'
);
break;
case 'delete':
foreach ( $request_ids as $request_id ) {
if ( wp_delete_post( $request_id, true ) ) {
$count++;
} else {
$failures++;
}
}
if ( $failures ) {
add_settings_error(
'bulk_action',
'bulk_action',
sprintf(
/* translators: %d: Number of requests. */
_n(
'%d request failed to delete.',
'%d requests failed to delete.',
$failures
),
$failures
),
'error'
);
}
if ( $count ) {
add_settings_error(
'bulk_action',
'bulk_action',
sprintf(
/* translators: %d: Number of requests. */
_n(
'%d request deleted successfully.',
'%d requests deleted successfully.',
$count
),
$count
),
'success'
);
}
break;
}
}
```
| Uses | Description |
| --- | --- |
| [\_wp\_privacy\_resend\_request()](../../functions/_wp_privacy_resend_request) wp-admin/includes/privacy-tools.php | Resend an existing request and return the result. |
| [\_wp\_privacy\_completed\_request()](../../functions/_wp_privacy_completed_request) wp-admin/includes/privacy-tools.php | Marks a request as completed by the admin and logs the current timestamp. |
| [add\_settings\_error()](../../functions/add_settings_error) wp-admin/includes/template.php | Registers a settings error to be displayed to the user. |
| [\_n()](../../functions/_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [check\_admin\_referer()](../../functions/check_admin_referer) wp-includes/pluggable.php | Ensures intent by verifying that a user was referred from another admin page with the correct security nonce. |
| [wp\_parse\_id\_list()](../../functions/wp_parse_id_list) wp-includes/functions.php | Cleans up an array, comma- or space-separated list of IDs. |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Added support for the `complete` action. |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Requests_Table::get_columns(): string[] WP\_Privacy\_Requests\_Table::get\_columns(): string[]
======================================================
Get columns to show in the list table.
string[] Array of column titles keyed by their column name.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
public function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'email' => __( 'Requester' ),
'status' => __( 'Status' ),
'created_timestamp' => __( 'Requested' ),
'next_steps' => __( 'Next steps' ),
);
return $columns;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
| programming_docs |
wordpress WP_Privacy_Requests_Table::get_bulk_actions(): array WP\_Privacy\_Requests\_Table::get\_bulk\_actions(): array
=========================================================
Get bulk actions.
array Array of bulk action labels keyed by their action.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
protected function get_bulk_actions() {
return array(
'resend' => __( 'Resend confirmation requests' ),
'complete' => __( 'Mark requests as completed' ),
'delete' => __( 'Delete requests' ),
);
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Requests_Table::get_timestamp_as_date( int $timestamp ): string WP\_Privacy\_Requests\_Table::get\_timestamp\_as\_date( int $timestamp ): string
================================================================================
Convert timestamp for display.
`$timestamp` int Required Event timestamp. string Human readable date.
File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
protected function get_timestamp_as_date( $timestamp ) {
if ( empty( $timestamp ) ) {
return '';
}
$time_diff = time() - $timestamp;
if ( $time_diff >= 0 && $time_diff < DAY_IN_SECONDS ) {
/* translators: %s: Human-readable time difference. */
return sprintf( __( '%s ago' ), human_time_diff( $timestamp ) );
}
return date_i18n( get_option( 'date_format' ), $timestamp );
}
```
| Uses | Description |
| --- | --- |
| [date\_i18n()](../../functions/date_i18n) wp-includes/functions.php | Retrieves the date in localized format, based on a sum of Unix timestamp and timezone offset in seconds. |
| [human\_time\_diff()](../../functions/human_time_diff) wp-includes/formatting.php | Determines the difference between two timestamps. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Privacy\_Requests\_Table::column\_created\_timestamp()](column_created_timestamp) wp-admin/includes/class-wp-privacy-requests-table.php | Created timestamp column. Overridden by children. |
| [WP\_Privacy\_Requests\_Table::column\_status()](column_status) wp-admin/includes/class-wp-privacy-requests-table.php | Status column. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Requests_Table::column_next_steps( WP_User_Request $item ) WP\_Privacy\_Requests\_Table::column\_next\_steps( WP\_User\_Request $item )
============================================================================
Next steps column. Overridden by children.
`$item` [WP\_User\_Request](../wp_user_request) Required Item being shown. File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
public function column_next_steps( $item ) {}
```
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Requests_Table::column_default( WP_User_Request $item, string $column_name ) WP\_Privacy\_Requests\_Table::column\_default( WP\_User\_Request $item, string $column\_name )
==============================================================================================
Default column handler.
`$item` [WP\_User\_Request](../wp_user_request) Required Item being shown. `$column_name` string Required Name of column being shown. File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/)
```
public function column_default( $item, $column_name ) {
/**
* Fires for each custom column of a specific request type in the Requests list table.
*
* Custom columns are registered using the {@see 'manage_export-personal-data_columns'}
* and the {@see 'manage_erase-personal-data_columns'} filters.
*
* @since 5.7.0
*
* @param string $column_name The name of the column to display.
* @param WP_User_Request $item The item being shown.
*/
do_action( "manage_{$this->screen->id}_custom_column", $column_name, $item );
}
```
[do\_action( "manage\_{$this->screen->id}\_custom\_column", string $column\_name, array $item )](../../hooks/manage_this-screen-id_custom_column)
Fires for each custom column in the Application Passwords list table.
| Uses | Description |
| --- | --- |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Added `manage_{$this->screen->id}_custom_column` action. |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Recovery_Mode_Email_Service::get_plugin( array $extension ): array|false WP\_Recovery\_Mode\_Email\_Service::get\_plugin( array $extension ): array|false
================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Return the details for a single plugin based on the extension data from an error.
`$extension` array Required The extension that caused the error.
* `slug`stringThe extension slug. The directory of the plugin or theme.
* `type`stringThe extension type. Either `'plugin'` or `'theme'`.
array|false A plugin array [get\_plugins()](../../functions/get_plugins) or `false` if no plugin was found.
File: `wp-includes/class-wp-recovery-mode-email-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-email-service.php/)
```
private function get_plugin( $extension ) {
if ( ! function_exists( 'get_plugins' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$plugins = get_plugins();
// Assume plugin main file name first since it is a common convention.
if ( isset( $plugins[ "{$extension['slug']}/{$extension['slug']}.php" ] ) ) {
return $plugins[ "{$extension['slug']}/{$extension['slug']}.php" ];
} else {
foreach ( $plugins as $file => $plugin_data ) {
if ( 0 === strpos( $file, "{$extension['slug']}/" ) || $file === $extension['slug'] ) {
return $plugin_data;
}
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [get\_plugins()](../../functions/get_plugins) wp-admin/includes/plugin.php | Checks the plugins directory and retrieve all plugin files with plugin data. |
| Used By | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Email\_Service::get\_debug()](get_debug) wp-includes/class-wp-recovery-mode-email-service.php | Return debug information in an easy to manipulate format. |
| [WP\_Recovery\_Mode\_Email\_Service::get\_cause()](get_cause) wp-includes/class-wp-recovery-mode-email-service.php | Gets the description indicating the possible cause for the error. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_Recovery_Mode_Email_Service::get_debug( array $extension ): array WP\_Recovery\_Mode\_Email\_Service::get\_debug( array $extension ): array
=========================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Return debug information in an easy to manipulate format.
`$extension` array Required The extension that caused the error.
* `slug`stringThe extension slug. The directory of the plugin or theme.
* `type`stringThe extension type. Either `'plugin'` or `'theme'`.
array An associative array of debug information.
File: `wp-includes/class-wp-recovery-mode-email-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-email-service.php/)
```
private function get_debug( $extension ) {
$theme = wp_get_theme();
$wp_version = get_bloginfo( 'version' );
if ( $extension ) {
$plugin = $this->get_plugin( $extension );
} else {
$plugin = null;
}
$debug = array(
'wp' => sprintf(
/* translators: %s: Current WordPress version number. */
__( 'WordPress version %s' ),
$wp_version
),
'theme' => sprintf(
/* translators: 1: Current active theme name. 2: Current active theme version. */
__( 'Active theme: %1$s (version %2$s)' ),
$theme->get( 'Name' ),
$theme->get( 'Version' )
),
);
if ( null !== $plugin ) {
$debug['plugin'] = sprintf(
/* translators: 1: The failing plugins name. 2: The failing plugins version. */
__( 'Current plugin: %1$s (version %2$s)' ),
$plugin['Name'],
$plugin['Version']
);
}
$debug['php'] = sprintf(
/* translators: %s: The currently used PHP version. */
__( 'PHP version %s' ),
PHP_VERSION
);
return $debug;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Email\_Service::get\_plugin()](get_plugin) wp-includes/class-wp-recovery-mode-email-service.php | Return the details for a single plugin based on the extension data from an error. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| Used By | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Email\_Service::send\_recovery\_mode\_email()](send_recovery_mode_email) wp-includes/class-wp-recovery-mode-email-service.php | Sends the Recovery Mode email to the site admin email address. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_Recovery_Mode_Email_Service::__construct( WP_Recovery_Mode_Link_Service $link_service ) WP\_Recovery\_Mode\_Email\_Service::\_\_construct( WP\_Recovery\_Mode\_Link\_Service $link\_service )
=====================================================================================================
[WP\_Recovery\_Mode\_Email\_Service](../wp_recovery_mode_email_service) constructor.
`$link_service` [WP\_Recovery\_Mode\_Link\_Service](../wp_recovery_mode_link_service) Required File: `wp-includes/class-wp-recovery-mode-email-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-email-service.php/)
```
public function __construct( WP_Recovery_Mode_Link_Service $link_service ) {
$this->link_service = $link_service;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Recovery\_Mode::\_\_construct()](../wp_recovery_mode/__construct) wp-includes/class-wp-recovery-mode.php | [WP\_Recovery\_Mode](../wp_recovery_mode) constructor. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Recovery_Mode_Email_Service::maybe_send_recovery_mode_email( int $rate_limit, array $error, array $extension ): true|WP_Error WP\_Recovery\_Mode\_Email\_Service::maybe\_send\_recovery\_mode\_email( int $rate\_limit, array $error, array $extension ): true|WP\_Error
==========================================================================================================================================
Sends the recovery mode email if the rate limit has not been sent.
`$rate_limit` int Required Number of seconds before another email can be sent. `$error` array Required Error details from `error_get_last()`. `$extension` array Required The extension that caused the error.
* `slug`stringThe extension slug. The plugin or theme's directory.
* `type`stringThe extension type. Either `'plugin'` or `'theme'`.
true|[WP\_Error](../wp_error) True if email sent, [WP\_Error](../wp_error) otherwise.
File: `wp-includes/class-wp-recovery-mode-email-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-email-service.php/)
```
public function maybe_send_recovery_mode_email( $rate_limit, $error, $extension ) {
$last_sent = get_option( self::RATE_LIMIT_OPTION );
if ( ! $last_sent || time() > $last_sent + $rate_limit ) {
if ( ! update_option( self::RATE_LIMIT_OPTION, time() ) ) {
return new WP_Error( 'storage_error', __( 'Could not update the email last sent time.' ) );
}
$sent = $this->send_recovery_mode_email( $rate_limit, $error, $extension );
if ( $sent ) {
return true;
}
return new WP_Error(
'email_failed',
sprintf(
/* translators: %s: mail() */
__( 'The email could not be sent. Possible reason: your host may have disabled the %s function.' ),
'mail()'
)
);
}
$err_message = sprintf(
/* translators: 1: Last sent as a human time diff, 2: Wait time as a human time diff. */
__( 'A recovery link was already sent %1$s ago. Please wait another %2$s before requesting a new email.' ),
human_time_diff( $last_sent ),
human_time_diff( $last_sent + $rate_limit )
);
return new WP_Error( 'email_sent_already', $err_message );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Email\_Service::send\_recovery\_mode\_email()](send_recovery_mode_email) wp-includes/class-wp-recovery-mode-email-service.php | Sends the Recovery Mode email to the site admin email address. |
| [human\_time\_diff()](../../functions/human_time_diff) wp-includes/formatting.php | Determines the difference between two timestamps. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Recovery_Mode_Email_Service::get_recovery_mode_email_address(): string WP\_Recovery\_Mode\_Email\_Service::get\_recovery\_mode\_email\_address(): string
=================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Gets the email address to send the recovery mode link to.
string Email address to send recovery mode link to.
File: `wp-includes/class-wp-recovery-mode-email-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-email-service.php/)
```
private function get_recovery_mode_email_address() {
if ( defined( 'RECOVERY_MODE_EMAIL' ) && is_email( RECOVERY_MODE_EMAIL ) ) {
return RECOVERY_MODE_EMAIL;
}
return get_option( 'admin_email' );
}
```
| Uses | Description |
| --- | --- |
| [is\_email()](../../functions/is_email) wp-includes/formatting.php | Verifies that an email is valid. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Email\_Service::send\_recovery\_mode\_email()](send_recovery_mode_email) wp-includes/class-wp-recovery-mode-email-service.php | Sends the Recovery Mode email to the site admin email address. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Recovery_Mode_Email_Service::send_recovery_mode_email( int $rate_limit, array $error, array $extension ): bool WP\_Recovery\_Mode\_Email\_Service::send\_recovery\_mode\_email( int $rate\_limit, array $error, array $extension ): bool
=========================================================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Sends the Recovery Mode email to the site admin email address.
`$rate_limit` int Required Number of seconds before another email can be sent. `$error` array Required Error details from `error_get_last()`. `$extension` array Required The extension that caused the error.
* `slug`stringThe extension slug. The directory of the plugin or theme.
* `type`stringThe extension type. Either `'plugin'` or `'theme'`.
bool Whether the email was sent successfully.
File: `wp-includes/class-wp-recovery-mode-email-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-email-service.php/)
```
private function send_recovery_mode_email( $rate_limit, $error, $extension ) {
$url = $this->link_service->generate_url();
$blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
$switched_locale = false;
// The switch_to_locale() function is loaded before it can actually be used.
if ( function_exists( 'switch_to_locale' ) && isset( $GLOBALS['wp_locale_switcher'] ) ) {
$switched_locale = switch_to_locale( get_locale() );
}
if ( $extension ) {
$cause = $this->get_cause( $extension );
$details = wp_strip_all_tags( wp_get_extension_error_description( $error ) );
if ( $details ) {
$header = __( 'Error Details' );
$details = "\n\n" . $header . "\n" . str_pad( '', strlen( $header ), '=' ) . "\n" . $details;
}
} else {
$cause = '';
$details = '';
}
/**
* Filters the support message sent with the the fatal error protection email.
*
* @since 5.2.0
*
* @param string $message The Message to include in the email.
*/
$support = apply_filters( 'recovery_email_support_info', __( 'Please contact your host for assistance with investigating this issue further.' ) );
/**
* Filters the debug information included in the fatal error protection email.
*
* @since 5.3.0
*
* @param array $message An associative array of debug information.
*/
$debug = apply_filters( 'recovery_email_debug_info', $this->get_debug( $extension ) );
/* translators: Do not translate LINK, EXPIRES, CAUSE, DETAILS, SITEURL, PAGEURL, SUPPORT. DEBUG: those are placeholders. */
$message = __(
'Howdy!
Since WordPress 5.2 there is a built-in feature that detects when a plugin or theme causes a fatal error on your site, and notifies you with this automated email.
###CAUSE###
First, visit your website (###SITEURL###) and check for any visible issues. Next, visit the page where the error was caught (###PAGEURL###) and check for any visible issues.
###SUPPORT###
If your site appears broken and you can\'t access your dashboard normally, WordPress now has a special "recovery mode". This lets you safely login to your dashboard and investigate further.
###LINK###
To keep your site safe, this link will expire in ###EXPIRES###. Don\'t worry about that, though: a new link will be emailed to you if the error occurs again after it expires.
When seeking help with this issue, you may be asked for some of the following information:
###DEBUG###
###DETAILS###'
);
$message = str_replace(
array(
'###LINK###',
'###EXPIRES###',
'###CAUSE###',
'###DETAILS###',
'###SITEURL###',
'###PAGEURL###',
'###SUPPORT###',
'###DEBUG###',
),
array(
$url,
human_time_diff( time() + $rate_limit ),
$cause ? "\n{$cause}\n" : "\n",
$details,
home_url( '/' ),
home_url( $_SERVER['REQUEST_URI'] ),
$support,
implode( "\r\n", $debug ),
),
$message
);
$email = array(
'to' => $this->get_recovery_mode_email_address(),
/* translators: %s: Site title. */
'subject' => __( '[%s] Your Site is Experiencing a Technical Issue' ),
'message' => $message,
'headers' => '',
'attachments' => '',
);
/**
* Filters the contents of the Recovery Mode email.
*
* @since 5.2.0
* @since 5.6.0 The `$email` argument includes the `attachments` key.
*
* @param array $email {
* Used to build a call to wp_mail().
*
* @type string|array $to Array or comma-separated list of email addresses to send message.
* @type string $subject Email subject
* @type string $message Message contents
* @type string|array $headers Optional. Additional headers.
* @type string|array $attachments Optional. Files to attach.
* }
* @param string $url URL to enter recovery mode.
*/
$email = apply_filters( 'recovery_mode_email', $email, $url );
$sent = wp_mail(
$email['to'],
wp_specialchars_decode( sprintf( $email['subject'], $blogname ) ),
$email['message'],
$email['headers'],
$email['attachments']
);
if ( $switched_locale ) {
restore_previous_locale();
}
return $sent;
}
```
[apply\_filters( 'recovery\_email\_debug\_info', array $message )](../../hooks/recovery_email_debug_info)
Filters the debug information included in the fatal error protection email.
[apply\_filters( 'recovery\_email\_support\_info', string $message )](../../hooks/recovery_email_support_info)
Filters the support message sent with the the fatal error protection email.
[apply\_filters( 'recovery\_mode\_email', array $email, string $url )](../../hooks/recovery_mode_email)
Filters the contents of the Recovery Mode email.
| Uses | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Email\_Service::get\_debug()](get_debug) wp-includes/class-wp-recovery-mode-email-service.php | Return debug information in an easy to manipulate format. |
| [WP\_Recovery\_Mode\_Email\_Service::get\_cause()](get_cause) wp-includes/class-wp-recovery-mode-email-service.php | Gets the description indicating the possible cause for the error. |
| [WP\_Recovery\_Mode\_Email\_Service::get\_recovery\_mode\_email\_address()](get_recovery_mode_email_address) wp-includes/class-wp-recovery-mode-email-service.php | Gets the email address to send the recovery mode link to. |
| [wp\_get\_extension\_error\_description()](../../functions/wp_get_extension_error_description) wp-includes/error-protection.php | Get a human readable description of an extension’s error. |
| [restore\_previous\_locale()](../../functions/restore_previous_locale) wp-includes/l10n.php | Restores the translations according to the previous locale. |
| [switch\_to\_locale()](../../functions/switch_to_locale) wp-includes/l10n.php | Switches the translations according to the given locale. |
| [get\_locale()](../../functions/get_locale) wp-includes/l10n.php | Retrieves the current locale. |
| [wp\_strip\_all\_tags()](../../functions/wp_strip_all_tags) wp-includes/formatting.php | Properly strips all HTML tags including script and style |
| [human\_time\_diff()](../../functions/human_time_diff) wp-includes/formatting.php | Determines the difference between two timestamps. |
| [wp\_specialchars\_decode()](../../functions/wp_specialchars_decode) wp-includes/formatting.php | Converts a number of HTML entities into their special characters. |
| [wp\_mail()](../../functions/wp_mail) wp-includes/pluggable.php | Sends an email, similar to PHP’s mail function. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Email\_Service::maybe\_send\_recovery\_mode\_email()](maybe_send_recovery_mode_email) wp-includes/class-wp-recovery-mode-email-service.php | Sends the recovery mode email if the rate limit has not been sent. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Recovery_Mode_Email_Service::get_cause( array $extension ): string WP\_Recovery\_Mode\_Email\_Service::get\_cause( array $extension ): string
==========================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Gets the description indicating the possible cause for the error.
`$extension` array Required The extension that caused the error.
* `slug`stringThe extension slug. The directory of the plugin or theme.
* `type`stringThe extension type. Either `'plugin'` or `'theme'`.
string Message about which extension caused the error.
File: `wp-includes/class-wp-recovery-mode-email-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-email-service.php/)
```
private function get_cause( $extension ) {
if ( 'plugin' === $extension['type'] ) {
$plugin = $this->get_plugin( $extension );
if ( false === $plugin ) {
$name = $extension['slug'];
} else {
$name = $plugin['Name'];
}
/* translators: %s: Plugin name. */
$cause = sprintf( __( 'In this case, WordPress caught an error with one of your plugins, %s.' ), $name );
} else {
$theme = wp_get_theme( $extension['slug'] );
$name = $theme->exists() ? $theme->display( 'Name' ) : $extension['slug'];
/* translators: %s: Theme name. */
$cause = sprintf( __( 'In this case, WordPress caught an error with your theme, %s.' ), $name );
}
return $cause;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Email\_Service::get\_plugin()](get_plugin) wp-includes/class-wp-recovery-mode-email-service.php | Return the details for a single plugin based on the extension data from an error. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Email\_Service::send\_recovery\_mode\_email()](send_recovery_mode_email) wp-includes/class-wp-recovery-mode-email-service.php | Sends the Recovery Mode email to the site admin email address. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Recovery_Mode_Email_Service::clear_rate_limit(): bool WP\_Recovery\_Mode\_Email\_Service::clear\_rate\_limit(): bool
==============================================================
Clears the rate limit, allowing a new recovery mode email to be sent immediately.
bool True on success, false on failure.
File: `wp-includes/class-wp-recovery-mode-email-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-email-service.php/)
```
public function clear_rate_limit() {
return delete_option( self::RATE_LIMIT_OPTION );
}
```
| Uses | Description |
| --- | --- |
| [delete\_option()](../../functions/delete_option) wp-includes/option.php | Removes option by name. Prevents removal of protected WordPress options. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress Requests_IPv6::check_ipv6( string $ip ): bool Requests\_IPv6::check\_ipv6( string $ip ): bool
===============================================
Checks an IPv6 address
Checks if the given IP is a valid IPv6 address
`$ip` string Required An IPv6 address bool true if $ip is a valid IPv6 address
File: `wp-includes/Requests/IPv6.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/ipv6.php/)
```
public static function check_ipv6($ip) {
$ip = self::uncompress($ip);
list($ipv6, $ipv4) = self::split_v6_v4($ip);
$ipv6 = explode(':', $ipv6);
$ipv4 = explode('.', $ipv4);
if (count($ipv6) === 8 && count($ipv4) === 1 || count($ipv6) === 6 && count($ipv4) === 4) {
foreach ($ipv6 as $ipv6_part) {
// The section can't be empty
if ($ipv6_part === '') {
return false;
}
// Nor can it be over four characters
if (strlen($ipv6_part) > 4) {
return false;
}
// Remove leading zeros (this is safe because of the above)
$ipv6_part = ltrim($ipv6_part, '0');
if ($ipv6_part === '') {
$ipv6_part = '0';
}
// Check the value is valid
$value = hexdec($ipv6_part);
if (dechex($value) !== strtolower($ipv6_part) || $value < 0 || $value > 0xFFFF) {
return false;
}
}
if (count($ipv4) === 4) {
foreach ($ipv4 as $ipv4_part) {
$value = (int) $ipv4_part;
if ((string) $value !== $ipv4_part || $value < 0 || $value > 0xFF) {
return false;
}
}
}
return true;
}
else {
return false;
}
}
```
| Uses | Description |
| --- | --- |
| [Requests\_IPv6::split\_v6\_v4()](split_v6_v4) wp-includes/Requests/IPv6.php | Splits an IPv6 address into the IPv6 and IPv4 representation parts |
| [Requests\_IPv6::uncompress()](uncompress) wp-includes/Requests/IPv6.php | Uncompresses an IPv6 address |
| Used By | Description |
| --- | --- |
| [rest\_is\_ip\_address()](../../functions/rest_is_ip_address) wp-includes/rest-api.php | Determines if an IP address is valid. |
| [Requests\_IRI::set\_host()](../requests_iri/set_host) wp-includes/Requests/IRI.php | Set the ihost. Returns true on success, false on failure (if there are any invalid characters). |
wordpress Requests_IPv6::uncompress( string $ip ): string Requests\_IPv6::uncompress( string $ip ): string
================================================
Uncompresses an IPv6 address
RFC 4291 allows you to compress consecutive zero pieces in an address to ‘::’. This method expects a valid IPv6 address and expands the ‘::’ to the required number of zero pieces.
Example: FF01::101 -> FF01:0:0:0:0:0:0:101 ::1 -> 0:0:0:0:0:0:0:1
`$ip` string Required An IPv6 address string The uncompressed IPv6 address
File: `wp-includes/Requests/IPv6.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/ipv6.php/)
```
public static function uncompress($ip) {
if (substr_count($ip, '::') !== 1) {
return $ip;
}
list($ip1, $ip2) = explode('::', $ip);
$c1 = ($ip1 === '') ? -1 : substr_count($ip1, ':');
$c2 = ($ip2 === '') ? -1 : substr_count($ip2, ':');
if (strpos($ip2, '.') !== false) {
$c2++;
}
// ::
if ($c1 === -1 && $c2 === -1) {
$ip = '0:0:0:0:0:0:0:0';
}
// ::xxx
elseif ($c1 === -1) {
$fill = str_repeat('0:', 7 - $c2);
$ip = str_replace('::', $fill, $ip);
}
// xxx::
elseif ($c2 === -1) {
$fill = str_repeat(':0', 7 - $c1);
$ip = str_replace('::', $fill, $ip);
}
// xxx::xxx
else {
$fill = ':' . str_repeat('0:', 6 - $c2 - $c1);
$ip = str_replace('::', $fill, $ip);
}
return $ip;
}
```
| Used By | Description |
| --- | --- |
| [Requests\_IPv6::check\_ipv6()](check_ipv6) wp-includes/Requests/IPv6.php | Checks an IPv6 address |
| [Requests\_IPv6::compress()](compress) wp-includes/Requests/IPv6.php | Compresses an IPv6 address |
wordpress Requests_IPv6::compress( string $ip ): string Requests\_IPv6::compress( string $ip ): string
==============================================
Compresses an IPv6 address
RFC 4291 allows you to compress consecutive zero pieces in an address to ‘::’. This method expects a valid IPv6 address and compresses consecutive zero pieces to ‘::’.
Example: FF01:0:0:0:0:0:0:101 -> FF01::101 0:0:0:0:0:0:0:1 -> ::1
* [uncompress()](../../functions/uncompress)
`$ip` string Required An IPv6 address string The compressed IPv6 address
File: `wp-includes/Requests/IPv6.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/ipv6.php/)
```
public static function compress($ip) {
// Prepare the IP to be compressed
$ip = self::uncompress($ip);
$ip_parts = self::split_v6_v4($ip);
// Replace all leading zeros
$ip_parts[0] = preg_replace('/(^|:)0+([0-9])/', '\1\2', $ip_parts[0]);
// Find bunches of zeros
if (preg_match_all('/(?:^|:)(?:0(?::|$))+/', $ip_parts[0], $matches, PREG_OFFSET_CAPTURE)) {
$max = 0;
$pos = null;
foreach ($matches[0] as $match) {
if (strlen($match[0]) > $max) {
$max = strlen($match[0]);
$pos = $match[1];
}
}
$ip_parts[0] = substr_replace($ip_parts[0], '::', $pos, $max);
}
if ($ip_parts[1] !== '') {
return implode(':', $ip_parts);
}
else {
return $ip_parts[0];
}
}
```
| Uses | Description |
| --- | --- |
| [Requests\_IPv6::split\_v6\_v4()](split_v6_v4) wp-includes/Requests/IPv6.php | Splits an IPv6 address into the IPv6 and IPv4 representation parts |
| [Requests\_IPv6::uncompress()](uncompress) wp-includes/Requests/IPv6.php | Uncompresses an IPv6 address |
| Used By | Description |
| --- | --- |
| [Requests\_IRI::set\_host()](../requests_iri/set_host) wp-includes/Requests/IRI.php | Set the ihost. Returns true on success, false on failure (if there are any invalid characters). |
wordpress Requests_IPv6::split_v6_v4( string $ip ): string[] Requests\_IPv6::split\_v6\_v4( string $ip ): string[]
=====================================================
Splits an IPv6 address into the IPv6 and IPv4 representation parts
RFC 4291 allows you to represent the last two parts of an IPv6 address using the standard IPv4 representation
Example: 0:0:0:0:0:0:13.1.68.3 0:0:0:0:0:FFFF:129.144.52.38
`$ip` string Required An IPv6 address string[] [0] contains the IPv6 represented part, and [1] the IPv4 represented part
File: `wp-includes/Requests/IPv6.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/ipv6.php/)
```
protected static function split_v6_v4($ip) {
if (strpos($ip, '.') !== false) {
$pos = strrpos($ip, ':');
$ipv6_part = substr($ip, 0, $pos);
$ipv4_part = substr($ip, $pos + 1);
return array($ipv6_part, $ipv4_part);
}
else {
return array($ip, '');
}
}
```
| Used By | Description |
| --- | --- |
| [Requests\_IPv6::check\_ipv6()](check_ipv6) wp-includes/Requests/IPv6.php | Checks an IPv6 address |
| [Requests\_IPv6::compress()](compress) wp-includes/Requests/IPv6.php | Compresses an IPv6 address |
wordpress Requests_Session::post( $url, $headers = array(), $data = array(), $options = array() ) Requests\_Session::post( $url, $headers = array(), $data = array(), $options = array() )
========================================================================================
Send a POST request
File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
public function post($url, $headers = array(), $data = array(), $options = array()) {
return $this->request($url, $headers, $data, Requests::POST, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Session::request()](request) wp-includes/Requests/Session.php | Main interface for HTTP requests |
wordpress Requests_Session::patch( $url, $headers, $data = array(), $options = array() ) Requests\_Session::patch( $url, $headers, $data = array(), $options = array() )
===============================================================================
Send a PATCH request
Note: Unlike [post](../../functions/post) and [put](../../functions/put), `$headers` is required, as the specification recommends that should send an ETag
File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
public function patch($url, $headers, $data = array(), $options = array()) {
return $this->request($url, $headers, $data, Requests::PATCH, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Session::request()](request) wp-includes/Requests/Session.php | Main interface for HTTP requests |
wordpress Requests_Session::__unset( string $key ) Requests\_Session::\_\_unset( string $key )
===========================================
Remove a property’s value
`$key` string Required Property key File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
public function __unset($key) {
if (isset($this->options[$key])) {
unset($this->options[$key]);
}
}
```
wordpress Requests_Session::request_multiple( array $requests, array $options = array() ): array Requests\_Session::request\_multiple( array $requests, array $options = array() ): array
========================================================================================
Send multiple HTTP requests simultaneously
* [Requests::request\_multiple()](../requests/request_multiple)
`$requests` array Required Requests data (see [Requests::request\_multiple()](../requests/request_multiple) ) More Arguments from Requests::request\_multiple( ... $requests ) Requests data (see description for more information) `$options` array Optional Global and default options (see [Requests::request()](../requests/request) ) More Arguments from Requests::request( ... $options ) Options for the request (see description for more information) Default: `array()`
array Responses (either [Requests\_Response](../requests_response) or a [Requests\_Exception](../requests_exception) object)
File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
public function request_multiple($requests, $options = array()) {
foreach ($requests as $key => $request) {
$requests[$key] = $this->merge_request($request, false);
}
$options = array_merge($this->options, $options);
// Disallow forcing the type, as that's a per request setting
unset($options['type']);
return Requests::request_multiple($requests, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests::request\_multiple()](../requests/request_multiple) wp-includes/class-requests.php | Send multiple HTTP requests simultaneously |
| [Requests\_Session::merge\_request()](merge_request) wp-includes/Requests/Session.php | Merge a request’s data with the default data |
wordpress Requests_Session::merge_request( array $request, boolean $merge_options = true ): array Requests\_Session::merge\_request( array $request, boolean $merge\_options = true ): array
==========================================================================================
Merge a request’s data with the default data
`$request` array Required Request data (same form as [request\_multiple](../../functions/request_multiple)) `$merge_options` boolean Optional Should we merge options as well? Default: `true`
array Request data
File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
protected function merge_request($request, $merge_options = true) {
if ($this->url !== null) {
$request['url'] = Requests_IRI::absolutize($this->url, $request['url']);
$request['url'] = $request['url']->uri;
}
if (empty($request['headers'])) {
$request['headers'] = array();
}
$request['headers'] = array_merge($this->headers, $request['headers']);
if (empty($request['data'])) {
if (is_array($this->data)) {
$request['data'] = $this->data;
}
}
elseif (is_array($request['data']) && is_array($this->data)) {
$request['data'] = array_merge($this->data, $request['data']);
}
if ($merge_options !== false) {
$request['options'] = array_merge($this->options, $request['options']);
// Disallow forcing the type, as that's a per request setting
unset($request['options']['type']);
}
return $request;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_IRI::absolutize()](../requests_iri/absolutize) wp-includes/Requests/IRI.php | Create a new IRI object by resolving a relative IRI |
| Used By | Description |
| --- | --- |
| [Requests\_Session::request()](request) wp-includes/Requests/Session.php | Main interface for HTTP requests |
| [Requests\_Session::request\_multiple()](request_multiple) wp-includes/Requests/Session.php | Send multiple HTTP requests simultaneously |
wordpress Requests_Session::__set( string $key, mixed $value ) Requests\_Session::\_\_set( string $key, mixed $value )
=======================================================
Set a property’s value
`$key` string Required Property key `$value` mixed Required Property value File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
public function __set($key, $value) {
$this->options[$key] = $value;
}
```
wordpress Requests_Session::__get( string $key ): mixed|null Requests\_Session::\_\_get( string $key ): mixed|null
=====================================================
Get a property’s value
`$key` string Required Property key mixed|null Property value, null if none found
File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
public function __get($key) {
if (isset($this->options[$key])) {
return $this->options[$key];
}
return null;
}
```
wordpress Requests_Session::__isset( string $key ) Requests\_Session::\_\_isset( string $key )
===========================================
Remove a property’s value
`$key` string Required Property key File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
public function __isset($key) {
return isset($this->options[$key]);
}
```
wordpress Requests_Session::head( $url, $headers = array(), $options = array() ) Requests\_Session::head( $url, $headers = array(), $options = array() )
=======================================================================
Send a HEAD request
File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
public function head($url, $headers = array(), $options = array()) {
return $this->request($url, $headers, null, Requests::HEAD, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Session::request()](request) wp-includes/Requests/Session.php | Main interface for HTTP requests |
wordpress Requests_Session::put( $url, $headers = array(), $data = array(), $options = array() ) Requests\_Session::put( $url, $headers = array(), $data = array(), $options = array() )
=======================================================================================
Send a PUT request
File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
public function put($url, $headers = array(), $data = array(), $options = array()) {
return $this->request($url, $headers, $data, Requests::PUT, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Session::request()](request) wp-includes/Requests/Session.php | Main interface for HTTP requests |
wordpress Requests_Session::__construct( string|null $url = null, array $headers = array(), array $data = array(), array $options = array() ) Requests\_Session::\_\_construct( string|null $url = null, array $headers = array(), array $data = array(), array $options = array() )
======================================================================================================================================
Create a new session
`$url` string|null Optional Base URL for requests Default: `null`
`$headers` array Optional Default headers for requests Default: `array()`
`$data` array Optional Default data for requests Default: `array()`
`$options` array Optional Default options for requests Default: `array()`
File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
public function __construct($url = null, $headers = array(), $data = array(), $options = array()) {
$this->url = $url;
$this->headers = $headers;
$this->data = $data;
$this->options = $options;
if (empty($this->options['cookies'])) {
$this->options['cookies'] = new Requests_Cookie_Jar();
}
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Cookie\_Jar::\_\_construct()](../requests_cookie_jar/__construct) wp-includes/Requests/Cookie/Jar.php | Create a new jar |
| programming_docs |
wordpress Requests_Session::delete( $url, $headers = array(), $options = array() ) Requests\_Session::delete( $url, $headers = array(), $options = array() )
=========================================================================
Send a DELETE request
File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
public function delete($url, $headers = array(), $options = array()) {
return $this->request($url, $headers, null, Requests::DELETE, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Session::request()](request) wp-includes/Requests/Session.php | Main interface for HTTP requests |
wordpress Requests_Session::get( $url, $headers = array(), $options = array() ) Requests\_Session::get( $url, $headers = array(), $options = array() )
======================================================================
Send a GET request
File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
public function get($url, $headers = array(), $options = array()) {
return $this->request($url, $headers, null, Requests::GET, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Session::request()](request) wp-includes/Requests/Session.php | Main interface for HTTP requests |
wordpress Requests_Session::request( string $url, array $headers = array(), array|null $data = array(), string $type = Requests::GET, array $options = array() ): Requests_Response Requests\_Session::request( string $url, array $headers = array(), array|null $data = array(), string $type = Requests::GET, array $options = array() ): Requests\_Response
===========================================================================================================================================================================
Main interface for HTTP requests
This method initiates a request and sends it via a transport before parsing.
* [Requests::request()](../requests/request)
`$url` string Required URL to request `$headers` array Optional Extra headers to send with the request Default: `array()`
`$data` array|null Optional Data to send either as a query string for GET/HEAD requests, or in the body for POST requests Default: `array()`
`$type` string Optional HTTP request type (use Requests constants) Default: `Requests::GET`
`$options` array Optional Options for the request (see [Requests::request()](../requests/request) ) More Arguments from Requests::request( ... $options ) Options for the request (see description for more information) Default: `array()`
[Requests\_Response](../requests_response)
File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/)
```
public function request($url, $headers = array(), $data = array(), $type = Requests::GET, $options = array()) {
$request = $this->merge_request(compact('url', 'headers', 'data', 'options'));
return Requests::request($request['url'], $request['headers'], $request['data'], $type, $request['options']);
}
```
| Uses | Description |
| --- | --- |
| [Requests::request()](../requests/request) wp-includes/class-requests.php | Main interface for HTTP requests |
| [Requests\_Session::merge\_request()](merge_request) wp-includes/Requests/Session.php | Merge a request’s data with the default data |
| Used By | Description |
| --- | --- |
| [Requests\_Session::head()](head) wp-includes/Requests/Session.php | Send a HEAD request |
| [Requests\_Session::delete()](delete) wp-includes/Requests/Session.php | Send a DELETE request |
| [Requests\_Session::post()](post) wp-includes/Requests/Session.php | Send a POST request |
| [Requests\_Session::put()](put) wp-includes/Requests/Session.php | Send a PUT request |
| [Requests\_Session::patch()](patch) wp-includes/Requests/Session.php | Send a PATCH request |
| [Requests\_Session::get()](get) wp-includes/Requests/Session.php | Send a GET request |
wordpress WP_Site_Health::get_test_php_default_timezone(): array WP\_Site\_Health::get\_test\_php\_default\_timezone(): array
============================================================
Tests if the PHP default timezone is set to UTC.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_php_default_timezone() {
$result = array(
'label' => __( 'PHP default timezone is valid' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'PHP default timezone was configured by WordPress on loading. This is necessary for correct calculations of dates and times.' )
),
'actions' => '',
'test' => 'php_default_timezone',
);
if ( 'UTC' !== date_default_timezone_get() ) {
$result['status'] = 'critical';
$result['label'] = __( 'PHP default timezone is invalid' );
$result['description'] = sprintf(
'<p>%s</p>',
sprintf(
/* translators: %s: date_default_timezone_set() */
__( 'PHP default timezone was changed after WordPress loading by a %s function call. This interferes with correct calculations of dates and times.' ),
'<code>date_default_timezone_set()</code>'
)
);
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.3.1](https://developer.wordpress.org/reference/since/5.3.1/) | Introduced. |
wordpress WP_Site_Health::get_cron_tasks() WP\_Site\_Health::get\_cron\_tasks()
====================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Populates the list of cron events and store them to a class-wide variable.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
private function get_cron_tasks() {
$cron_tasks = _get_cron_array();
if ( empty( $cron_tasks ) ) {
$this->crons = new WP_Error( 'no_tasks', __( 'No scheduled events exist on this site.' ) );
return;
}
$this->crons = array();
foreach ( $cron_tasks as $time => $cron ) {
foreach ( $cron as $hook => $dings ) {
foreach ( $dings as $sig => $data ) {
$this->crons[ "$hook-$sig-$time" ] = (object) array(
'hook' => $hook,
'time' => $time,
'sig' => $sig,
'args' => $data['args'],
'schedule' => $data['schedule'],
'interval' => isset( $data['interval'] ) ? $data['interval'] : null,
);
}
}
}
}
```
| Uses | Description |
| --- | --- |
| [\_get\_cron\_array()](../../functions/_get_cron_array) wp-includes/cron.php | Retrieve cron info array option. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::wp\_schedule\_test\_init()](wp_schedule_test_init) wp-admin/includes/class-wp-site-health.php | Initiates the WP\_Cron schedule test cases. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::get_test_dotorg_communication(): array WP\_Site\_Health::get\_test\_dotorg\_communication(): array
===========================================================
Tests if the site can communicate with WordPress.org.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_dotorg_communication() {
$result = array(
'label' => __( 'Can communicate with WordPress.org' ),
'status' => '',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'Communicating with the WordPress servers is used to check for new versions, and to both install and update WordPress core, themes or plugins.' )
),
'actions' => '',
'test' => 'dotorg_communication',
);
$wp_dotorg = wp_remote_get(
'https://api.wordpress.org',
array(
'timeout' => 10,
)
);
if ( ! is_wp_error( $wp_dotorg ) ) {
$result['status'] = 'good';
} else {
$result['status'] = 'critical';
$result['label'] = __( 'Could not reach WordPress.org' );
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
'<span class="error"><span class="screen-reader-text">%s</span></span> %s',
__( 'Error' ),
sprintf(
/* translators: 1: The IP address WordPress.org resolves to. 2: The error returned by the lookup. */
__( 'Your site is unable to reach WordPress.org at %1$s, and returned the error: %2$s' ),
gethostbyname( 'api.wordpress.org' ),
$wp_dotorg->get_error_message()
)
)
);
$result['actions'] = sprintf(
'<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
/* translators: Localized Support reference. */
esc_url( __( 'https://wordpress.org/support' ) ),
__( 'Get help resolving this issue.' ),
/* translators: Accessibility text. */
__( '(opens in a new tab)' )
);
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [wp\_remote\_get()](../../functions/wp_remote_get) wp-includes/http.php | Performs an HTTP request using the GET method and returns its response. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::get_test_loopback_requests(): array WP\_Site\_Health::get\_test\_loopback\_requests(): array
========================================================
Tests if loopbacks work as expected.
A loopback is when WordPress queries itself, for example to start a new WP\_Cron instance, or when editing a plugin or theme. This has shown itself to be a recurring issue, as code can very easily break this interaction.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_loopback_requests() {
$result = array(
'label' => __( 'Your site can perform loopback requests' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'Loopback requests are used to run scheduled events, and are also used by the built-in editors for themes and plugins to verify code stability.' )
),
'actions' => '',
'test' => 'loopback_requests',
);
$check_loopback = $this->can_perform_loopback();
$result['status'] = $check_loopback->status;
if ( 'good' !== $result['status'] ) {
$result['label'] = __( 'Your site could not complete a loopback request' );
$result['description'] .= sprintf(
'<p>%s</p>',
$check_loopback->message
);
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::can\_perform\_loopback()](can_perform_loopback) wp-admin/includes/class-wp-site-health.php | Runs a loopback test on the site. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::get_test_theme_version(): array WP\_Site\_Health::get\_test\_theme\_version(): array
====================================================
Tests if themes are outdated, or unnecessary.
Checks if your site has a default theme (to fall back on if there is a need), if your themes are up to date and, finally, encourages you to remove any themes that are not needed.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_theme_version() {
$result = array(
'label' => __( 'Your themes are all up to date' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'Themes add your site’s look and feel. It’s important to keep them up to date, to stay consistent with your brand and keep your site secure.' )
),
'actions' => sprintf(
'<p><a href="%s">%s</a></p>',
esc_url( admin_url( 'themes.php' ) ),
__( 'Manage your themes' )
),
'test' => 'theme_version',
);
$theme_updates = get_theme_updates();
$themes_total = 0;
$themes_need_updates = 0;
$themes_inactive = 0;
// This value is changed during processing to determine how many themes are considered a reasonable amount.
$allowed_theme_count = 1;
$has_default_theme = false;
$has_unused_themes = false;
$show_unused_themes = true;
$using_default_theme = false;
// Populate a list of all themes available in the install.
$all_themes = wp_get_themes();
$active_theme = wp_get_theme();
// If WP_DEFAULT_THEME doesn't exist, fall back to the latest core default theme.
$default_theme = wp_get_theme( WP_DEFAULT_THEME );
if ( ! $default_theme->exists() ) {
$default_theme = WP_Theme::get_core_default_theme();
}
if ( $default_theme ) {
$has_default_theme = true;
if (
$active_theme->get_stylesheet() === $default_theme->get_stylesheet()
||
is_child_theme() && $active_theme->get_template() === $default_theme->get_template()
) {
$using_default_theme = true;
}
}
foreach ( $all_themes as $theme_slug => $theme ) {
$themes_total++;
if ( array_key_exists( $theme_slug, $theme_updates ) ) {
$themes_need_updates++;
}
}
// If this is a child theme, increase the allowed theme count by one, to account for the parent.
if ( is_child_theme() ) {
$allowed_theme_count++;
}
// If there's a default theme installed and not in use, we count that as allowed as well.
if ( $has_default_theme && ! $using_default_theme ) {
$allowed_theme_count++;
}
if ( $themes_total > $allowed_theme_count ) {
$has_unused_themes = true;
$themes_inactive = ( $themes_total - $allowed_theme_count );
}
// Check if any themes need to be updated.
if ( $themes_need_updates > 0 ) {
$result['status'] = 'critical';
$result['label'] = __( 'You have themes waiting to be updated' );
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: %d: The number of outdated themes. */
_n(
'Your site has %d theme waiting to be updated.',
'Your site has %d themes waiting to be updated.',
$themes_need_updates
),
$themes_need_updates
)
);
} else {
// Give positive feedback about the site being good about keeping things up to date.
if ( 1 === $themes_total ) {
$result['description'] .= sprintf(
'<p>%s</p>',
__( 'Your site has 1 installed theme, and it is up to date.' )
);
} elseif ( $themes_total > 0 ) {
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: %d: The number of themes. */
_n(
'Your site has %d installed theme, and it is up to date.',
'Your site has %d installed themes, and they are all up to date.',
$themes_total
),
$themes_total
)
);
} else {
$result['description'] .= sprintf(
'<p>%s</p>',
__( 'Your site does not have any installed themes.' )
);
}
}
if ( $has_unused_themes && $show_unused_themes && ! is_multisite() ) {
// This is a child theme, so we want to be a bit more explicit in our messages.
if ( $active_theme->parent() ) {
// Recommend removing inactive themes, except a default theme, your current one, and the parent theme.
$result['status'] = 'recommended';
$result['label'] = __( 'You should remove inactive themes' );
if ( $using_default_theme ) {
$result['description'] .= sprintf(
'<p>%s %s</p>',
sprintf(
/* translators: %d: The number of inactive themes. */
_n(
'Your site has %d inactive theme.',
'Your site has %d inactive themes.',
$themes_inactive
),
$themes_inactive
),
sprintf(
/* translators: 1: The currently active theme. 2: The active theme's parent theme. */
__( 'To enhance your site’s security, you should consider removing any themes you are not using. You should keep your active theme, %1$s, and %2$s, its parent theme.' ),
$active_theme->name,
$active_theme->parent()->name
)
);
} else {
$result['description'] .= sprintf(
'<p>%s %s</p>',
sprintf(
/* translators: %d: The number of inactive themes. */
_n(
'Your site has %d inactive theme.',
'Your site has %d inactive themes.',
$themes_inactive
),
$themes_inactive
),
sprintf(
/* translators: 1: The default theme for WordPress. 2: The currently active theme. 3: The active theme's parent theme. */
__( 'To enhance your site’s security, you should consider removing any themes you are not using. You should keep %1$s, the default WordPress theme, %2$s, your active theme, and %3$s, its parent theme.' ),
$default_theme ? $default_theme->name : WP_DEFAULT_THEME,
$active_theme->name,
$active_theme->parent()->name
)
);
}
} else {
// Recommend removing all inactive themes.
$result['status'] = 'recommended';
$result['label'] = __( 'You should remove inactive themes' );
if ( $using_default_theme ) {
$result['description'] .= sprintf(
'<p>%s %s</p>',
sprintf(
/* translators: 1: The amount of inactive themes. 2: The currently active theme. */
_n(
'Your site has %1$d inactive theme, other than %2$s, your active theme.',
'Your site has %1$d inactive themes, other than %2$s, your active theme.',
$themes_inactive
),
$themes_inactive,
$active_theme->name
),
__( 'You should consider removing any unused themes to enhance your site’s security.' )
);
} else {
$result['description'] .= sprintf(
'<p>%s %s</p>',
sprintf(
/* translators: 1: The amount of inactive themes. 2: The default theme for WordPress. 3: The currently active theme. */
_n(
'Your site has %1$d inactive theme, other than %2$s, the default WordPress theme, and %3$s, your active theme.',
'Your site has %1$d inactive themes, other than %2$s, the default WordPress theme, and %3$s, your active theme.',
$themes_inactive
),
$themes_inactive,
$default_theme ? $default_theme->name : WP_DEFAULT_THEME,
$active_theme->name
),
__( 'You should consider removing any unused themes to enhance your site’s security.' )
);
}
}
}
// If no default Twenty* theme exists.
if ( ! $has_default_theme ) {
$result['status'] = 'recommended';
$result['label'] = __( 'Have a default theme available' );
$result['description'] .= sprintf(
'<p>%s</p>',
__( 'Your site does not have any default theme. Default themes are used by WordPress automatically if anything is wrong with your chosen theme.' )
);
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::get\_core\_default\_theme()](../wp_theme/get_core_default_theme) wp-includes/class-wp-theme.php | Determines the latest WordPress default theme that is installed. |
| [get\_theme\_updates()](../../functions/get_theme_updates) wp-admin/includes/update.php | Retrieves themes with updates available. |
| [wp\_get\_themes()](../../functions/wp_get_themes) wp-includes/theme.php | Returns an array of [WP\_Theme](../wp_theme) objects based on the arguments. |
| [is\_child\_theme()](../../functions/is_child_theme) wp-includes/theme.php | Whether a child theme is in use. |
| [\_n()](../../functions/_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Site_Health::wp_cron_scheduled_check() WP\_Site\_Health::wp\_cron\_scheduled\_check()
==============================================
Runs the scheduled event to check and update the latest site health status for the website.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function wp_cron_scheduled_check() {
// Bootstrap wp-admin, as WP_Cron doesn't do this for us.
require_once trailingslashit( ABSPATH ) . 'wp-admin/includes/admin.php';
$tests = WP_Site_Health::get_tests();
$results = array();
$site_status = array(
'good' => 0,
'recommended' => 0,
'critical' => 0,
);
// Don't run https test on development environments.
if ( $this->is_development_environment() ) {
unset( $tests['async']['https_status'] );
}
foreach ( $tests['direct'] as $test ) {
if ( ! empty( $test['skip_cron'] ) ) {
continue;
}
if ( is_string( $test['test'] ) ) {
$test_function = sprintf(
'get_test_%s',
$test['test']
);
if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) {
$results[] = $this->perform_test( array( $this, $test_function ) );
continue;
}
}
if ( is_callable( $test['test'] ) ) {
$results[] = $this->perform_test( $test['test'] );
}
}
foreach ( $tests['async'] as $test ) {
if ( ! empty( $test['skip_cron'] ) ) {
continue;
}
// Local endpoints may require authentication, so asynchronous tests can pass a direct test runner as well.
if ( ! empty( $test['async_direct_test'] ) && is_callable( $test['async_direct_test'] ) ) {
// This test is callable, do so and continue to the next asynchronous check.
$results[] = $this->perform_test( $test['async_direct_test'] );
continue;
}
if ( is_string( $test['test'] ) ) {
// Check if this test has a REST API endpoint.
if ( isset( $test['has_rest'] ) && $test['has_rest'] ) {
$result_fetch = wp_remote_get(
$test['test'],
array(
'body' => array(
'_wpnonce' => wp_create_nonce( 'wp_rest' ),
),
)
);
} else {
$result_fetch = wp_remote_post(
admin_url( 'admin-ajax.php' ),
array(
'body' => array(
'action' => $test['test'],
'_wpnonce' => wp_create_nonce( 'health-check-site-status' ),
),
)
);
}
if ( ! is_wp_error( $result_fetch ) && 200 === wp_remote_retrieve_response_code( $result_fetch ) ) {
$result = json_decode( wp_remote_retrieve_body( $result_fetch ), true );
} else {
$result = false;
}
if ( is_array( $result ) ) {
$results[] = $result;
} else {
$results[] = array(
'status' => 'recommended',
'label' => __( 'A test is unavailable' ),
);
}
}
}
foreach ( $results as $result ) {
if ( 'critical' === $result['status'] ) {
$site_status['critical']++;
} elseif ( 'recommended' === $result['status'] ) {
$site_status['recommended']++;
} else {
$site_status['good']++;
}
}
set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::is\_development\_environment()](is_development_environment) wp-admin/includes/class-wp-site-health.php | Checks if the current environment type is set to ‘development’ or ‘local’. |
| [WP\_Site\_Health::perform\_test()](perform_test) wp-admin/includes/class-wp-site-health.php | Runs a Site Health test directly. |
| [WP\_Site\_Health::get\_tests()](get_tests) wp-admin/includes/class-wp-site-health.php | Returns a set of tests that belong to the site status page. |
| [wp\_create\_nonce()](../../functions/wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| [wp\_remote\_get()](../../functions/wp_remote_get) wp-includes/http.php | Performs an HTTP request using the GET method and returns its response. |
| [wp\_remote\_post()](../../functions/wp_remote_post) wp-includes/http.php | Performs an HTTP request using the POST method and returns its response. |
| [wp\_remote\_retrieve\_response\_code()](../../functions/wp_remote_retrieve_response_code) wp-includes/http.php | Retrieve only the response code from the raw response. |
| [wp\_remote\_retrieve\_body()](../../functions/wp_remote_retrieve_body) wp-includes/http.php | Retrieve only the body from the raw response. |
| [set\_transient()](../../functions/set_transient) wp-includes/option.php | Sets/updates the value of a transient. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | Introduced. |
wordpress WP_Site_Health::get_test_http_requests(): array WP\_Site\_Health::get\_test\_http\_requests(): array
====================================================
Tests if HTTP requests are blocked.
It’s possible to block all outgoing communication (with the possibility of allowing certain hosts) via the HTTP API. This may create problems for users as many features are running as services these days.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_http_requests() {
$result = array(
'label' => __( 'HTTP requests seem to be working as expected' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'It is possible for site maintainers to block all, or some, communication to other sites and services. If set up incorrectly, this may prevent plugins and themes from working as intended.' )
),
'actions' => '',
'test' => 'http_requests',
);
$blocked = false;
$hosts = array();
if ( defined( 'WP_HTTP_BLOCK_EXTERNAL' ) && WP_HTTP_BLOCK_EXTERNAL ) {
$blocked = true;
}
if ( defined( 'WP_ACCESSIBLE_HOSTS' ) ) {
$hosts = explode( ',', WP_ACCESSIBLE_HOSTS );
}
if ( $blocked && 0 === count( $hosts ) ) {
$result['status'] = 'critical';
$result['label'] = __( 'HTTP requests are blocked' );
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: %s: Name of the constant used. */
__( 'HTTP requests have been blocked by the %s constant, with no allowed hosts.' ),
'<code>WP_HTTP_BLOCK_EXTERNAL</code>'
)
);
}
if ( $blocked && 0 < count( $hosts ) ) {
$result['status'] = 'recommended';
$result['label'] = __( 'HTTP requests are partially blocked' );
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: Name of the constant used. 2: List of allowed hostnames. */
__( 'HTTP requests have been blocked by the %1$s constant, with some allowed hosts: %2$s.' ),
'<code>WP_HTTP_BLOCK_EXTERNAL</code>',
implode( ',', $hosts )
)
);
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::get_test_rest_availability(): array WP\_Site\_Health::get\_test\_rest\_availability(): array
========================================================
Tests if the REST API is accessible.
Various security measures may block the REST API from working, or it may have been disabled in general.
This is required for the new block editor to work, so we explicitly test for this.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_rest_availability() {
$result = array(
'label' => __( 'The REST API is available' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'The REST API is one way that WordPress and other applications communicate with the server. For example, the block editor screen relies on the REST API to display and save your posts and pages.' )
),
'actions' => '',
'test' => 'rest_availability',
);
$cookies = wp_unslash( $_COOKIE );
$timeout = 10; // 10 seconds.
$headers = array(
'Cache-Control' => 'no-cache',
'X-WP-Nonce' => wp_create_nonce( 'wp_rest' ),
);
/** This filter is documented in wp-includes/class-wp-http-streams.php */
$sslverify = apply_filters( 'https_local_ssl_verify', false );
// Include Basic auth in loopback requests.
if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
$headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
}
$url = rest_url( 'wp/v2/types/post' );
// The context for this is editing with the new block editor.
$url = add_query_arg(
array(
'context' => 'edit',
),
$url
);
$r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
if ( is_wp_error( $r ) ) {
$result['status'] = 'critical';
$result['label'] = __( 'The REST API encountered an error' );
$result['description'] .= sprintf(
'<p>%s</p><p>%s<br>%s</p>',
__( 'When testing the REST API, an error was encountered:' ),
sprintf(
// translators: %s: The REST API URL.
__( 'REST API Endpoint: %s' ),
$url
),
sprintf(
// translators: 1: The WordPress error code. 2: The WordPress error message.
__( 'REST API Response: (%1$s) %2$s' ),
$r->get_error_code(),
$r->get_error_message()
)
);
} elseif ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
$result['status'] = 'recommended';
$result['label'] = __( 'The REST API encountered an unexpected result' );
$result['description'] .= sprintf(
'<p>%s</p><p>%s<br>%s</p>',
__( 'When testing the REST API, an unexpected result was returned:' ),
sprintf(
// translators: %s: The REST API URL.
__( 'REST API Endpoint: %s' ),
$url
),
sprintf(
// translators: 1: The WordPress error code. 2: The HTTP status code error message.
__( 'REST API Response: (%1$s) %2$s' ),
wp_remote_retrieve_response_code( $r ),
wp_remote_retrieve_response_message( $r )
)
);
} else {
$json = json_decode( wp_remote_retrieve_body( $r ), true );
if ( false !== $json && ! isset( $json['capabilities'] ) ) {
$result['status'] = 'recommended';
$result['label'] = __( 'The REST API did not behave correctly' );
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: %s: The name of the query parameter being tested. */
__( 'The REST API did not process the %s query parameter correctly.' ),
'<code>context</code>'
)
);
}
}
return $result;
}
```
[apply\_filters( 'https\_local\_ssl\_verify', bool $ssl\_verify, string $url )](../../hooks/https_local_ssl_verify)
Filters whether SSL should be verified for local HTTP API requests.
| Uses | Description |
| --- | --- |
| [wp\_create\_nonce()](../../functions/wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| [wp\_remote\_get()](../../functions/wp_remote_get) wp-includes/http.php | Performs an HTTP request using the GET method and returns its response. |
| [wp\_remote\_retrieve\_response\_code()](../../functions/wp_remote_retrieve_response_code) wp-includes/http.php | Retrieve only the response code from the raw response. |
| [wp\_remote\_retrieve\_response\_message()](../../functions/wp_remote_retrieve_response_message) wp-includes/http.php | Retrieve only the response message from the raw response. |
| [wp\_remote\_retrieve\_body()](../../functions/wp_remote_retrieve_body) wp-includes/http.php | Retrieve only the body from the raw response. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::get_test_php_version(): array WP\_Site\_Health::get\_test\_php\_version(): array
==================================================
Tests if the supplied PHP version is supported.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_php_version() {
$response = wp_check_php_version();
$result = array(
'label' => sprintf(
/* translators: %s: The current PHP version. */
__( 'Your site is running the current version of PHP (%s)' ),
PHP_VERSION
),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
sprintf(
/* translators: %s: The minimum recommended PHP version. */
__( 'PHP is one of the programming languages used to build WordPress. Newer versions of PHP receive regular security updates and may increase your site’s performance. The minimum recommended version of PHP is %s.' ),
$response ? $response['recommended_version'] : ''
)
),
'actions' => sprintf(
'<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
esc_url( wp_get_update_php_url() ),
__( 'Learn more about updating PHP' ),
/* translators: Accessibility text. */
__( '(opens in a new tab)' )
),
'test' => 'php_version',
);
// PHP is up to date.
if ( ! $response || version_compare( PHP_VERSION, $response['recommended_version'], '>=' ) ) {
return $result;
}
// The PHP version is older than the recommended version, but still receiving active support.
if ( $response['is_supported'] ) {
$result['label'] = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an older version of PHP (%s)' ),
PHP_VERSION
);
$result['status'] = 'recommended';
return $result;
}
// The PHP version is still receiving security fixes, but is lower than
// the expected minimum version that will be required by WordPress in the near future.
if ( $response['is_secure'] && $response['is_lower_than_future_minimum'] ) {
// The `is_secure` array key name doesn't actually imply this is a secure version of PHP. It only means it receives security updates.
$result['label'] = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an outdated version of PHP (%s), which soon will not be supported by WordPress.' ),
PHP_VERSION
);
$result['status'] = 'critical';
$result['badge']['label'] = __( 'Requirements' );
return $result;
}
// The PHP version is only receiving security fixes.
if ( $response['is_secure'] ) {
$result['label'] = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an older version of PHP (%s), which should be updated' ),
PHP_VERSION
);
$result['status'] = 'recommended';
return $result;
}
// No more security updates for the PHP version, and lower than the expected minimum version required by WordPress.
if ( $response['is_lower_than_future_minimum'] ) {
$message = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates and soon will not be supported by WordPress.' ),
PHP_VERSION
);
} else {
// No more security updates for the PHP version, must be updated.
$message = sprintf(
/* translators: %s: The server PHP version. */
__( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates. It should be updated.' ),
PHP_VERSION
);
}
$result['label'] = $message;
$result['status'] = 'critical';
$result['badge']['label'] = __( 'Security' );
return $result;
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_update\_php\_url()](../../functions/wp_get_update_php_url) wp-includes/functions.php | Gets the URL to learn more about updating the PHP version the site is running on. |
| [wp\_check\_php\_version()](../../functions/wp_check_php_version) wp-admin/includes/misc.php | Checks if the user needs to update PHP. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::show_site_health_tab( string $tab ) WP\_Site\_Health::show\_site\_health\_tab( string $tab )
========================================================
Outputs the content of a tab in the Site Health screen.
`$tab` string Required Slug of the current tab being displayed. File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function show_site_health_tab( $tab ) {
if ( 'debug' === $tab ) {
require_once ABSPATH . '/wp-admin/site-health-info.php';
}
}
```
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_Site_Health::get_test_scheduled_events(): array WP\_Site\_Health::get\_test\_scheduled\_events(): array
=======================================================
Tests if scheduled events run as intended.
If scheduled events are not running, this may indicate something with WP\_Cron is not working as intended, or that there are orphaned events hanging around from older code.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_scheduled_events() {
$result = array(
'label' => __( 'Scheduled events are running' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'Scheduled events are what periodically looks for updates to plugins, themes and WordPress itself. It is also what makes sure scheduled posts are published on time. It may also be used by various plugins to make sure that planned actions are executed.' )
),
'actions' => '',
'test' => 'scheduled_events',
);
$this->wp_schedule_test_init();
if ( is_wp_error( $this->has_missed_cron() ) ) {
$result['status'] = 'critical';
$result['label'] = __( 'It was not possible to check your scheduled events' );
$result['description'] = sprintf(
'<p>%s</p>',
sprintf(
/* translators: %s: The error message returned while from the cron scheduler. */
__( 'While trying to test your site’s scheduled events, the following error was returned: %s' ),
$this->has_missed_cron()->get_error_message()
)
);
} elseif ( $this->has_missed_cron() ) {
$result['status'] = 'recommended';
$result['label'] = __( 'A scheduled event has failed' );
$result['description'] = sprintf(
'<p>%s</p>',
sprintf(
/* translators: %s: The name of the failed cron event. */
__( 'The scheduled event, %s, failed to run. Your site still works, but this may indicate that scheduling posts or automated updates may not work as intended.' ),
$this->last_missed_cron
)
);
} elseif ( $this->has_late_cron() ) {
$result['status'] = 'recommended';
$result['label'] = __( 'A scheduled event is late' );
$result['description'] = sprintf(
'<p>%s</p>',
sprintf(
/* translators: %s: The name of the late cron event. */
__( 'The scheduled event, %s, is late to run. Your site still works, but this may indicate that scheduling posts or automated updates may not work as intended.' ),
$this->last_late_cron
)
);
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::has\_late\_cron()](has_late_cron) wp-admin/includes/class-wp-site-health.php | Checks if any scheduled tasks are late. |
| [WP\_Site\_Health::wp\_schedule\_test\_init()](wp_schedule_test_init) wp-admin/includes/class-wp-site-health.php | Initiates the WP\_Cron schedule test cases. |
| [WP\_Site\_Health::has\_missed\_cron()](has_missed_cron) wp-admin/includes/class-wp-site-health.php | Checks if any scheduled tasks have been missed. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Site_Health::get_page_cache_detail(): WP_Error|array WP\_Site\_Health::get\_page\_cache\_detail(): WP\_Error|array
=============================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Gets page cache details.
[WP\_Error](../wp_error)|array Page cache detail or else a [WP\_Error](../wp_error) if unable to determine.
* `status`stringPage cache status. Good, Recommended or Critical.
* `advanced_cache_present`boolWhether page cache plugin is available or not.
* `headers`string[]Client caching response headers detected.
* `response_time`floatResponse time of site.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
private function get_page_cache_detail() {
$page_cache_detail = $this->check_for_page_caching();
if ( is_wp_error( $page_cache_detail ) ) {
return $page_cache_detail;
}
// Use the median server response time.
$response_timings = $page_cache_detail['response_timing'];
rsort( $response_timings );
$page_speed = $response_timings[ floor( count( $response_timings ) / 2 ) ];
// Obtain unique set of all client caching response headers.
$headers = array();
foreach ( $page_cache_detail['page_caching_response_headers'] as $page_caching_response_headers ) {
$headers = array_merge( $headers, array_keys( $page_caching_response_headers ) );
}
$headers = array_unique( $headers );
// Page cache is detected if there are response headers or a page cache plugin is present.
$has_page_caching = ( count( $headers ) > 0 || $page_cache_detail['advanced_cache_present'] );
if ( $page_speed && $page_speed < $this->get_good_response_time_threshold() ) {
$result = $has_page_caching ? 'good' : 'recommended';
} else {
$result = 'critical';
}
return array(
'status' => $result,
'advanced_cache_present' => $page_cache_detail['advanced_cache_present'],
'headers' => $headers,
'response_time' => $page_speed,
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::check\_for\_page\_caching()](check_for_page_caching) wp-admin/includes/class-wp-site-health.php | Checks if site has page cache enabled or not. |
| [WP\_Site\_Health::get\_good\_response\_time\_threshold()](get_good_response_time_threshold) wp-admin/includes/class-wp-site-health.php | Gets the threshold below which a response time is considered good. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_test\_page\_cache()](get_test_page_cache) wp-admin/includes/class-wp-site-health.php | Tests if a full page cache is available. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Site_Health::should_suggest_persistent_object_cache(): bool WP\_Site\_Health::should\_suggest\_persistent\_object\_cache(): bool
====================================================================
Determines whether to suggest using a persistent object cache.
bool Whether to suggest using a persistent object cache.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function should_suggest_persistent_object_cache() {
global $wpdb;
/**
* Filters whether to suggest use of a persistent object cache and bypass default threshold checks.
*
* Using this filter allows to override the default logic, effectively short-circuiting the method.
*
* @since 6.1.0
*
* @param bool|null $suggest Boolean to short-circuit, for whether to suggest using a persistent object cache.
* Default null.
*/
$short_circuit = apply_filters( 'site_status_should_suggest_persistent_object_cache', null );
if ( is_bool( $short_circuit ) ) {
return $short_circuit;
}
if ( is_multisite() ) {
return true;
}
/**
* Filters the thresholds used to determine whether to suggest the use of a persistent object cache.
*
* @since 6.1.0
*
* @param int[] $thresholds The list of threshold numbers keyed by threshold name.
*/
$thresholds = apply_filters(
'site_status_persistent_object_cache_thresholds',
array(
'alloptions_count' => 500,
'alloptions_bytes' => 100000,
'comments_count' => 1000,
'options_count' => 1000,
'posts_count' => 1000,
'terms_count' => 1000,
'users_count' => 1000,
)
);
$alloptions = wp_load_alloptions();
if ( $thresholds['alloptions_count'] < count( $alloptions ) ) {
return true;
}
if ( $thresholds['alloptions_bytes'] < strlen( serialize( $alloptions ) ) ) {
return true;
}
$table_names = implode( "','", array( $wpdb->comments, $wpdb->options, $wpdb->posts, $wpdb->terms, $wpdb->users ) );
// With InnoDB the `TABLE_ROWS` are estimates, which are accurate enough and faster to retrieve than individual `COUNT()` queries.
$results = $wpdb->get_results(
$wpdb->prepare(
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- This query cannot use interpolation.
"SELECT TABLE_NAME AS 'table', TABLE_ROWS AS 'rows', SUM(data_length + index_length) as 'bytes' FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME IN ('$table_names') GROUP BY TABLE_NAME;",
DB_NAME
),
OBJECT_K
);
$threshold_map = array(
'comments_count' => $wpdb->comments,
'options_count' => $wpdb->options,
'posts_count' => $wpdb->posts,
'terms_count' => $wpdb->terms,
'users_count' => $wpdb->users,
);
foreach ( $threshold_map as $threshold => $table ) {
if ( $thresholds[ $threshold ] <= $results[ $table ]->rows ) {
return true;
}
}
return false;
}
```
[apply\_filters( 'site\_status\_persistent\_object\_cache\_thresholds', int[] $thresholds )](../../hooks/site_status_persistent_object_cache_thresholds)
Filters the thresholds used to determine whether to suggest the use of a persistent object cache.
[apply\_filters( 'site\_status\_should\_suggest\_persistent\_object\_cache', bool|null $suggest )](../../hooks/site_status_should_suggest_persistent_object_cache)
Filters whether to suggest use of a persistent object cache and bypass default threshold checks.
| Uses | Description |
| --- | --- |
| [wp\_load\_alloptions()](../../functions/wp_load_alloptions) wp-includes/option.php | Loads and caches all autoloaded options, if available or all options. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [wpdb::get\_results()](../wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_test\_persistent\_object\_cache()](get_test_persistent_object_cache) wp-admin/includes/class-wp-site-health.php | Tests if the site uses persistent object cache and recommends to use it if not. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Site_Health::get_test_ssl_support(): array WP\_Site\_Health::get\_test\_ssl\_support(): array
==================================================
Checks if the HTTP API can handle SSL/TLS requests.
array The test result.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_ssl_support() {
$result = array(
'label' => '',
'status' => '',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'Securely communicating between servers are needed for transactions such as fetching files, conducting sales on store sites, and much more.' )
),
'actions' => '',
'test' => 'ssl_support',
);
$supports_https = wp_http_supports( array( 'ssl' ) );
if ( $supports_https ) {
$result['status'] = 'good';
$result['label'] = __( 'Your site can communicate securely with other services' );
} else {
$result['status'] = 'critical';
$result['label'] = __( 'Your site is unable to communicate securely with other services' );
$result['description'] .= sprintf(
'<p>%s</p>',
__( 'Talk to your web host about OpenSSL support for PHP.' )
);
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [wp\_http\_supports()](../../functions/wp_http_supports) wp-includes/http.php | Determines if there is an HTTP Transport that can process this request. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::get_test_persistent_object_cache(): array WP\_Site\_Health::get\_test\_persistent\_object\_cache(): array
===============================================================
Tests if the site uses persistent object cache and recommends to use it if not.
array The test result.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_persistent_object_cache() {
/**
* Filters the action URL for the persistent object cache health check.
*
* @since 6.1.0
*
* @param string $action_url Learn more link for persistent object cache health check.
*/
$action_url = apply_filters(
'site_status_persistent_object_cache_url',
/* translators: Localized Support reference. */
__( 'https://wordpress.org/support/article/optimization/#persistent-object-cache' )
);
$result = array(
'test' => 'persistent_object_cache',
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'label' => __( 'A persistent object cache is being used' ),
'description' => sprintf(
'<p>%s</p>',
__( 'A persistent object cache makes your site’s database more efficient, resulting in faster load times because WordPress can retrieve your site’s content and settings much more quickly.' )
),
'actions' => sprintf(
'<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
esc_url( $action_url ),
__( 'Learn more about persistent object caching.' ),
/* translators: Accessibility text. */
__( '(opens in a new tab)' )
),
);
if ( wp_using_ext_object_cache() ) {
return $result;
}
if ( ! $this->should_suggest_persistent_object_cache() ) {
$result['label'] = __( 'A persistent object cache is not required' );
return $result;
}
$available_services = $this->available_object_cache_services();
$notes = __( 'Your hosting provider can tell you if a persistent object cache can be enabled on your site.' );
if ( ! empty( $available_services ) ) {
$notes .= ' ' . sprintf(
/* translators: Available object caching services. */
__( 'Your host appears to support the following object caching services: %s.' ),
implode( ', ', $available_services )
);
}
/**
* Filters the second paragraph of the health check's description
* when suggesting the use of a persistent object cache.
*
* Hosts may want to replace the notes to recommend their preferred object caching solution.
*
* Plugin authors may want to append notes (not replace) on why object caching is recommended for their plugin.
*
* @since 6.1.0
*
* @param string $notes The notes appended to the health check description.
* @param string[] $available_services The list of available persistent object cache services.
*/
$notes = apply_filters( 'site_status_persistent_object_cache_notes', $notes, $available_services );
$result['status'] = 'recommended';
$result['label'] = __( 'You should use a persistent object cache' );
$result['description'] .= sprintf(
'<p>%s</p>',
wp_kses(
$notes,
array(
'a' => array( 'href' => true ),
'code' => true,
'em' => true,
'strong' => true,
)
)
);
return $result;
}
```
[apply\_filters( 'site\_status\_persistent\_object\_cache\_notes', string $notes, string[] $available\_services )](../../hooks/site_status_persistent_object_cache_notes)
Filters the second paragraph of the health check’s description when suggesting the use of a persistent object cache.
[apply\_filters( 'site\_status\_persistent\_object\_cache\_url', string $action\_url )](../../hooks/site_status_persistent_object_cache_url)
Filters the action URL for the persistent object cache health check.
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::available\_object\_cache\_services()](available_object_cache_services) wp-admin/includes/class-wp-site-health.php | Returns a list of available persistent object cache services. |
| [WP\_Site\_Health::should\_suggest\_persistent\_object\_cache()](should_suggest_persistent_object_cache) wp-admin/includes/class-wp-site-health.php | Determines whether to suggest using a persistent object cache. |
| [wp\_kses()](../../functions/wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| [wp\_using\_ext\_object\_cache()](../../functions/wp_using_ext_object_cache) wp-includes/load.php | Toggle `$_wp_using_ext_object_cache` on and off without directly touching global. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Site_Health::get_tests(): array WP\_Site\_Health::get\_tests(): array
=====================================
Returns a set of tests that belong to the site status page.
Each site status test is defined here, they may be `direct` tests, that run on page load, or `async` tests which will run later down the line via JavaScript calls to improve page performance and hopefully also user experiences.
array The list of tests to run.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public static function get_tests() {
$tests = array(
'direct' => array(
'wordpress_version' => array(
'label' => __( 'WordPress Version' ),
'test' => 'wordpress_version',
),
'plugin_version' => array(
'label' => __( 'Plugin Versions' ),
'test' => 'plugin_version',
),
'theme_version' => array(
'label' => __( 'Theme Versions' ),
'test' => 'theme_version',
),
'php_version' => array(
'label' => __( 'PHP Version' ),
'test' => 'php_version',
),
'php_extensions' => array(
'label' => __( 'PHP Extensions' ),
'test' => 'php_extensions',
),
'php_default_timezone' => array(
'label' => __( 'PHP Default Timezone' ),
'test' => 'php_default_timezone',
),
'php_sessions' => array(
'label' => __( 'PHP Sessions' ),
'test' => 'php_sessions',
),
'sql_server' => array(
'label' => __( 'Database Server version' ),
'test' => 'sql_server',
),
'utf8mb4_support' => array(
'label' => __( 'MySQL utf8mb4 support' ),
'test' => 'utf8mb4_support',
),
'ssl_support' => array(
'label' => __( 'Secure communication' ),
'test' => 'ssl_support',
),
'scheduled_events' => array(
'label' => __( 'Scheduled events' ),
'test' => 'scheduled_events',
),
'http_requests' => array(
'label' => __( 'HTTP Requests' ),
'test' => 'http_requests',
),
'rest_availability' => array(
'label' => __( 'REST API availability' ),
'test' => 'rest_availability',
'skip_cron' => true,
),
'debug_enabled' => array(
'label' => __( 'Debugging enabled' ),
'test' => 'is_in_debug_mode',
),
'file_uploads' => array(
'label' => __( 'File uploads' ),
'test' => 'file_uploads',
),
'plugin_theme_auto_updates' => array(
'label' => __( 'Plugin and theme auto-updates' ),
'test' => 'plugin_theme_auto_updates',
),
),
'async' => array(
'dotorg_communication' => array(
'label' => __( 'Communication with WordPress.org' ),
'test' => rest_url( 'wp-site-health/v1/tests/dotorg-communication' ),
'has_rest' => true,
'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_dotorg_communication' ),
),
'background_updates' => array(
'label' => __( 'Background updates' ),
'test' => rest_url( 'wp-site-health/v1/tests/background-updates' ),
'has_rest' => true,
'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_background_updates' ),
),
'loopback_requests' => array(
'label' => __( 'Loopback request' ),
'test' => rest_url( 'wp-site-health/v1/tests/loopback-requests' ),
'has_rest' => true,
'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_loopback_requests' ),
),
'https_status' => array(
'label' => __( 'HTTPS status' ),
'test' => rest_url( 'wp-site-health/v1/tests/https-status' ),
'has_rest' => true,
'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_https_status' ),
),
),
);
// Conditionally include Authorization header test if the site isn't protected by Basic Auth.
if ( ! wp_is_site_protected_by_basic_auth() ) {
$tests['async']['authorization_header'] = array(
'label' => __( 'Authorization header' ),
'test' => rest_url( 'wp-site-health/v1/tests/authorization-header' ),
'has_rest' => true,
'headers' => array( 'Authorization' => 'Basic ' . base64_encode( 'user:pwd' ) ),
'skip_cron' => true,
);
}
// Only check for caches in production environments.
if ( 'production' === wp_get_environment_type() ) {
$tests['async']['page_cache'] = array(
'label' => __( 'Page cache' ),
'test' => rest_url( 'wp-site-health/v1/tests/page-cache' ),
'has_rest' => true,
'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_page_cache' ),
);
$tests['direct']['persistent_object_cache'] = array(
'label' => __( 'Persistent object cache' ),
'test' => 'persistent_object_cache',
);
}
/**
* Filters which site status tests are run on a site.
*
* The site health is determined by a set of tests based on best practices from
* both the WordPress Hosting Team and web standards in general.
*
* Some sites may not have the same requirements, for example the automatic update
* checks may be handled by a host, and are therefore disabled in core.
* Or maybe you want to introduce a new test, is caching enabled/disabled/stale for example.
*
* Tests may be added either as direct, or asynchronous ones. Any test that may require some time
* to complete should run asynchronously, to avoid extended loading periods within wp-admin.
*
* @since 5.2.0
* @since 5.6.0 Added the `async_direct_test` array key for asynchronous tests.
* Added the `skip_cron` array key for all tests.
*
* @param array[] $tests {
* An associative array of direct and asynchronous tests.
*
* @type array[] $direct {
* An array of direct tests.
*
* @type array ...$identifier {
* `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to
* prefix test identifiers with their slug to avoid collisions between tests.
*
* @type string $label The friendly label to identify the test.
* @type callable $test The callback function that runs the test and returns its result.
* @type bool $skip_cron Whether to skip this test when running as cron.
* }
* }
* @type array[] $async {
* An array of asynchronous tests.
*
* @type array ...$identifier {
* `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to
* prefix test identifiers with their slug to avoid collisions between tests.
*
* @type string $label The friendly label to identify the test.
* @type string $test An admin-ajax.php action to be called to perform the test, or
* if `$has_rest` is true, a URL to a REST API endpoint to perform
* the test.
* @type bool $has_rest Whether the `$test` property points to a REST API endpoint.
* @type bool $skip_cron Whether to skip this test when running as cron.
* @type callable $async_direct_test A manner of directly calling the test marked as asynchronous,
* as the scheduled event can not authenticate, and endpoints
* may require authentication.
* }
* }
* }
*/
$tests = apply_filters( 'site_status_tests', $tests );
// Ensure that the filtered tests contain the required array keys.
$tests = array_merge(
array(
'direct' => array(),
'async' => array(),
),
$tests
);
return $tests;
}
```
[apply\_filters( 'site\_status\_tests', array[] $tests )](../../hooks/site_status_tests)
Filters which site status tests are run on a site.
| Uses | Description |
| --- | --- |
| [wp\_is\_site\_protected\_by\_basic\_auth()](../../functions/wp_is_site_protected_by_basic_auth) wp-includes/load.php | Checks if this site is protected by HTTP Basic Auth. |
| [wp\_get\_environment\_type()](../../functions/wp_get_environment_type) wp-includes/load.php | Retrieves the current environment type. |
| [WP\_Site\_Health::get\_instance()](get_instance) wp-admin/includes/class-wp-site-health.php | Returns an instance of the [WP\_Site\_Health](../wp_site_health) class, or create one if none exist yet. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::wp\_cron\_scheduled\_check()](wp_cron_scheduled_check) wp-admin/includes/class-wp-site-health.php | Runs the scheduled event to check and update the latest site health status for the website. |
| [WP\_Site\_Health::enqueue\_scripts()](enqueue_scripts) wp-admin/includes/class-wp-site-health.php | Enqueues the site health scripts. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Added support for `has_rest` and `permissions`. |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Site_Health::get_good_response_time_threshold(): int WP\_Site\_Health::get\_good\_response\_time\_threshold(): int
=============================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Gets the threshold below which a response time is considered good.
int Threshold in milliseconds.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
private function get_good_response_time_threshold() {
/**
* Filters the threshold below which a response time is considered good.
*
* The default is based on https://web.dev/time-to-first-byte/.
*
* @param int $threshold Threshold in milliseconds. Default 600.
*
* @since 6.1.0
*/
return (int) apply_filters( 'site_status_good_response_time_threshold', 600 );
}
```
[apply\_filters( 'site\_status\_good\_response\_time\_threshold', int $threshold )](../../hooks/site_status_good_response_time_threshold)
Filters the threshold below which a response time is considered good.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_page\_cache\_detail()](get_page_cache_detail) wp-admin/includes/class-wp-site-health.php | Gets page cache details. |
| [WP\_Site\_Health::get\_test\_page\_cache()](get_test_page_cache) wp-admin/includes/class-wp-site-health.php | Tests if a full page cache is available. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Site_Health::has_late_cron(): bool|WP_Error WP\_Site\_Health::has\_late\_cron(): bool|WP\_Error
===================================================
Checks if any scheduled tasks are late.
Returns a boolean value of `true` if a scheduled task is late and ends processing.
If the list of crons is an instance of [WP\_Error](../wp_error), returns the instance instead of a boolean value.
bool|[WP\_Error](../wp_error) True if a cron is late, false if not. [WP\_Error](../wp_error) if the cron is set to that.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function has_late_cron() {
if ( is_wp_error( $this->crons ) ) {
return $this->crons;
}
foreach ( $this->crons as $id => $cron ) {
$cron_offset = $cron->time - time();
if (
$cron_offset >= $this->timeout_missed_cron &&
$cron_offset < $this->timeout_late_cron
) {
$this->last_late_cron = $cron->hook;
return true;
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_test\_scheduled\_events()](get_test_scheduled_events) wp-admin/includes/class-wp-site-health.php | Tests if scheduled events run as intended. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_Site_Health::has_missed_cron(): bool|WP_Error WP\_Site\_Health::has\_missed\_cron(): bool|WP\_Error
=====================================================
Checks if any scheduled tasks have been missed.
Returns a boolean value of `true` if a scheduled task has been missed and ends processing.
If the list of crons is an instance of [WP\_Error](../wp_error), returns the instance instead of a boolean value.
bool|[WP\_Error](../wp_error) True if a cron was missed, false if not. [WP\_Error](../wp_error) if the cron is set to that.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function has_missed_cron() {
if ( is_wp_error( $this->crons ) ) {
return $this->crons;
}
foreach ( $this->crons as $id => $cron ) {
if ( ( $cron->time - time() ) < $this->timeout_missed_cron ) {
$this->last_missed_cron = $cron->hook;
return true;
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_test\_scheduled\_events()](get_test_scheduled_events) wp-admin/includes/class-wp-site-health.php | Tests if scheduled events run as intended. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::check_wp_version_check_exists() WP\_Site\_Health::check\_wp\_version\_check\_exists()
=====================================================
Tests whether `wp_version_check` is blocked.
It’s possible to block updates with the `wp_version_check` filter, but this can’t be checked during an Ajax call, as the filter is never introduced then.
This filter overrides a standard page request if it’s made by an admin through the Ajax call with the right query argument to check for this.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function check_wp_version_check_exists() {
if ( ! is_admin() || ! is_user_logged_in() || ! current_user_can( 'update_core' ) || ! isset( $_GET['health-check-test-wp_version_check'] ) ) {
return;
}
echo ( has_filter( 'wp_version_check', 'wp_version_check' ) ? 'yes' : 'no' );
die();
}
```
| Uses | Description |
| --- | --- |
| [has\_filter()](../../functions/has_filter) wp-includes/plugin.php | Checks if any filter has been registered for a hook. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [is\_user\_logged\_in()](../../functions/is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::test_php_extension_availability( string $extension_name = null, string $function_name = null, string $constant_name = null, string $class_name = null ): bool WP\_Site\_Health::test\_php\_extension\_availability( string $extension\_name = null, string $function\_name = null, string $constant\_name = null, string $class\_name = null ): bool
======================================================================================================================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Checks if the passed extension or function are available.
Make the check for available PHP modules into a simple boolean operator for a cleaner test runner.
`$extension_name` string Optional The extension name to test. Default: `null`
`$function_name` string Optional The function name to test. Default: `null`
`$constant_name` string Optional The constant name to test for. Default: `null`
`$class_name` string Optional The class name to test for. Default: `null`
bool Whether or not the extension and function are available.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
private function test_php_extension_availability( $extension_name = null, $function_name = null, $constant_name = null, $class_name = null ) {
// If no extension or function is passed, claim to fail testing, as we have nothing to test against.
if ( ! $extension_name && ! $function_name && ! $constant_name && ! $class_name ) {
return false;
}
if ( $extension_name && ! extension_loaded( $extension_name ) ) {
return false;
}
if ( $function_name && ! function_exists( $function_name ) ) {
return false;
}
if ( $constant_name && ! defined( $constant_name ) ) {
return false;
}
if ( $class_name && ! class_exists( $class_name ) ) {
return false;
}
return true;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_test\_php\_extensions()](get_test_php_extensions) wp-admin/includes/class-wp-site-health.php | Tests if required PHP modules are installed on the host. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | The `$constant_name` and `$class_name` parameters were added. |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::get_test_utf8mb4_support(): array WP\_Site\_Health::get\_test\_utf8mb4\_support(): array
======================================================
Tests if the database server is capable of using utf8mb4.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_utf8mb4_support() {
global $wpdb;
if ( ! $this->mysql_server_version ) {
$this->prepare_sql_data();
}
$result = array(
'label' => __( 'UTF8MB4 is supported' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'UTF8MB4 is the character set WordPress prefers for database storage because it safely supports the widest set of characters and encodings, including Emoji, enabling better support for non-English languages.' )
),
'actions' => '',
'test' => 'utf8mb4_support',
);
if ( ! $this->is_mariadb ) {
if ( version_compare( $this->mysql_server_version, '5.5.3', '<' ) ) {
$result['status'] = 'recommended';
$result['label'] = __( 'utf8mb4 requires a MySQL update' );
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: %s: Version number. */
__( 'WordPress’ utf8mb4 support requires MySQL version %s or greater. Please contact your server administrator.' ),
'5.5.3'
)
);
} else {
$result['description'] .= sprintf(
'<p>%s</p>',
__( 'Your MySQL version supports utf8mb4.' )
);
}
} else { // MariaDB introduced utf8mb4 support in 5.5.0.
if ( version_compare( $this->mysql_server_version, '5.5.0', '<' ) ) {
$result['status'] = 'recommended';
$result['label'] = __( 'utf8mb4 requires a MariaDB update' );
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: %s: Version number. */
__( 'WordPress’ utf8mb4 support requires MariaDB version %s or greater. Please contact your server administrator.' ),
'5.5.0'
)
);
} else {
$result['description'] .= sprintf(
'<p>%s</p>',
__( 'Your MariaDB version supports utf8mb4.' )
);
}
}
if ( $wpdb->use_mysqli ) {
// phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysqli_get_client_info
$mysql_client_version = mysqli_get_client_info();
} else {
// phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysql_get_client_info,PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved
$mysql_client_version = mysql_get_client_info();
}
/*
* libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
* mysqlnd has supported utf8mb4 since 5.0.9.
*/
if ( false !== strpos( $mysql_client_version, 'mysqlnd' ) ) {
$mysql_client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $mysql_client_version );
if ( version_compare( $mysql_client_version, '5.0.9', '<' ) ) {
$result['status'] = 'recommended';
$result['label'] = __( 'utf8mb4 requires a newer client library' );
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: Name of the library, 2: Number of version. */
__( 'WordPress’ utf8mb4 support requires MySQL client library (%1$s) version %2$s or newer. Please contact your server administrator.' ),
'mysqlnd',
'5.0.9'
)
);
}
} else {
if ( version_compare( $mysql_client_version, '5.5.3', '<' ) ) {
$result['status'] = 'recommended';
$result['label'] = __( 'utf8mb4 requires a newer client library' );
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: Name of the library, 2: Number of version. */
__( 'WordPress’ utf8mb4 support requires MySQL client library (%1$s) version %2$s or newer. Please contact your server administrator.' ),
'libmysql',
'5.5.3'
)
);
}
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::prepare\_sql\_data()](prepare_sql_data) wp-admin/includes/class-wp-site-health.php | Runs the SQL version checks. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::prepare_sql_data() WP\_Site\_Health::prepare\_sql\_data()
======================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Runs the SQL version checks.
These values are used in later tests, but the part of preparing them is more easily managed early in the class for ease of access and discovery.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
private function prepare_sql_data() {
global $wpdb;
$mysql_server_type = $wpdb->db_server_info();
$this->mysql_server_version = $wpdb->get_var( 'SELECT VERSION()' );
if ( stristr( $mysql_server_type, 'mariadb' ) ) {
$this->is_mariadb = true;
$this->mysql_recommended_version = $this->mariadb_recommended_version;
}
$this->is_acceptable_mysql_version = version_compare( $this->mysql_required_version, $this->mysql_server_version, '<=' );
$this->is_recommended_mysql_version = version_compare( $this->mysql_recommended_version, $this->mysql_server_version, '<=' );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::db\_server\_info()](../wpdb/db_server_info) wp-includes/class-wpdb.php | Retrieves full database server information. |
| [wpdb::get\_var()](../wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_test\_sql\_server()](get_test_sql_server) wp-admin/includes/class-wp-site-health.php | Tests if the SQL server is up to date. |
| [WP\_Site\_Health::get\_test\_utf8mb4\_support()](get_test_utf8mb4_support) wp-admin/includes/class-wp-site-health.php | Tests if the database server is capable of using utf8mb4. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::get_test_page_cache(): array WP\_Site\_Health::get\_test\_page\_cache(): array
=================================================
Tests if a full page cache is available.
array The test result.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_page_cache() {
$description = '<p>' . __( 'Page cache enhances the speed and performance of your site by saving and serving static pages instead of calling for a page every time a user visits.' ) . '</p>';
$description .= '<p>' . __( 'Page cache is detected by looking for an active page cache plugin as well as making three requests to the homepage and looking for one or more of the following HTTP client caching response headers:' ) . '</p>';
$description .= '<code>' . implode( '</code>, <code>', array_keys( $this->get_page_cache_headers() ) ) . '.</code>';
$result = array(
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => wp_kses_post( $description ),
'test' => 'page_cache',
'status' => 'good',
'label' => '',
'actions' => sprintf(
'<p><a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s <span class="screen-reader-text">%3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
__( 'https://wordpress.org/support/article/optimization/#Caching' ),
__( 'Learn more about page cache' ),
/* translators: Accessibility text. */
__( '(opens in a new tab)' )
),
);
$page_cache_detail = $this->get_page_cache_detail();
if ( is_wp_error( $page_cache_detail ) ) {
$result['label'] = __( 'Unable to detect the presence of page cache' );
$result['status'] = 'recommended';
$error_info = sprintf(
/* translators: 1: Error message, 2: Error code. */
__( 'Unable to detect page cache due to possible loopback request problem. Please verify that the loopback request test is passing. Error: %1$s (Code: %2$s)' ),
$page_cache_detail->get_error_message(),
$page_cache_detail->get_error_code()
);
$result['description'] = wp_kses_post( "<p>$error_info</p>" ) . $result['description'];
return $result;
}
$result['status'] = $page_cache_detail['status'];
switch ( $page_cache_detail['status'] ) {
case 'recommended':
$result['label'] = __( 'Page cache is not detected but the server response time is OK' );
break;
case 'good':
$result['label'] = __( 'Page cache is detected and the server response time is good' );
break;
default:
if ( empty( $page_cache_detail['headers'] ) && ! $page_cache_detail['advanced_cache_present'] ) {
$result['label'] = __( 'Page cache is not detected and the server response time is slow' );
} else {
$result['label'] = __( 'Page cache is detected but the server response time is still slow' );
}
}
$page_cache_test_summary = array();
if ( empty( $page_cache_detail['response_time'] ) ) {
$page_cache_test_summary[] = '<span class="dashicons dashicons-dismiss"></span> ' . __( 'Server response time could not be determined. Verify that loopback requests are working.' );
} else {
$threshold = $this->get_good_response_time_threshold();
if ( $page_cache_detail['response_time'] < $threshold ) {
$page_cache_test_summary[] = '<span class="dashicons dashicons-yes-alt"></span> ' . sprintf(
/* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */
__( 'Median server response time was %1$s milliseconds. This is less than the recommended %2$s milliseconds threshold.' ),
number_format_i18n( $page_cache_detail['response_time'] ),
number_format_i18n( $threshold )
);
} else {
$page_cache_test_summary[] = '<span class="dashicons dashicons-warning"></span> ' . sprintf(
/* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */
__( 'Median server response time was %1$s milliseconds. It should be less than the recommended %2$s milliseconds threshold.' ),
number_format_i18n( $page_cache_detail['response_time'] ),
number_format_i18n( $threshold )
);
}
if ( empty( $page_cache_detail['headers'] ) ) {
$page_cache_test_summary[] = '<span class="dashicons dashicons-warning"></span> ' . __( 'No client caching response headers were detected.' );
} else {
$headers_summary = '<span class="dashicons dashicons-yes-alt"></span>';
$headers_summary .= ' ' . sprintf(
/* translators: %d: Number of caching headers. */
_n(
'There was %d client caching response header detected:',
'There were %d client caching response headers detected:',
count( $page_cache_detail['headers'] )
),
count( $page_cache_detail['headers'] )
);
$headers_summary .= ' <code>' . implode( '</code>, <code>', $page_cache_detail['headers'] ) . '</code>.';
$page_cache_test_summary[] = $headers_summary;
}
}
if ( $page_cache_detail['advanced_cache_present'] ) {
$page_cache_test_summary[] = '<span class="dashicons dashicons-yes-alt"></span> ' . __( 'A page cache plugin was detected.' );
} elseif ( ! ( is_array( $page_cache_detail ) && ! empty( $page_cache_detail['headers'] ) ) ) {
// Note: This message is not shown if client caching response headers were present since an external caching layer may be employed.
$page_cache_test_summary[] = '<span class="dashicons dashicons-warning"></span> ' . __( 'A page cache plugin was not detected.' );
}
$result['description'] .= '<ul><li>' . implode( '</li><li>', $page_cache_test_summary ) . '</li></ul>';
return $result;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::get\_page\_cache\_headers()](get_page_cache_headers) wp-admin/includes/class-wp-site-health.php | Returns a list of headers and its verification callback to verify if page cache is enabled or not. |
| [WP\_Site\_Health::get\_page\_cache\_detail()](get_page_cache_detail) wp-admin/includes/class-wp-site-health.php | Gets page cache details. |
| [WP\_Site\_Health::get\_good\_response\_time\_threshold()](get_good_response_time_threshold) wp-admin/includes/class-wp-site-health.php | Gets the threshold below which a response time is considered good. |
| [\_n()](../../functions/_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [wp\_kses\_post()](../../functions/wp_kses_post) wp-includes/kses.php | Sanitizes content for allowed HTML tags for post content. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Site_Health::available_object_cache_services(): string[] WP\_Site\_Health::available\_object\_cache\_services(): string[]
================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Returns a list of available persistent object cache services.
string[] The list of available persistent object cache services.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
private function available_object_cache_services() {
$extensions = array_map(
'extension_loaded',
array(
'APCu' => 'apcu',
'Redis' => 'redis',
'Relay' => 'relay',
'Memcache' => 'memcache',
'Memcached' => 'memcached',
)
);
$services = array_keys( array_filter( $extensions ) );
/**
* Filters the persistent object cache services available to the user.
*
* This can be useful to hide or add services not included in the defaults.
*
* @since 6.1.0
*
* @param string[] $services The list of available persistent object cache services.
*/
return apply_filters( 'site_status_available_object_cache_services', $services );
}
```
[apply\_filters( 'site\_status\_available\_object\_cache\_services', string[] $services )](../../hooks/site_status_available_object_cache_services)
Filters the persistent object cache services available to the user.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_test\_persistent\_object\_cache()](get_test_persistent_object_cache) wp-admin/includes/class-wp-site-health.php | Tests if the site uses persistent object cache and recommends to use it if not. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Site_Health::get_test_file_uploads(): array WP\_Site\_Health::get\_test\_file\_uploads(): array
===================================================
Tests if ‘file\_uploads’ directive in PHP.ini is turned off.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_file_uploads() {
$result = array(
'label' => __( 'Files can be uploaded' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: file_uploads, 2: php.ini */
__( 'The %1$s directive in %2$s determines if uploading files is allowed on your site.' ),
'<code>file_uploads</code>',
'<code>php.ini</code>'
)
),
'actions' => '',
'test' => 'file_uploads',
);
if ( ! function_exists( 'ini_get' ) ) {
$result['status'] = 'critical';
$result['description'] .= sprintf(
/* translators: %s: ini_get() */
__( 'The %s function has been disabled, some media settings are unavailable because of this.' ),
'<code>ini_get()</code>'
);
return $result;
}
if ( empty( ini_get( 'file_uploads' ) ) ) {
$result['status'] = 'critical';
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: file_uploads, 2: 0 */
__( '%1$s is set to %2$s. You won\'t be able to upload files on your site.' ),
'<code>file_uploads</code>',
'<code>0</code>'
)
);
return $result;
}
$post_max_size = ini_get( 'post_max_size' );
$upload_max_filesize = ini_get( 'upload_max_filesize' );
if ( wp_convert_hr_to_bytes( $post_max_size ) < wp_convert_hr_to_bytes( $upload_max_filesize ) ) {
$result['label'] = sprintf(
/* translators: 1: post_max_size, 2: upload_max_filesize */
__( 'The "%1$s" value is smaller than "%2$s"' ),
'post_max_size',
'upload_max_filesize'
);
$result['status'] = 'recommended';
if ( 0 === wp_convert_hr_to_bytes( $post_max_size ) ) {
$result['description'] = sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: post_max_size, 2: upload_max_filesize */
__( 'The setting for %1$s is currently configured as 0, this could cause some problems when trying to upload files through plugin or theme features that rely on various upload methods. It is recommended to configure this setting to a fixed value, ideally matching the value of %2$s, as some upload methods read the value 0 as either unlimited, or disabled.' ),
'<code>post_max_size</code>',
'<code>upload_max_filesize</code>'
)
);
} else {
$result['description'] = sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: post_max_size, 2: upload_max_filesize */
__( 'The setting for %1$s is smaller than %2$s, this could cause some problems when trying to upload files.' ),
'<code>post_max_size</code>',
'<code>upload_max_filesize</code>'
)
);
}
return $result;
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [wp\_convert\_hr\_to\_bytes()](../../functions/wp_convert_hr_to_bytes) wp-includes/load.php | Converts a shorthand byte value to an integer byte value. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Site_Health::admin_body_class( string $body_class ): string WP\_Site\_Health::admin\_body\_class( string $body\_class ): string
===================================================================
Adds a class to the body HTML tag.
Filters the body class string for admin pages and adds our own class for easier styling.
`$body_class` string Required The body class string. string The modified body class string.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function admin_body_class( $body_class ) {
$screen = get_current_screen();
if ( 'site-health' !== $screen->id ) {
return $body_class;
}
$body_class .= ' site-health';
return $body_class;
}
```
| Uses | Description |
| --- | --- |
| [get\_current\_screen()](../../functions/get_current_screen) wp-admin/includes/screen.php | Get the current screen object |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::get_page_cache_headers(): array WP\_Site\_Health::get\_page\_cache\_headers(): array
====================================================
Returns a list of headers and its verification callback to verify if page cache is enabled or not.
Note: key is header name and value could be callable function to verify header value.
Empty value mean existence of header detect page cache is enabled.
array List of client caching headers and their (optional) verification callbacks.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_page_cache_headers() {
$cache_hit_callback = static function ( $header_value ) {
return false !== strpos( strtolower( $header_value ), 'hit' );
};
$cache_headers = array(
'cache-control' => static function ( $header_value ) {
return (bool) preg_match( '/max-age=[1-9]/', $header_value );
},
'expires' => static function ( $header_value ) {
return strtotime( $header_value ) > time();
},
'age' => static function ( $header_value ) {
return is_numeric( $header_value ) && $header_value > 0;
},
'last-modified' => '',
'etag' => '',
'x-cache-enabled' => static function ( $header_value ) {
return 'true' === strtolower( $header_value );
},
'x-cache-disabled' => static function ( $header_value ) {
return ( 'on' !== strtolower( $header_value ) );
},
'x-srcache-store-status' => $cache_hit_callback,
'x-srcache-fetch-status' => $cache_hit_callback,
);
/**
* Filters the list of cache headers supported by core.
*
* @since 6.1.0
*
* @param array $cache_headers Array of supported cache headers.
*/
return apply_filters( 'site_status_page_cache_supported_cache_headers', $cache_headers );
}
```
[apply\_filters( 'site\_status\_page\_cache\_supported\_cache\_headers', array $cache\_headers )](../../hooks/site_status_page_cache_supported_cache_headers)
Filters the list of cache headers supported by core.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::check\_for\_page\_caching()](check_for_page_caching) wp-admin/includes/class-wp-site-health.php | Checks if site has page cache enabled or not. |
| [WP\_Site\_Health::get\_test\_page\_cache()](get_test_page_cache) wp-admin/includes/class-wp-site-health.php | Tests if a full page cache is available. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Site_Health::get_test_plugin_version(): array WP\_Site\_Health::get\_test\_plugin\_version(): array
=====================================================
Tests if plugins are outdated, or unnecessary.
The test checks if your plugins are up to date, and encourages you to remove any that are not in use.
array The test result.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_plugin_version() {
$result = array(
'label' => __( 'Your plugins are all up to date' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'Plugins extend your site’s functionality with things like contact forms, ecommerce and much more. That means they have deep access to your site, so it’s vital to keep them up to date.' )
),
'actions' => sprintf(
'<p><a href="%s">%s</a></p>',
esc_url( admin_url( 'plugins.php' ) ),
__( 'Manage your plugins' )
),
'test' => 'plugin_version',
);
$plugins = get_plugins();
$plugin_updates = get_plugin_updates();
$plugins_active = 0;
$plugins_total = 0;
$plugins_need_update = 0;
// Loop over the available plugins and check their versions and active state.
foreach ( $plugins as $plugin_path => $plugin ) {
$plugins_total++;
if ( is_plugin_active( $plugin_path ) ) {
$plugins_active++;
}
if ( array_key_exists( $plugin_path, $plugin_updates ) ) {
$plugins_need_update++;
}
}
// Add a notice if there are outdated plugins.
if ( $plugins_need_update > 0 ) {
$result['status'] = 'critical';
$result['label'] = __( 'You have plugins waiting to be updated' );
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: %d: The number of outdated plugins. */
_n(
'Your site has %d plugin waiting to be updated.',
'Your site has %d plugins waiting to be updated.',
$plugins_need_update
),
$plugins_need_update
)
);
$result['actions'] .= sprintf(
'<p><a href="%s">%s</a></p>',
esc_url( network_admin_url( 'plugins.php?plugin_status=upgrade' ) ),
__( 'Update your plugins' )
);
} else {
if ( 1 === $plugins_active ) {
$result['description'] .= sprintf(
'<p>%s</p>',
__( 'Your site has 1 active plugin, and it is up to date.' )
);
} elseif ( $plugins_active > 0 ) {
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: %d: The number of active plugins. */
_n(
'Your site has %d active plugin, and it is up to date.',
'Your site has %d active plugins, and they are all up to date.',
$plugins_active
),
$plugins_active
)
);
} else {
$result['description'] .= sprintf(
'<p>%s</p>',
__( 'Your site does not have any active plugins.' )
);
}
}
// Check if there are inactive plugins.
if ( $plugins_total > $plugins_active && ! is_multisite() ) {
$unused_plugins = $plugins_total - $plugins_active;
$result['status'] = 'recommended';
$result['label'] = __( 'You should remove inactive plugins' );
$result['description'] .= sprintf(
'<p>%s %s</p>',
sprintf(
/* translators: %d: The number of inactive plugins. */
_n(
'Your site has %d inactive plugin.',
'Your site has %d inactive plugins.',
$unused_plugins
),
$unused_plugins
),
__( 'Inactive plugins are tempting targets for attackers. If you are not going to use a plugin, you should consider removing it.' )
);
$result['actions'] .= sprintf(
'<p><a href="%s">%s</a></p>',
esc_url( admin_url( 'plugins.php?plugin_status=inactive' ) ),
__( 'Manage inactive plugins' )
);
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [get\_plugin\_updates()](../../functions/get_plugin_updates) wp-admin/includes/update.php | Retrieves plugins with updates available. |
| [is\_plugin\_active()](../../functions/is_plugin_active) wp-admin/includes/plugin.php | Determines whether a plugin is active. |
| [get\_plugins()](../../functions/get_plugins) wp-admin/includes/plugin.php | Checks the plugins directory and retrieve all plugin files with plugin data. |
| [\_n()](../../functions/_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [network\_admin\_url()](../../functions/network_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the network. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::is_development_environment(): bool WP\_Site\_Health::is\_development\_environment(): bool
======================================================
Checks if the current environment type is set to ‘development’ or ‘local’.
bool True if it is a development environment, false if not.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function is_development_environment() {
return in_array( wp_get_environment_type(), array( 'development', 'local' ), true );
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_environment\_type()](../../functions/wp_get_environment_type) wp-includes/load.php | Retrieves the current environment type. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::wp\_cron\_scheduled\_check()](wp_cron_scheduled_check) wp-admin/includes/class-wp-site-health.php | Runs the scheduled event to check and update the latest site health status for the website. |
| [WP\_Site\_Health::enqueue\_scripts()](enqueue_scripts) wp-admin/includes/class-wp-site-health.php | Enqueues the site health scripts. |
| [WP\_Site\_Health::get\_test\_is\_in\_debug\_mode()](get_test_is_in_debug_mode) wp-admin/includes/class-wp-site-health.php | Tests if debug information is enabled. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Site_Health::get_test_sql_server(): array WP\_Site\_Health::get\_test\_sql\_server(): array
=================================================
Tests if the SQL server is up to date.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_sql_server() {
if ( ! $this->mysql_server_version ) {
$this->prepare_sql_data();
}
$result = array(
'label' => __( 'SQL server is up to date' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'The SQL server is a required piece of software for the database WordPress uses to store all your site’s content and settings.' )
),
'actions' => sprintf(
'<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
/* translators: Localized version of WordPress requirements if one exists. */
esc_url( __( 'https://wordpress.org/about/requirements/' ) ),
__( 'Learn more about what WordPress requires to run.' ),
/* translators: Accessibility text. */
__( '(opens in a new tab)' )
),
'test' => 'sql_server',
);
$db_dropin = file_exists( WP_CONTENT_DIR . '/db.php' );
if ( ! $this->is_recommended_mysql_version ) {
$result['status'] = 'recommended';
$result['label'] = __( 'Outdated SQL server' );
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server recommended version number. */
__( 'For optimal performance and security reasons, you should consider running %1$s version %2$s or higher. Contact your web hosting company to correct this.' ),
( $this->is_mariadb ? 'MariaDB' : 'MySQL' ),
$this->mysql_recommended_version
)
);
}
if ( ! $this->is_acceptable_mysql_version ) {
$result['status'] = 'critical';
$result['label'] = __( 'Severely outdated SQL server' );
$result['badge']['label'] = __( 'Security' );
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server minimum version number. */
__( 'WordPress requires %1$s version %2$s or higher. Contact your web hosting company to correct this.' ),
( $this->is_mariadb ? 'MariaDB' : 'MySQL' ),
$this->mysql_required_version
)
);
}
if ( $db_dropin ) {
$result['description'] .= sprintf(
'<p>%s</p>',
wp_kses(
sprintf(
/* translators: 1: The name of the drop-in. 2: The name of the database engine. */
__( 'You are using a %1$s drop-in which might mean that a %2$s database is not being used.' ),
'<code>wp-content/db.php</code>',
( $this->is_mariadb ? 'MariaDB' : 'MySQL' )
),
array(
'code' => true,
)
)
);
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::prepare\_sql\_data()](prepare_sql_data) wp-admin/includes/class-wp-site-health.php | Runs the SQL version checks. |
| [wp\_kses()](../../functions/wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Site_Health::get_test_wordpress_version(): array WP\_Site\_Health::get\_test\_wordpress\_version(): array
========================================================
Tests for WordPress version and outputs it.
Gives various results depending on what kind of updates are available, if any, to encourage the user to install security updates as a priority.
array The test result.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_wordpress_version() {
$result = array(
'label' => '',
'status' => '',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => '',
'actions' => '',
'test' => 'wordpress_version',
);
$core_current_version = get_bloginfo( 'version' );
$core_updates = get_core_updates();
if ( ! is_array( $core_updates ) ) {
$result['status'] = 'recommended';
$result['label'] = sprintf(
/* translators: %s: Your current version of WordPress. */
__( 'WordPress version %s' ),
$core_current_version
);
$result['description'] = sprintf(
'<p>%s</p>',
__( 'Unable to check if any new versions of WordPress are available.' )
);
$result['actions'] = sprintf(
'<a href="%s">%s</a>',
esc_url( admin_url( 'update-core.php?force-check=1' ) ),
__( 'Check for updates manually' )
);
} else {
foreach ( $core_updates as $core => $update ) {
if ( 'upgrade' === $update->response ) {
$current_version = explode( '.', $core_current_version );
$new_version = explode( '.', $update->version );
$current_major = $current_version[0] . '.' . $current_version[1];
$new_major = $new_version[0] . '.' . $new_version[1];
$result['label'] = sprintf(
/* translators: %s: The latest version of WordPress available. */
__( 'WordPress update available (%s)' ),
$update->version
);
$result['actions'] = sprintf(
'<a href="%s">%s</a>',
esc_url( admin_url( 'update-core.php' ) ),
__( 'Install the latest version of WordPress' )
);
if ( $current_major !== $new_major ) {
// This is a major version mismatch.
$result['status'] = 'recommended';
$result['description'] = sprintf(
'<p>%s</p>',
__( 'A new version of WordPress is available.' )
);
} else {
// This is a minor version, sometimes considered more critical.
$result['status'] = 'critical';
$result['badge']['label'] = __( 'Security' );
$result['description'] = sprintf(
'<p>%s</p>',
__( 'A new minor update is available for your site. Because minor updates often address security, it’s important to install them.' )
);
}
} else {
$result['status'] = 'good';
$result['label'] = sprintf(
/* translators: %s: The current version of WordPress installed on this site. */
__( 'Your version of WordPress (%s) is up to date' ),
$core_current_version
);
$result['description'] = sprintf(
'<p>%s</p>',
__( 'You are currently running the latest version of WordPress available, keep it up!' )
);
}
}
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [get\_core\_updates()](../../functions/get_core_updates) wp-admin/includes/update.php | Gets available core updates. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::__construct() WP\_Site\_Health::\_\_construct()
=================================
[WP\_Site\_Health](../wp_site_health) constructor.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function __construct() {
$this->maybe_create_scheduled_event();
// Save memory limit before it's affected by wp_raise_memory_limit( 'admin' ).
$this->php_memory_limit = ini_get( 'memory_limit' );
$this->timeout_late_cron = 0;
$this->timeout_missed_cron = - 5 * MINUTE_IN_SECONDS;
if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) {
$this->timeout_late_cron = - 15 * MINUTE_IN_SECONDS;
$this->timeout_missed_cron = - 1 * HOUR_IN_SECONDS;
}
add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'wp_site_health_scheduled_check', array( $this, 'wp_cron_scheduled_check' ) );
add_action( 'site_health_tab_content', array( $this, 'show_site_health_tab' ) );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::maybe\_create\_scheduled\_event()](maybe_create_scheduled_event) wp-admin/includes/class-wp-site-health.php | Creates a weekly cron event, if one does not already exist. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_instance()](get_instance) wp-admin/includes/class-wp-site-health.php | Returns an instance of the [WP\_Site\_Health](../wp_site_health) class, or create one if none exist yet. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::enqueue_scripts() WP\_Site\_Health::enqueue\_scripts()
====================================
Enqueues the site health scripts.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function enqueue_scripts() {
$screen = get_current_screen();
if ( 'site-health' !== $screen->id && 'dashboard' !== $screen->id ) {
return;
}
$health_check_js_variables = array(
'screen' => $screen->id,
'nonce' => array(
'site_status' => wp_create_nonce( 'health-check-site-status' ),
'site_status_result' => wp_create_nonce( 'health-check-site-status-result' ),
),
'site_status' => array(
'direct' => array(),
'async' => array(),
'issues' => array(
'good' => 0,
'recommended' => 0,
'critical' => 0,
),
),
);
$issue_counts = get_transient( 'health-check-site-status-result' );
if ( false !== $issue_counts ) {
$issue_counts = json_decode( $issue_counts );
$health_check_js_variables['site_status']['issues'] = $issue_counts;
}
if ( 'site-health' === $screen->id && ( ! isset( $_GET['tab'] ) || empty( $_GET['tab'] ) ) ) {
$tests = WP_Site_Health::get_tests();
// Don't run https test on development environments.
if ( $this->is_development_environment() ) {
unset( $tests['async']['https_status'] );
}
foreach ( $tests['direct'] as $test ) {
if ( is_string( $test['test'] ) ) {
$test_function = sprintf(
'get_test_%s',
$test['test']
);
if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) {
$health_check_js_variables['site_status']['direct'][] = $this->perform_test( array( $this, $test_function ) );
continue;
}
}
if ( is_callable( $test['test'] ) ) {
$health_check_js_variables['site_status']['direct'][] = $this->perform_test( $test['test'] );
}
}
foreach ( $tests['async'] as $test ) {
if ( is_string( $test['test'] ) ) {
$health_check_js_variables['site_status']['async'][] = array(
'test' => $test['test'],
'has_rest' => ( isset( $test['has_rest'] ) ? $test['has_rest'] : false ),
'completed' => false,
'headers' => isset( $test['headers'] ) ? $test['headers'] : array(),
);
}
}
}
wp_localize_script( 'site-health', 'SiteHealth', $health_check_js_variables );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::is\_development\_environment()](is_development_environment) wp-admin/includes/class-wp-site-health.php | Checks if the current environment type is set to ‘development’ or ‘local’. |
| [WP\_Site\_Health::perform\_test()](perform_test) wp-admin/includes/class-wp-site-health.php | Runs a Site Health test directly. |
| [WP\_Site\_Health::get\_tests()](get_tests) wp-admin/includes/class-wp-site-health.php | Returns a set of tests that belong to the site status page. |
| [get\_current\_screen()](../../functions/get_current_screen) wp-admin/includes/screen.php | Get the current screen object |
| [wp\_create\_nonce()](../../functions/wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| [wp\_localize\_script()](../../functions/wp_localize_script) wp-includes/functions.wp-scripts.php | Localize a script. |
| [get\_transient()](../../functions/get_transient) wp-includes/option.php | Retrieves the value of a transient. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::get_test_background_updates(): array WP\_Site\_Health::get\_test\_background\_updates(): array
=========================================================
Tests if WordPress can run automated background updates.
Background updates in WordPress are primarily used for minor releases and security updates.
It’s important to either have these working, or be aware that they are intentionally disabled for whatever reason.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_background_updates() {
$result = array(
'label' => __( 'Background updates are working' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'Background updates ensure that WordPress can auto-update if a security update is released for the version you are currently using.' )
),
'actions' => '',
'test' => 'background_updates',
);
if ( ! class_exists( 'WP_Site_Health_Auto_Updates' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-site-health-auto-updates.php';
}
// Run the auto-update tests in a separate class,
// as there are many considerations to be made.
$automatic_updates = new WP_Site_Health_Auto_Updates();
$tests = $automatic_updates->run_tests();
$output = '<ul>';
foreach ( $tests as $test ) {
$severity_string = __( 'Passed' );
if ( 'fail' === $test->severity ) {
$result['label'] = __( 'Background updates are not working as expected' );
$result['status'] = 'critical';
$severity_string = __( 'Error' );
}
if ( 'warning' === $test->severity && 'good' === $result['status'] ) {
$result['label'] = __( 'Background updates may not be working properly' );
$result['status'] = 'recommended';
$severity_string = __( 'Warning' );
}
$output .= sprintf(
'<li><span class="dashicons %s"><span class="screen-reader-text">%s</span></span> %s</li>',
esc_attr( $test->severity ),
$severity_string,
$test->description
);
}
$output .= '</ul>';
if ( 'good' !== $result['status'] ) {
$result['description'] .= $output;
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health\_Auto\_Updates::\_\_construct()](../wp_site_health_auto_updates/__construct) wp-admin/includes/class-wp-site-health-auto-updates.php | [WP\_Site\_Health\_Auto\_Updates](../wp_site_health_auto_updates) constructor. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::get_test_https_status(): array WP\_Site\_Health::get\_test\_https\_status(): array
===================================================
Tests if the site is serving content over HTTPS.
Many sites have varying degrees of HTTPS support, the most common of which is sites that have it enabled, but only if you visit the right site address.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_https_status() {
// Enforce fresh HTTPS detection results. This is normally invoked by using cron,
// but for Site Health it should always rely on the latest results.
wp_update_https_detection_errors();
$default_update_url = wp_get_default_update_https_url();
$result = array(
'label' => __( 'Your website is using an active HTTPS connection' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'An HTTPS connection is a more secure way of browsing the web. Many services now have HTTPS as a requirement. HTTPS allows you to take advantage of new features that can increase site speed, improve search rankings, and gain the trust of your visitors by helping to protect their online privacy.' )
),
'actions' => sprintf(
'<p><a href="%s" target="_blank" rel="noopener">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
esc_url( $default_update_url ),
__( 'Learn more about why you should use HTTPS' ),
/* translators: Accessibility text. */
__( '(opens in a new tab)' )
),
'test' => 'https_status',
);
if ( ! wp_is_using_https() ) {
// If the website is not using HTTPS, provide more information
// about whether it is supported and how it can be enabled.
$result['status'] = 'recommended';
$result['label'] = __( 'Your website does not use HTTPS' );
if ( wp_is_site_url_using_https() ) {
if ( is_ssl() ) {
$result['description'] = sprintf(
'<p>%s</p>',
sprintf(
/* translators: %s: URL to Settings > General > Site Address. */
__( 'You are accessing this website using HTTPS, but your <a href="%s">Site Address</a> is not set up to use HTTPS by default.' ),
esc_url( admin_url( 'options-general.php' ) . '#home' )
)
);
} else {
$result['description'] = sprintf(
'<p>%s</p>',
sprintf(
/* translators: %s: URL to Settings > General > Site Address. */
__( 'Your <a href="%s">Site Address</a> is not set up to use HTTPS.' ),
esc_url( admin_url( 'options-general.php' ) . '#home' )
)
);
}
} else {
if ( is_ssl() ) {
$result['description'] = sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */
__( 'You are accessing this website using HTTPS, but your <a href="%1$s">WordPress Address</a> and <a href="%2$s">Site Address</a> are not set up to use HTTPS by default.' ),
esc_url( admin_url( 'options-general.php' ) . '#siteurl' ),
esc_url( admin_url( 'options-general.php' ) . '#home' )
)
);
} else {
$result['description'] = sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */
__( 'Your <a href="%1$s">WordPress Address</a> and <a href="%2$s">Site Address</a> are not set up to use HTTPS.' ),
esc_url( admin_url( 'options-general.php' ) . '#siteurl' ),
esc_url( admin_url( 'options-general.php' ) . '#home' )
)
);
}
}
if ( wp_is_https_supported() ) {
$result['description'] .= sprintf(
'<p>%s</p>',
__( 'HTTPS is already supported for your website.' )
);
if ( defined( 'WP_HOME' ) || defined( 'WP_SITEURL' ) ) {
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: wp-config.php, 2: WP_HOME, 3: WP_SITEURL */
__( 'However, your WordPress Address is currently controlled by a PHP constant and therefore cannot be updated. You need to edit your %1$s and remove or update the definitions of %2$s and %3$s.' ),
'<code>wp-config.php</code>',
'<code>WP_HOME</code>',
'<code>WP_SITEURL</code>'
)
);
} elseif ( current_user_can( 'update_https' ) ) {
$default_direct_update_url = add_query_arg( 'action', 'update_https', wp_nonce_url( admin_url( 'site-health.php' ), 'wp_update_https' ) );
$direct_update_url = wp_get_direct_update_https_url();
if ( ! empty( $direct_update_url ) ) {
$result['actions'] = sprintf(
'<p class="button-container"><a class="button button-primary" href="%1$s" target="_blank" rel="noopener">%2$s<span class="screen-reader-text"> %3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
esc_url( $direct_update_url ),
__( 'Update your site to use HTTPS' ),
/* translators: Accessibility text. */
__( '(opens in a new tab)' )
);
} else {
$result['actions'] = sprintf(
'<p class="button-container"><a class="button button-primary" href="%1$s">%2$s</a></p>',
esc_url( $default_direct_update_url ),
__( 'Update your site to use HTTPS' )
);
}
}
} else {
// If host-specific "Update HTTPS" URL is provided, include a link.
$update_url = wp_get_update_https_url();
if ( $update_url !== $default_update_url ) {
$result['description'] .= sprintf(
'<p><a href="%s" target="_blank" rel="noopener">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
esc_url( $update_url ),
__( 'Talk to your web host about supporting HTTPS for your website.' ),
/* translators: Accessibility text. */
__( '(opens in a new tab)' )
);
} else {
$result['description'] .= sprintf(
'<p>%s</p>',
__( 'Talk to your web host about supporting HTTPS for your website.' )
);
}
}
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_default\_update\_https\_url()](../../functions/wp_get_default_update_https_url) wp-includes/functions.php | Gets the default URL to learn more about updating the site to use HTTPS. |
| [wp\_get\_direct\_update\_https\_url()](../../functions/wp_get_direct_update_https_url) wp-includes/functions.php | Gets the URL for directly updating the site to use HTTPS. |
| [wp\_get\_update\_https\_url()](../../functions/wp_get_update_https_url) wp-includes/functions.php | Gets the URL to learn more about updating the site to use HTTPS. |
| [wp\_update\_https\_detection\_errors()](../../functions/wp_update_https_detection_errors) wp-includes/https-detection.php | Runs a remote HTTPS request to detect whether HTTPS supported, and stores potential errors. |
| [wp\_is\_using\_https()](../../functions/wp_is_using_https) wp-includes/https-detection.php | Checks whether the website is using HTTPS. |
| [wp\_is\_site\_url\_using\_https()](../../functions/wp_is_site_url_using_https) wp-includes/https-detection.php | Checks whether the current site’s URL where WordPress is stored is using HTTPS. |
| [wp\_is\_https\_supported()](../../functions/wp_is_https_supported) wp-includes/https-detection.php | Checks whether HTTPS is supported for the server and domain. |
| [is\_ssl()](../../functions/is_ssl) wp-includes/load.php | Determines if SSL is used. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [wp\_nonce\_url()](../../functions/wp_nonce_url) wp-includes/functions.php | Retrieves URL with nonce added to URL query. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Updated to rely on [wp\_is\_using\_https()](../../functions/wp_is_using_https) and [wp\_is\_https\_supported()](../../functions/wp_is_https_supported) . |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Site_Health::get_instance(): WP_Site_Health|null WP\_Site\_Health::get\_instance(): WP\_Site\_Health|null
========================================================
Returns an instance of the [WP\_Site\_Health](../wp_site_health) class, or create one if none exist yet.
[WP\_Site\_Health](../wp_site_health)|null
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new WP_Site_Health();
}
return self::$instance;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::\_\_construct()](__construct) wp-admin/includes/class-wp-site-health.php | [WP\_Site\_Health](../wp_site_health) constructor. |
| Used By | Description |
| --- | --- |
| [WP\_Debug\_Data::debug\_data()](../wp_debug_data/debug_data) wp-admin/includes/class-wp-debug-data.php | Static function for generating site debug data when required. |
| [WP\_Site\_Health::get\_tests()](get_tests) wp-admin/includes/class-wp-site-health.php | Returns a set of tests that belong to the site status page. |
| [wp\_ajax\_health\_check\_dotorg\_communication()](../../functions/wp_ajax_health_check_dotorg_communication) wp-admin/includes/ajax-actions.php | Ajax handler for site health checks on server communication. |
| [wp\_ajax\_health\_check\_background\_updates()](../../functions/wp_ajax_health_check_background_updates) wp-admin/includes/ajax-actions.php | Ajax handler for site health checks on background updates. |
| [wp\_ajax\_health\_check\_loopback\_requests()](../../functions/wp_ajax_health_check_loopback_requests) wp-admin/includes/ajax-actions.php | Ajax handler for site health checks on loopback requests. |
| [create\_initial\_rest\_routes()](../../functions/create_initial_rest_routes) wp-includes/rest-api.php | Registers default REST API routes. |
| [wp\_dashboard\_setup()](../../functions/wp_dashboard_setup) wp-admin/includes/dashboard.php | Registers dashboard widgets. |
| Version | Description |
| --- | --- |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | Introduced. |
wordpress WP_Site_Health::maybe_create_scheduled_event() WP\_Site\_Health::maybe\_create\_scheduled\_event()
===================================================
Creates a weekly cron event, if one does not already exist.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function maybe_create_scheduled_event() {
if ( ! wp_next_scheduled( 'wp_site_health_scheduled_check' ) && ! wp_installing() ) {
wp_schedule_event( time() + DAY_IN_SECONDS, 'weekly', 'wp_site_health_scheduled_check' );
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_installing()](../../functions/wp_installing) wp-includes/load.php | Check or set whether WordPress is in “installation” mode. |
| [wp\_next\_scheduled()](../../functions/wp_next_scheduled) wp-includes/cron.php | Retrieve the next timestamp for an event. |
| [wp\_schedule\_event()](../../functions/wp_schedule_event) wp-includes/cron.php | Schedules a recurring event. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::\_\_construct()](__construct) wp-admin/includes/class-wp-site-health.php | [WP\_Site\_Health](../wp_site_health) constructor. |
| Version | Description |
| --- | --- |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | Introduced. |
wordpress WP_Site_Health::get_test_is_in_debug_mode(): array WP\_Site\_Health::get\_test\_is\_in\_debug\_mode(): array
=========================================================
Tests if debug information is enabled.
When WP\_DEBUG is enabled, errors and information may be disclosed to site visitors, or logged to a publicly accessible file.
Debugging is also frequently left enabled after looking for errors on a site, as site owners do not understand the implications of this.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_is_in_debug_mode() {
$result = array(
'label' => __( 'Your site is not set to output debug information' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'Debug mode is often enabled to gather more details about an error or site failure, but may contain sensitive information which should not be available on a publicly available website.' )
),
'actions' => sprintf(
'<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
/* translators: Documentation explaining debugging in WordPress. */
esc_url( __( 'https://wordpress.org/support/article/debugging-in-wordpress/' ) ),
__( 'Learn more about debugging in WordPress.' ),
/* translators: Accessibility text. */
__( '(opens in a new tab)' )
),
'test' => 'is_in_debug_mode',
);
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
$result['label'] = __( 'Your site is set to log errors to a potentially public file' );
$result['status'] = ( 0 === strpos( ini_get( 'error_log' ), ABSPATH ) ) ? 'critical' : 'recommended';
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: %s: WP_DEBUG_LOG */
__( 'The value, %s, has been added to this website’s configuration file. This means any errors on the site will be written to a file which is potentially available to all users.' ),
'<code>WP_DEBUG_LOG</code>'
)
);
}
if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) {
$result['label'] = __( 'Your site is set to display errors to site visitors' );
$result['status'] = 'critical';
// On development environments, set the status to recommended.
if ( $this->is_development_environment() ) {
$result['status'] = 'recommended';
}
$result['description'] .= sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: WP_DEBUG_DISPLAY, 2: WP_DEBUG */
__( 'The value, %1$s, has either been enabled by %2$s or added to your configuration file. This will make errors display on the front end of your site.' ),
'<code>WP_DEBUG_DISPLAY</code>',
'<code>WP_DEBUG</code>'
)
);
}
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::is\_development\_environment()](is_development_environment) wp-admin/includes/class-wp-site-health.php | Checks if the current environment type is set to ‘development’ or ‘local’. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::check_for_page_caching(): WP_Error|array WP\_Site\_Health::check\_for\_page\_caching(): WP\_Error|array
==============================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Checks if site has page cache enabled or not.
[WP\_Error](../wp_error)|array Page cache detection details or else error information.
* `advanced_cache_present`boolWhether a page cache plugin is present.
* `page_caching_response_headers`array[]Sets of client caching headers for the responses.
* `response_timing`float[]Response timings.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
private function check_for_page_caching() {
/** This filter is documented in wp-includes/class-wp-http-streams.php */
$sslverify = apply_filters( 'https_local_ssl_verify', false );
$headers = array();
// Include basic auth in loopback requests. Note that this will only pass along basic auth when user is
// initiating the test. If a site requires basic auth, the test will fail when it runs in WP Cron as part of
// wp_site_health_scheduled_check. This logic is copied from WP_Site_Health::can_perform_loopback().
if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
$headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
}
$caching_headers = $this->get_page_cache_headers();
$page_caching_response_headers = array();
$response_timing = array();
for ( $i = 1; $i <= 3; $i++ ) {
$start_time = microtime( true );
$http_response = wp_remote_get( home_url( '/' ), compact( 'sslverify', 'headers' ) );
$end_time = microtime( true );
if ( is_wp_error( $http_response ) ) {
return $http_response;
}
if ( wp_remote_retrieve_response_code( $http_response ) !== 200 ) {
return new WP_Error(
'http_' . wp_remote_retrieve_response_code( $http_response ),
wp_remote_retrieve_response_message( $http_response )
);
}
$response_headers = array();
foreach ( $caching_headers as $header => $callback ) {
$header_values = wp_remote_retrieve_header( $http_response, $header );
if ( empty( $header_values ) ) {
continue;
}
$header_values = (array) $header_values;
if ( empty( $callback ) || ( is_callable( $callback ) && count( array_filter( $header_values, $callback ) ) > 0 ) ) {
$response_headers[ $header ] = $header_values;
}
}
$page_caching_response_headers[] = $response_headers;
$response_timing[] = ( $end_time - $start_time ) * 1000;
}
return array(
'advanced_cache_present' => (
file_exists( WP_CONTENT_DIR . '/advanced-cache.php' )
&&
( defined( 'WP_CACHE' ) && WP_CACHE )
&&
/** This filter is documented in wp-settings.php */
apply_filters( 'enable_loading_advanced_cache_dropin', true )
),
'page_caching_response_headers' => $page_caching_response_headers,
'response_timing' => $response_timing,
);
}
```
[apply\_filters( 'enable\_loading\_advanced\_cache\_dropin', bool $enable\_advanced\_cache )](../../hooks/enable_loading_advanced_cache_dropin)
Filters whether to enable loading of the advanced-cache.php drop-in.
[apply\_filters( 'https\_local\_ssl\_verify', bool $ssl\_verify, string $url )](../../hooks/https_local_ssl_verify)
Filters whether SSL should be verified for local HTTP API requests.
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::get\_page\_cache\_headers()](get_page_cache_headers) wp-admin/includes/class-wp-site-health.php | Returns a list of headers and its verification callback to verify if page cache is enabled or not. |
| [wp\_remote\_get()](../../functions/wp_remote_get) wp-includes/http.php | Performs an HTTP request using the GET method and returns its response. |
| [wp\_remote\_retrieve\_response\_code()](../../functions/wp_remote_retrieve_response_code) wp-includes/http.php | Retrieve only the response code from the raw response. |
| [wp\_remote\_retrieve\_response\_message()](../../functions/wp_remote_retrieve_response_message) wp-includes/http.php | Retrieve only the response message from the raw response. |
| [wp\_remote\_retrieve\_header()](../../functions/wp_remote_retrieve_header) wp-includes/http.php | Retrieve a single header by name from the raw response. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_page\_cache\_detail()](get_page_cache_detail) wp-admin/includes/class-wp-site-health.php | Gets page cache details. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Site_Health::perform_test( callable $callback ): mixed|void WP\_Site\_Health::perform\_test( callable $callback ): mixed|void
=================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Runs a Site Health test directly.
`$callback` callable Required mixed|void
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
private function perform_test( $callback ) {
/**
* Filters the output of a finished Site Health test.
*
* @since 5.3.0
*
* @param array $test_result {
* An associative array of test result data.
*
* @type string $label A label describing the test, and is used as a header in the output.
* @type string $status The status of the test, which can be a value of `good`, `recommended` or `critical`.
* @type array $badge {
* Tests are put into categories which have an associated badge shown, these can be modified and assigned here.
*
* @type string $label The test label, for example `Performance`.
* @type string $color Default `blue`. A string representing a color to use for the label.
* }
* @type string $description A more descriptive explanation of what the test looks for, and why it is important for the end user.
* @type string $actions An action to direct the user to where they can resolve the issue, if one exists.
* @type string $test The name of the test being ran, used as a reference point.
* }
*/
return apply_filters( 'site_status_test_result', call_user_func( $callback ) );
}
```
[apply\_filters( 'site\_status\_test\_result', array $test\_result )](../../hooks/site_status_test_result)
Filters the output of a finished Site Health test.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::wp\_cron\_scheduled\_check()](wp_cron_scheduled_check) wp-admin/includes/class-wp-site-health.php | Runs the scheduled event to check and update the latest site health status for the website. |
| [WP\_Site\_Health::enqueue\_scripts()](enqueue_scripts) wp-admin/includes/class-wp-site-health.php | Enqueues the site health scripts. |
| Version | Description |
| --- | --- |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | Introduced. |
wordpress WP_Site_Health::get_test_authorization_header(): array WP\_Site\_Health::get\_test\_authorization\_header(): array
===========================================================
Tests if the Authorization header has the expected values.
array
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_authorization_header() {
$result = array(
'label' => __( 'The Authorization header is working as expected' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'The Authorization header is used by third-party applications you have approved for this site. Without this header, those apps cannot connect to your site.' )
),
'actions' => '',
'test' => 'authorization_header',
);
if ( ! isset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
$result['label'] = __( 'The authorization header is missing' );
} elseif ( 'user' !== $_SERVER['PHP_AUTH_USER'] || 'pwd' !== $_SERVER['PHP_AUTH_PW'] ) {
$result['label'] = __( 'The authorization header is invalid' );
} else {
return $result;
}
$result['status'] = 'recommended';
$result['description'] .= sprintf(
'<p>%s</p>',
__( 'If you are still seeing this warning after having tried the actions below, you may need to contact your hosting provider for further assistance.' )
);
if ( ! function_exists( 'got_mod_rewrite' ) ) {
require_once ABSPATH . 'wp-admin/includes/misc.php';
}
if ( got_mod_rewrite() ) {
$result['actions'] .= sprintf(
'<p><a href="%s">%s</a></p>',
esc_url( admin_url( 'options-permalink.php' ) ),
__( 'Flush permalinks' )
);
} else {
$result['actions'] .= sprintf(
'<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
__( 'https://developer.wordpress.org/rest-api/frequently-asked-questions/#why-is-authentication-not-working' ),
__( 'Learn how to configure the Authorization header.' ),
/* translators: Accessibility text. */
__( '(opens in a new tab)' )
);
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [got\_mod\_rewrite()](../../functions/got_mod_rewrite) wp-admin/includes/misc.php | Returns whether the server is running Apache with the mod\_rewrite module loaded. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Site_Health::can_perform_loopback(): object WP\_Site\_Health::can\_perform\_loopback(): object
==================================================
Runs a loopback test on the site.
Loopbacks are what WordPress uses to communicate with itself to start up WP\_Cron, scheduled posts, make sure plugin or theme edits don’t cause site failures and similar.
object The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function can_perform_loopback() {
$body = array( 'site-health' => 'loopback-test' );
$cookies = wp_unslash( $_COOKIE );
$timeout = 10; // 10 seconds.
$headers = array(
'Cache-Control' => 'no-cache',
);
/** This filter is documented in wp-includes/class-wp-http-streams.php */
$sslverify = apply_filters( 'https_local_ssl_verify', false );
// Include Basic auth in loopback requests.
if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
$headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
}
$url = site_url( 'wp-cron.php' );
/*
* A post request is used for the wp-cron.php loopback test to cause the file
* to finish early without triggering cron jobs. This has two benefits:
* - cron jobs are not triggered a second time on the site health page,
* - the loopback request finishes sooner providing a quicker result.
*
* Using a POST request causes the loopback to differ slightly to the standard
* GET request WordPress uses for wp-cron.php loopback requests but is close
* enough. See https://core.trac.wordpress.org/ticket/52547
*/
$r = wp_remote_post( $url, compact( 'body', 'cookies', 'headers', 'timeout', 'sslverify' ) );
if ( is_wp_error( $r ) ) {
return (object) array(
'status' => 'critical',
'message' => sprintf(
'%s<br>%s',
__( 'The loopback request to your site failed, this means features relying on them are not currently working as expected.' ),
sprintf(
/* translators: 1: The WordPress error message. 2: The WordPress error code. */
__( 'Error: %1$s (%2$s)' ),
$r->get_error_message(),
$r->get_error_code()
)
),
);
}
if ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
return (object) array(
'status' => 'recommended',
'message' => sprintf(
/* translators: %d: The HTTP response code returned. */
__( 'The loopback request returned an unexpected http status code, %d, it was not possible to determine if this will prevent features from working as expected.' ),
wp_remote_retrieve_response_code( $r )
),
);
}
return (object) array(
'status' => 'good',
'message' => __( 'The loopback request to your site completed successfully.' ),
);
}
```
[apply\_filters( 'https\_local\_ssl\_verify', bool $ssl\_verify, string $url )](../../hooks/https_local_ssl_verify)
Filters whether SSL should be verified for local HTTP API requests.
| Uses | Description |
| --- | --- |
| [site\_url()](../../functions/site_url) wp-includes/link-template.php | Retrieves the URL for the current site where WordPress application files (e.g. wp-blog-header.php or the wp-admin/ folder) are accessible. |
| [wp\_remote\_post()](../../functions/wp_remote_post) wp-includes/http.php | Performs an HTTP request using the POST method and returns its response. |
| [wp\_remote\_retrieve\_response\_code()](../../functions/wp_remote_retrieve_response_code) wp-includes/http.php | Retrieve only the response code from the raw response. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_test\_loopback\_requests()](get_test_loopback_requests) wp-admin/includes/class-wp-site-health.php | Tests if loopbacks work as expected. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Site_Health::get_test_php_extensions(): array WP\_Site\_Health::get\_test\_php\_extensions(): array
=====================================================
Tests if required PHP modules are installed on the host.
This test builds on the recommendations made by the WordPress Hosting Team as seen at <https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions>
array
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_php_extensions() {
$result = array(
'label' => __( 'Required and recommended modules are installed' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p><p>%s</p>',
__( 'PHP modules perform most of the tasks on the server that make your site run. Any changes to these must be made by your server administrator.' ),
sprintf(
/* translators: 1: Link to the hosting group page about recommended PHP modules. 2: Additional link attributes. 3: Accessibility text. */
__( 'The WordPress Hosting Team maintains a list of those modules, both recommended and required, in <a href="%1$s" %2$s>the team handbook%3$s</a>.' ),
/* translators: Localized team handbook, if one exists. */
esc_url( __( 'https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions' ) ),
'target="_blank" rel="noopener"',
sprintf(
' <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span>',
/* translators: Accessibility text. */
__( '(opens in a new tab)' )
)
)
),
'actions' => '',
'test' => 'php_extensions',
);
$modules = array(
'curl' => array(
'function' => 'curl_version',
'required' => false,
),
'dom' => array(
'class' => 'DOMNode',
'required' => false,
),
'exif' => array(
'function' => 'exif_read_data',
'required' => false,
),
'fileinfo' => array(
'function' => 'finfo_file',
'required' => false,
),
'hash' => array(
'function' => 'hash',
'required' => false,
),
'imagick' => array(
'extension' => 'imagick',
'required' => false,
),
'json' => array(
'function' => 'json_last_error',
'required' => true,
),
'mbstring' => array(
'function' => 'mb_check_encoding',
'required' => false,
),
'mysqli' => array(
'function' => 'mysqli_connect',
'required' => false,
),
'libsodium' => array(
'constant' => 'SODIUM_LIBRARY_VERSION',
'required' => false,
'php_bundled_version' => '7.2.0',
),
'openssl' => array(
'function' => 'openssl_encrypt',
'required' => false,
),
'pcre' => array(
'function' => 'preg_match',
'required' => false,
),
'mod_xml' => array(
'extension' => 'libxml',
'required' => false,
),
'zip' => array(
'class' => 'ZipArchive',
'required' => false,
),
'filter' => array(
'function' => 'filter_list',
'required' => false,
),
'gd' => array(
'extension' => 'gd',
'required' => false,
'fallback_for' => 'imagick',
),
'iconv' => array(
'function' => 'iconv',
'required' => false,
),
'intl' => array(
'extension' => 'intl',
'required' => false,
),
'mcrypt' => array(
'extension' => 'mcrypt',
'required' => false,
'fallback_for' => 'libsodium',
),
'simplexml' => array(
'extension' => 'simplexml',
'required' => false,
'fallback_for' => 'mod_xml',
),
'xmlreader' => array(
'extension' => 'xmlreader',
'required' => false,
'fallback_for' => 'mod_xml',
),
'zlib' => array(
'extension' => 'zlib',
'required' => false,
'fallback_for' => 'zip',
),
);
/**
* Filters the array representing all the modules we wish to test for.
*
* @since 5.2.0
* @since 5.3.0 The `$constant` and `$class` parameters were added.
*
* @param array $modules {
* An associative array of modules to test for.
*
* @type array ...$0 {
* An associative array of module properties used during testing.
* One of either `$function` or `$extension` must be provided, or they will fail by default.
*
* @type string $function Optional. A function name to test for the existence of.
* @type string $extension Optional. An extension to check if is loaded in PHP.
* @type string $constant Optional. A constant name to check for to verify an extension exists.
* @type string $class Optional. A class name to check for to verify an extension exists.
* @type bool $required Is this a required feature or not.
* @type string $fallback_for Optional. The module this module replaces as a fallback.
* }
* }
*/
$modules = apply_filters( 'site_status_test_php_modules', $modules );
$failures = array();
foreach ( $modules as $library => $module ) {
$extension_name = ( isset( $module['extension'] ) ? $module['extension'] : null );
$function_name = ( isset( $module['function'] ) ? $module['function'] : null );
$constant_name = ( isset( $module['constant'] ) ? $module['constant'] : null );
$class_name = ( isset( $module['class'] ) ? $module['class'] : null );
// If this module is a fallback for another function, check if that other function passed.
if ( isset( $module['fallback_for'] ) ) {
/*
* If that other function has a failure, mark this module as required for usual operations.
* If that other function hasn't failed, skip this test as it's only a fallback.
*/
if ( isset( $failures[ $module['fallback_for'] ] ) ) {
$module['required'] = true;
} else {
continue;
}
}
if ( ! $this->test_php_extension_availability( $extension_name, $function_name, $constant_name, $class_name )
&& ( ! isset( $module['php_bundled_version'] )
|| version_compare( PHP_VERSION, $module['php_bundled_version'], '<' ) )
) {
if ( $module['required'] ) {
$result['status'] = 'critical';
$class = 'error';
$screen_reader = __( 'Error' );
$message = sprintf(
/* translators: %s: The module name. */
__( 'The required module, %s, is not installed, or has been disabled.' ),
$library
);
} else {
$class = 'warning';
$screen_reader = __( 'Warning' );
$message = sprintf(
/* translators: %s: The module name. */
__( 'The optional module, %s, is not installed, or has been disabled.' ),
$library
);
}
if ( ! $module['required'] && 'good' === $result['status'] ) {
$result['status'] = 'recommended';
}
$failures[ $library ] = "<span class='dashicons $class'><span class='screen-reader-text'>$screen_reader</span></span> $message";
}
}
if ( ! empty( $failures ) ) {
$output = '<ul>';
foreach ( $failures as $failure ) {
$output .= sprintf(
'<li>%s</li>',
$failure
);
}
$output .= '</ul>';
}
if ( 'good' !== $result['status'] ) {
if ( 'recommended' === $result['status'] ) {
$result['label'] = __( 'One or more recommended modules are missing' );
}
if ( 'critical' === $result['status'] ) {
$result['label'] = __( 'One or more required modules are missing' );
}
$result['description'] .= $output;
}
return $result;
}
```
[apply\_filters( 'site\_status\_test\_php\_modules', array $modules )](../../hooks/site_status_test_php_modules)
Filters the array representing all the modules we wish to test for.
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::test\_php\_extension\_availability()](test_php_extension_availability) wp-admin/includes/class-wp-site-health.php | Checks if the passed extension or function are available. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Site_Health::get_test_plugin_theme_auto_updates(): array WP\_Site\_Health::get\_test\_plugin\_theme\_auto\_updates(): array
==================================================================
Tests if plugin and theme auto-updates appear to be configured correctly.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_plugin_theme_auto_updates() {
$result = array(
'label' => __( 'Plugin and theme auto-updates appear to be configured correctly' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Security' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
__( 'Plugin and theme auto-updates ensure that the latest versions are always installed.' )
),
'actions' => '',
'test' => 'plugin_theme_auto_updates',
);
$check_plugin_theme_updates = $this->detect_plugin_theme_auto_update_issues();
$result['status'] = $check_plugin_theme_updates->status;
if ( 'good' !== $result['status'] ) {
$result['label'] = __( 'Your site may have problems auto-updating plugins and themes' );
$result['description'] .= sprintf(
'<p>%s</p>',
$check_plugin_theme_updates->message
);
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::detect\_plugin\_theme\_auto\_update\_issues()](detect_plugin_theme_auto_update_issues) wp-admin/includes/class-wp-site-health.php | Checks for potential issues with plugin and theme auto-updates. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Site_Health::detect_plugin_theme_auto_update_issues(): object WP\_Site\_Health::detect\_plugin\_theme\_auto\_update\_issues(): object
=======================================================================
Checks for potential issues with plugin and theme auto-updates.
Though there is no way to 100% determine if plugin and theme auto-updates are configured correctly, a few educated guesses could be made to flag any conditions that would potentially cause unexpected behaviors.
object The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function detect_plugin_theme_auto_update_issues() {
$mock_plugin = (object) array(
'id' => 'w.org/plugins/a-fake-plugin',
'slug' => 'a-fake-plugin',
'plugin' => 'a-fake-plugin/a-fake-plugin.php',
'new_version' => '9.9',
'url' => 'https://wordpress.org/plugins/a-fake-plugin/',
'package' => 'https://downloads.wordpress.org/plugin/a-fake-plugin.9.9.zip',
'icons' => array(
'2x' => 'https://ps.w.org/a-fake-plugin/assets/icon-256x256.png',
'1x' => 'https://ps.w.org/a-fake-plugin/assets/icon-128x128.png',
),
'banners' => array(
'2x' => 'https://ps.w.org/a-fake-plugin/assets/banner-1544x500.png',
'1x' => 'https://ps.w.org/a-fake-plugin/assets/banner-772x250.png',
),
'banners_rtl' => array(),
'tested' => '5.5.0',
'requires_php' => '5.6.20',
'compatibility' => new stdClass(),
);
$mock_theme = (object) array(
'theme' => 'a-fake-theme',
'new_version' => '9.9',
'url' => 'https://wordpress.org/themes/a-fake-theme/',
'package' => 'https://downloads.wordpress.org/theme/a-fake-theme.9.9.zip',
'requires' => '5.0.0',
'requires_php' => '5.6.20',
);
$test_plugins_enabled = wp_is_auto_update_forced_for_item( 'plugin', true, $mock_plugin );
$test_themes_enabled = wp_is_auto_update_forced_for_item( 'theme', true, $mock_theme );
$ui_enabled_for_plugins = wp_is_auto_update_enabled_for_type( 'plugin' );
$ui_enabled_for_themes = wp_is_auto_update_enabled_for_type( 'theme' );
$plugin_filter_present = has_filter( 'auto_update_plugin' );
$theme_filter_present = has_filter( 'auto_update_theme' );
if ( ( ! $test_plugins_enabled && $ui_enabled_for_plugins )
|| ( ! $test_themes_enabled && $ui_enabled_for_themes )
) {
return (object) array(
'status' => 'critical',
'message' => __( 'Auto-updates for plugins and/or themes appear to be disabled, but settings are still set to be displayed. This could cause auto-updates to not work as expected.' ),
);
}
if ( ( ! $test_plugins_enabled && $plugin_filter_present )
&& ( ! $test_themes_enabled && $theme_filter_present )
) {
return (object) array(
'status' => 'recommended',
'message' => __( 'Auto-updates for plugins and themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
);
} elseif ( ! $test_plugins_enabled && $plugin_filter_present ) {
return (object) array(
'status' => 'recommended',
'message' => __( 'Auto-updates for plugins appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
);
} elseif ( ! $test_themes_enabled && $theme_filter_present ) {
return (object) array(
'status' => 'recommended',
'message' => __( 'Auto-updates for themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
);
}
return (object) array(
'status' => 'good',
'message' => __( 'There appear to be no issues with plugin and theme auto-updates.' ),
);
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_auto\_update\_forced\_for\_item()](../../functions/wp_is_auto_update_forced_for_item) wp-admin/includes/update.php | Checks whether auto-updates are forced for an item. |
| [wp\_is\_auto\_update\_enabled\_for\_type()](../../functions/wp_is_auto_update_enabled_for_type) wp-admin/includes/update.php | Checks whether auto-updates are enabled. |
| [has\_filter()](../../functions/has_filter) wp-includes/plugin.php | Checks if any filter has been registered for a hook. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_test\_plugin\_theme\_auto\_updates()](get_test_plugin_theme_auto_updates) wp-admin/includes/class-wp-site-health.php | Tests if plugin and theme auto-updates appear to be configured correctly. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Site_Health::get_test_php_sessions(): array WP\_Site\_Health::get\_test\_php\_sessions(): array
===================================================
Tests if there’s an active PHP session that can affect loopback requests.
array The test results.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
public function get_test_php_sessions() {
$result = array(
'label' => __( 'No PHP sessions detected' ),
'status' => 'good',
'badge' => array(
'label' => __( 'Performance' ),
'color' => 'blue',
),
'description' => sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: session_start(), 2: session_write_close() */
__( 'PHP sessions created by a %1$s function call may interfere with REST API and loopback requests. An active session should be closed by %2$s before making any HTTP requests.' ),
'<code>session_start()</code>',
'<code>session_write_close()</code>'
)
),
'test' => 'php_sessions',
);
if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) {
$result['status'] = 'critical';
$result['label'] = __( 'An active PHP session was detected' );
$result['description'] = sprintf(
'<p>%s</p>',
sprintf(
/* translators: 1: session_start(), 2: session_write_close() */
__( 'A PHP session was created by a %1$s function call. This interferes with REST API and loopback requests. The session should be closed by %2$s before making any HTTP requests.' ),
'<code>session_start()</code>',
'<code>session_write_close()</code>'
)
);
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Site_Health::wp_schedule_test_init() WP\_Site\_Health::wp\_schedule\_test\_init()
============================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Initiates the WP\_Cron schedule test cases.
File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/)
```
private function wp_schedule_test_init() {
$this->schedules = wp_get_schedules();
$this->get_cron_tasks();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Health::get\_cron\_tasks()](get_cron_tasks) wp-admin/includes/class-wp-site-health.php | Populates the list of cron events and store them to a class-wide variable. |
| [wp\_get\_schedules()](../../functions/wp_get_schedules) wp-includes/cron.php | Retrieve supported event recurrence schedules. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::get\_test\_scheduled\_events()](get_test_scheduled_events) wp-admin/includes/class-wp-site-health.php | Tests if scheduled events run as intended. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress Requests_Transport_cURL::__destruct() Requests\_Transport\_cURL::\_\_destruct()
=========================================
Destructor
File: `wp-includes/Requests/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/curl.php/)
```
public function __destruct() {
if (is_resource($this->handle)) {
curl_close($this->handle);
}
}
```
wordpress Requests_Transport_cURL::request_multiple( array $requests, array $options ): array Requests\_Transport\_cURL::request\_multiple( array $requests, array $options ): array
======================================================================================
Send multiple requests simultaneously
`$requests` array Required Request data `$options` array Required Global options array Array of [Requests\_Response](../requests_response) objects (may contain [Requests\_Exception](../requests_exception) or string responses as well)
File: `wp-includes/Requests/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/curl.php/)
```
public function request_multiple($requests, $options) {
// If you're not requesting, we can't get any responses ¯\_(ツ)_/¯
if (empty($requests)) {
return array();
}
$multihandle = curl_multi_init();
$subrequests = array();
$subhandles = array();
$class = get_class($this);
foreach ($requests as $id => $request) {
$subrequests[$id] = new $class();
$subhandles[$id] = $subrequests[$id]->get_subrequest_handle($request['url'], $request['headers'], $request['data'], $request['options']);
$request['options']['hooks']->dispatch('curl.before_multi_add', array(&$subhandles[$id]));
curl_multi_add_handle($multihandle, $subhandles[$id]);
}
$completed = 0;
$responses = array();
$subrequestcount = count($subrequests);
$request['options']['hooks']->dispatch('curl.before_multi_exec', array(&$multihandle));
do {
$active = 0;
do {
$status = curl_multi_exec($multihandle, $active);
}
while ($status === CURLM_CALL_MULTI_PERFORM);
$to_process = array();
// Read the information as needed
while ($done = curl_multi_info_read($multihandle)) {
$key = array_search($done['handle'], $subhandles, true);
if (!isset($to_process[$key])) {
$to_process[$key] = $done;
}
}
// Parse the finished requests before we start getting the new ones
foreach ($to_process as $key => $done) {
$options = $requests[$key]['options'];
if ($done['result'] !== CURLE_OK) {
//get error string for handle.
$reason = curl_error($done['handle']);
$exception = new Requests_Exception_Transport_cURL(
$reason,
Requests_Exception_Transport_cURL::EASY,
$done['handle'],
$done['result']
);
$responses[$key] = $exception;
$options['hooks']->dispatch('transport.internal.parse_error', array(&$responses[$key], $requests[$key]));
}
else {
$responses[$key] = $subrequests[$key]->process_response($subrequests[$key]->response_data, $options);
$options['hooks']->dispatch('transport.internal.parse_response', array(&$responses[$key], $requests[$key]));
}
curl_multi_remove_handle($multihandle, $done['handle']);
curl_close($done['handle']);
if (!is_string($responses[$key])) {
$options['hooks']->dispatch('multiple.request.complete', array(&$responses[$key], $key));
}
$completed++;
}
}
while ($active || $completed < $subrequestcount);
$request['options']['hooks']->dispatch('curl.after_multi_exec', array(&$multihandle));
curl_multi_close($multihandle);
return $responses;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception\_Transport\_cURL::\_\_construct()](../requests_exception_transport_curl/__construct) wp-includes/Requests/Exception/Transport/cURL.php | |
| programming_docs |
wordpress Requests_Transport_cURL::stream_headers( resource $handle, string $headers ): integer Requests\_Transport\_cURL::stream\_headers( resource $handle, string $headers ): integer
========================================================================================
Collect the headers as they are received
`$handle` resource Required cURL resource `$headers` string Required Header string integer Length of provided header
File: `wp-includes/Requests/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/curl.php/)
```
public function stream_headers($handle, $headers) {
// Why do we do this? cURL will send both the final response and any
// interim responses, such as a 100 Continue. We don't need that.
// (We may want to keep this somewhere just in case)
if ($this->done_headers) {
$this->headers = '';
$this->done_headers = false;
}
$this->headers .= $headers;
if ($headers === "\r\n") {
$this->done_headers = true;
}
return strlen($headers);
}
```
wordpress Requests_Transport_cURL::format_get( string $url, array|object $data ): string Requests\_Transport\_cURL::format\_get( string $url, array|object $data ): string
=================================================================================
Format a URL given GET data
`$url` string Required `$data` array|object Required Data to build query using, see <https://secure.php.net/http_build_query> string URL with data
File: `wp-includes/Requests/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/curl.php/)
```
protected static function format_get($url, $data) {
if (!empty($data)) {
$query = '';
$url_parts = parse_url($url);
if (empty($url_parts['query'])) {
$url_parts['query'] = '';
}
else {
$query = $url_parts['query'];
}
$query .= '&' . http_build_query($data, null, '&');
$query = trim($query, '&');
if (empty($url_parts['query'])) {
$url .= '?' . $query;
}
else {
$url = str_replace($url_parts['query'], $query, $url);
}
}
return $url;
}
```
| Used By | Description |
| --- | --- |
| [Requests\_Transport\_cURL::setup\_handle()](setup_handle) wp-includes/Requests/Transport/cURL.php | Setup the cURL handle for the given data |
wordpress Requests_Transport_cURL::process_response( string $response, array $options ): string|false Requests\_Transport\_cURL::process\_response( string $response, array $options ): string|false
==============================================================================================
Process a response
`$response` string Required Response data from the body `$options` array Required Request options string|false HTTP response data including headers. False if non-blocking.
File: `wp-includes/Requests/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/curl.php/)
```
public function process_response($response, $options) {
if ($options['blocking'] === false) {
$fake_headers = '';
$options['hooks']->dispatch('curl.after_request', array(&$fake_headers));
return false;
}
if ($options['filename'] !== false && $this->stream_handle) {
fclose($this->stream_handle);
$this->headers = trim($this->headers);
}
else {
$this->headers .= $response;
}
if (curl_errno($this->handle)) {
$error = sprintf(
'cURL error %s: %s',
curl_errno($this->handle),
curl_error($this->handle)
);
throw new Requests_Exception($error, 'curlerror', $this->handle);
}
$this->info = curl_getinfo($this->handle);
$options['hooks']->dispatch('curl.after_request', array(&$this->headers, &$this->info));
return $this->headers;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
| Used By | Description |
| --- | --- |
| [Requests\_Transport\_cURL::request()](request) wp-includes/Requests/Transport/cURL.php | Perform a request |
wordpress Requests_Transport_cURL::setup_handle( string $url, array $headers, string|array $data, array $options ) Requests\_Transport\_cURL::setup\_handle( string $url, array $headers, string|array $data, array $options )
===========================================================================================================
Setup the cURL handle for the given data
`$url` string Required URL to request `$headers` array Required Associative array of request headers `$data` string|array Required Data to send either as the POST body, or as parameters in the URL for a GET/HEAD `$options` array Required Request options, see [Requests::response()](../requests/response) for documentation File: `wp-includes/Requests/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/curl.php/)
```
protected function setup_handle($url, $headers, $data, $options) {
$options['hooks']->dispatch('curl.before_request', array(&$this->handle));
// Force closing the connection for old versions of cURL (<7.22).
if (!isset($headers['Connection'])) {
$headers['Connection'] = 'close';
}
/**
* Add "Expect" header.
*
* By default, cURL adds a "Expect: 100-Continue" to most requests. This header can
* add as much as a second to the time it takes for cURL to perform a request. To
* prevent this, we need to set an empty "Expect" header. To match the behaviour of
* Guzzle, we'll add the empty header to requests that are smaller than 1 MB and use
* HTTP/1.1.
*
* https://curl.se/mail/lib-2017-07/0013.html
*/
if (!isset($headers['Expect']) && $options['protocol_version'] === 1.1) {
$headers['Expect'] = $this->get_expect_header($data);
}
$headers = Requests::flatten($headers);
if (!empty($data)) {
$data_format = $options['data_format'];
if ($data_format === 'query') {
$url = self::format_get($url, $data);
$data = '';
}
elseif (!is_string($data)) {
$data = http_build_query($data, null, '&');
}
}
switch ($options['type']) {
case Requests::POST:
curl_setopt($this->handle, CURLOPT_POST, true);
curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data);
break;
case Requests::HEAD:
curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
curl_setopt($this->handle, CURLOPT_NOBODY, true);
break;
case Requests::TRACE:
curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
break;
case Requests::PATCH:
case Requests::PUT:
case Requests::DELETE:
case Requests::OPTIONS:
default:
curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
if (!empty($data)) {
curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data);
}
}
// cURL requires a minimum timeout of 1 second when using the system
// DNS resolver, as it uses `alarm()`, which is second resolution only.
// There's no way to detect which DNS resolver is being used from our
// end, so we need to round up regardless of the supplied timeout.
//
// https://github.com/curl/curl/blob/4f45240bc84a9aa648c8f7243be7b79e9f9323a5/lib/hostip.c#L606-L609
$timeout = max($options['timeout'], 1);
if (is_int($timeout) || $this->version < self::CURL_7_16_2) {
curl_setopt($this->handle, CURLOPT_TIMEOUT, ceil($timeout));
}
else {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_timeout_msFound
curl_setopt($this->handle, CURLOPT_TIMEOUT_MS, round($timeout * 1000));
}
if (is_int($options['connect_timeout']) || $this->version < self::CURL_7_16_2) {
curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT, ceil($options['connect_timeout']));
}
else {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_connecttimeout_msFound
curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT_MS, round($options['connect_timeout'] * 1000));
}
curl_setopt($this->handle, CURLOPT_URL, $url);
curl_setopt($this->handle, CURLOPT_REFERER, $url);
curl_setopt($this->handle, CURLOPT_USERAGENT, $options['useragent']);
if (!empty($headers)) {
curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers);
}
if ($options['protocol_version'] === 1.1) {
curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
}
else {
curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
}
if ($options['blocking'] === true) {
curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, array($this, 'stream_headers'));
curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, array($this, 'stream_body'));
curl_setopt($this->handle, CURLOPT_BUFFERSIZE, Requests::BUFFER_SIZE);
}
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Transport\_cURL::get\_expect\_header()](get_expect_header) wp-includes/Requests/Transport/cURL.php | Get the correct “Expect” header for the given request data. |
| [Requests::flatten()](../requests/flatten) wp-includes/class-requests.php | Convert a key => value array to a ‘key: value’ array for headers |
| [Requests\_Transport\_cURL::format\_get()](format_get) wp-includes/Requests/Transport/cURL.php | Format a URL given GET data |
| Used By | Description |
| --- | --- |
| [Requests\_Transport\_cURL::request()](request) wp-includes/Requests/Transport/cURL.php | Perform a request |
| [Requests\_Transport\_cURL::get\_subrequest\_handle()](get_subrequest_handle) wp-includes/Requests/Transport/cURL.php | Get the cURL handle for use in a multi-request |
wordpress Requests_Transport_cURL::test( $capabilities = array() ): boolean Requests\_Transport\_cURL::test( $capabilities = array() ): boolean
===================================================================
Whether this transport is valid
boolean True if the transport is valid, false otherwise.
File: `wp-includes/Requests/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/curl.php/)
```
public static function test($capabilities = array()) {
if (!function_exists('curl_init') || !function_exists('curl_exec')) {
return false;
}
// If needed, check that our installed curl version supports SSL
if (isset($capabilities['ssl']) && $capabilities['ssl']) {
$curl_version = curl_version();
if (!(CURL_VERSION_SSL & $curl_version['features'])) {
return false;
}
}
return true;
}
```
wordpress Requests_Transport_cURL::get_subrequest_handle( string $url, array $headers, string|array $data, array $options ): resource Requests\_Transport\_cURL::get\_subrequest\_handle( string $url, array $headers, string|array $data, array $options ): resource
===============================================================================================================================
Get the cURL handle for use in a multi-request
`$url` string Required URL to request `$headers` array Required Associative array of request headers `$data` string|array Required Data to send either as the POST body, or as parameters in the URL for a GET/HEAD `$options` array Required Request options, see [Requests::response()](../requests/response) for documentation resource Subrequest's cURL handle
File: `wp-includes/Requests/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/curl.php/)
```
public function &get_subrequest_handle($url, $headers, $data, $options) {
$this->setup_handle($url, $headers, $data, $options);
if ($options['filename'] !== false) {
$this->stream_handle = fopen($options['filename'], 'wb');
}
$this->response_data = '';
$this->response_bytes = 0;
$this->response_byte_limit = false;
if ($options['max_bytes'] !== false) {
$this->response_byte_limit = $options['max_bytes'];
}
$this->hooks = $options['hooks'];
return $this->handle;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Transport\_cURL::setup\_handle()](setup_handle) wp-includes/Requests/Transport/cURL.php | Setup the cURL handle for the given data |
wordpress Requests_Transport_cURL::stream_body( resource $handle, string $data ): integer Requests\_Transport\_cURL::stream\_body( resource $handle, string $data ): integer
==================================================================================
Collect data as it’s received
`$handle` resource Required cURL resource `$data` string Required Body data integer Length of provided data
File: `wp-includes/Requests/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/curl.php/)
```
public function stream_body($handle, $data) {
$this->hooks->dispatch('request.progress', array($data, $this->response_bytes, $this->response_byte_limit));
$data_length = strlen($data);
// Are we limiting the response size?
if ($this->response_byte_limit) {
if ($this->response_bytes === $this->response_byte_limit) {
// Already at maximum, move on
return $data_length;
}
if (($this->response_bytes + $data_length) > $this->response_byte_limit) {
// Limit the length
$limited_length = ($this->response_byte_limit - $this->response_bytes);
$data = substr($data, 0, $limited_length);
}
}
if ($this->stream_handle) {
fwrite($this->stream_handle, $data);
}
else {
$this->response_data .= $data;
}
$this->response_bytes += strlen($data);
return $data_length;
}
```
| Version | Description |
| --- | --- |
| [1.6.1](https://developer.wordpress.org/reference/since/1.6.1/) | Introduced. |
wordpress Requests_Transport_cURL::__construct() Requests\_Transport\_cURL::\_\_construct()
==========================================
Constructor
File: `wp-includes/Requests/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/curl.php/)
```
public function __construct() {
$curl = curl_version();
$this->version = $curl['version_number'];
$this->handle = curl_init();
curl_setopt($this->handle, CURLOPT_HEADER, false);
curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, 1);
if ($this->version >= self::CURL_7_10_5) {
curl_setopt($this->handle, CURLOPT_ENCODING, '');
}
if (defined('CURLOPT_PROTOCOLS')) {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_protocolsFound
curl_setopt($this->handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
}
if (defined('CURLOPT_REDIR_PROTOCOLS')) {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_redir_protocolsFound
curl_setopt($this->handle, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
}
}
```
wordpress Requests_Transport_cURL::request( string $url, array $headers = array(), string|array $data = array(), array $options = array() ): string Requests\_Transport\_cURL::request( string $url, array $headers = array(), string|array $data = array(), array $options = array() ): string
===========================================================================================================================================
Perform a request
`$url` string Required URL to request `$headers` array Optional Associative array of request headers Default: `array()`
`$data` string|array Optional Data to send either as the POST body, or as parameters in the URL for a GET/HEAD Default: `array()`
`$options` array Optional Request options, see [Requests::response()](../requests/response) for documentation Default: `array()`
string Raw HTTP result
File: `wp-includes/Requests/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/curl.php/)
```
public function request($url, $headers = array(), $data = array(), $options = array()) {
$this->hooks = $options['hooks'];
$this->setup_handle($url, $headers, $data, $options);
$options['hooks']->dispatch('curl.before_send', array(&$this->handle));
if ($options['filename'] !== false) {
$this->stream_handle = fopen($options['filename'], 'wb');
}
$this->response_data = '';
$this->response_bytes = 0;
$this->response_byte_limit = false;
if ($options['max_bytes'] !== false) {
$this->response_byte_limit = $options['max_bytes'];
}
if (isset($options['verify'])) {
if ($options['verify'] === false) {
curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($this->handle, CURLOPT_SSL_VERIFYPEER, 0);
}
elseif (is_string($options['verify'])) {
curl_setopt($this->handle, CURLOPT_CAINFO, $options['verify']);
}
}
if (isset($options['verifyname']) && $options['verifyname'] === false) {
curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0);
}
curl_exec($this->handle);
$response = $this->response_data;
$options['hooks']->dispatch('curl.after_send', array());
if (curl_errno($this->handle) === 23 || curl_errno($this->handle) === 61) {
// Reset encoding and try again
curl_setopt($this->handle, CURLOPT_ENCODING, 'none');
$this->response_data = '';
$this->response_bytes = 0;
curl_exec($this->handle);
$response = $this->response_data;
}
$this->process_response($response, $options);
// Need to remove the $this reference from the curl handle.
// Otherwise Requests_Transport_cURL wont be garbage collected and the curl_close() will never be called.
curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, null);
curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, null);
return $this->headers;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Transport\_cURL::process\_response()](process_response) wp-includes/Requests/Transport/cURL.php | Process a response |
| [Requests\_Transport\_cURL::setup\_handle()](setup_handle) wp-includes/Requests/Transport/cURL.php | Setup the cURL handle for the given data |
wordpress Requests_Transport_cURL::get_expect_header( string|array $data ): string Requests\_Transport\_cURL::get\_expect\_header( string|array $data ): string
============================================================================
Get the correct “Expect” header for the given request data.
`$data` string|array Required Data to send either as the POST body, or as parameters in the URL for a GET/HEAD. string The "Expect" header.
File: `wp-includes/Requests/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/curl.php/)
```
protected function get_expect_header($data) {
if (!is_array($data)) {
return strlen((string) $data) >= 1048576 ? '100-Continue' : '';
}
$bytesize = 0;
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
foreach ($iterator as $datum) {
$bytesize += strlen((string) $datum);
if ($bytesize >= 1048576) {
return '100-Continue';
}
}
return '';
}
```
| Used By | Description |
| --- | --- |
| [Requests\_Transport\_cURL::setup\_handle()](setup_handle) wp-includes/Requests/Transport/cURL.php | Setup the cURL handle for the given data |
wordpress Plural_Forms::execute( int $n ): int Plural\_Forms::execute( int $n ): int
=====================================
Execute the plural form function.
`$n` int Required Variable "n" to substitute. int Plural form value.
File: `wp-includes/pomo/plural-forms.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/plural-forms.php/)
```
public function execute( $n ) {
$stack = array();
$i = 0;
$total = count( $this->tokens );
while ( $i < $total ) {
$next = $this->tokens[ $i ];
$i++;
if ( 'var' === $next[0] ) {
$stack[] = $n;
continue;
} elseif ( 'value' === $next[0] ) {
$stack[] = $next[1];
continue;
}
// Only operators left.
switch ( $next[1] ) {
case '%':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 % $v2;
break;
case '||':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 || $v2;
break;
case '&&':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 && $v2;
break;
case '<':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 < $v2;
break;
case '<=':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 <= $v2;
break;
case '>':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 > $v2;
break;
case '>=':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 >= $v2;
break;
case '!=':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 != $v2;
break;
case '==':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 == $v2;
break;
case '?:':
$v3 = array_pop( $stack );
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 ? $v2 : $v3;
break;
default:
throw new Exception( sprintf( 'Unknown operator "%s"', $next[1] ) );
}
}
if ( count( $stack ) !== 1 ) {
throw new Exception( 'Too many values remaining on the stack' );
}
return (int) $stack[0];
}
```
| Used By | Description |
| --- | --- |
| [Plural\_Forms::get()](get) wp-includes/pomo/plural-forms.php | Get the plural form for a number. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
| programming_docs |
wordpress Plural_Forms::__construct( string $str ) Plural\_Forms::\_\_construct( string $str )
===========================================
Constructor.
`$str` string Required Plural function (just the bit after `plural=` from Plural-Forms) File: `wp-includes/pomo/plural-forms.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/plural-forms.php/)
```
public function __construct( $str ) {
$this->parse( $str );
}
```
| Uses | Description |
| --- | --- |
| [Plural\_Forms::parse()](parse) wp-includes/pomo/plural-forms.php | Parse a Plural-Forms string into tokens. |
| Used By | Description |
| --- | --- |
| [Gettext\_Translations::make\_plural\_form\_function()](../gettext_translations/make_plural_form_function) wp-includes/pomo/translations.php | Makes a function, which will return the right translation index, according to the plural forms header |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress Plural_Forms::parse( string $str ) Plural\_Forms::parse( string $str )
===================================
Parse a Plural-Forms string into tokens.
Uses the shunting-yard algorithm to convert the string to Reverse Polish Notation tokens.
`$str` string Required String to parse. File: `wp-includes/pomo/plural-forms.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/plural-forms.php/)
```
protected function parse( $str ) {
$pos = 0;
$len = strlen( $str );
// Convert infix operators to postfix using the shunting-yard algorithm.
$output = array();
$stack = array();
while ( $pos < $len ) {
$next = substr( $str, $pos, 1 );
switch ( $next ) {
// Ignore whitespace.
case ' ':
case "\t":
$pos++;
break;
// Variable (n).
case 'n':
$output[] = array( 'var' );
$pos++;
break;
// Parentheses.
case '(':
$stack[] = $next;
$pos++;
break;
case ')':
$found = false;
while ( ! empty( $stack ) ) {
$o2 = $stack[ count( $stack ) - 1 ];
if ( '(' !== $o2 ) {
$output[] = array( 'op', array_pop( $stack ) );
continue;
}
// Discard open paren.
array_pop( $stack );
$found = true;
break;
}
if ( ! $found ) {
throw new Exception( 'Mismatched parentheses' );
}
$pos++;
break;
// Operators.
case '|':
case '&':
case '>':
case '<':
case '!':
case '=':
case '%':
case '?':
$end_operator = strspn( $str, self::OP_CHARS, $pos );
$operator = substr( $str, $pos, $end_operator );
if ( ! array_key_exists( $operator, self::$op_precedence ) ) {
throw new Exception( sprintf( 'Unknown operator "%s"', $operator ) );
}
while ( ! empty( $stack ) ) {
$o2 = $stack[ count( $stack ) - 1 ];
// Ternary is right-associative in C.
if ( '?:' === $operator || '?' === $operator ) {
if ( self::$op_precedence[ $operator ] >= self::$op_precedence[ $o2 ] ) {
break;
}
} elseif ( self::$op_precedence[ $operator ] > self::$op_precedence[ $o2 ] ) {
break;
}
$output[] = array( 'op', array_pop( $stack ) );
}
$stack[] = $operator;
$pos += $end_operator;
break;
// Ternary "else".
case ':':
$found = false;
$s_pos = count( $stack ) - 1;
while ( $s_pos >= 0 ) {
$o2 = $stack[ $s_pos ];
if ( '?' !== $o2 ) {
$output[] = array( 'op', array_pop( $stack ) );
$s_pos--;
continue;
}
// Replace.
$stack[ $s_pos ] = '?:';
$found = true;
break;
}
if ( ! $found ) {
throw new Exception( 'Missing starting "?" ternary operator' );
}
$pos++;
break;
// Default - number or invalid.
default:
if ( $next >= '0' && $next <= '9' ) {
$span = strspn( $str, self::NUM_CHARS, $pos );
$output[] = array( 'value', intval( substr( $str, $pos, $span ) ) );
$pos += $span;
break;
}
throw new Exception( sprintf( 'Unknown symbol "%s"', $next ) );
}
}
while ( ! empty( $stack ) ) {
$o2 = array_pop( $stack );
if ( '(' === $o2 || ')' === $o2 ) {
throw new Exception( 'Mismatched parentheses' );
}
$output[] = array( 'op', $o2 );
}
$this->tokens = $output;
}
```
| Used By | Description |
| --- | --- |
| [Plural\_Forms::\_\_construct()](__construct) wp-includes/pomo/plural-forms.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress Plural_Forms::get( int $num ): int Plural\_Forms::get( int $num ): int
===================================
Get the plural form for a number.
Caches the value for repeated calls.
`$num` int Required Number to get plural form for. int Plural form value.
File: `wp-includes/pomo/plural-forms.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/plural-forms.php/)
```
public function get( $num ) {
if ( isset( $this->cache[ $num ] ) ) {
return $this->cache[ $num ];
}
$this->cache[ $num ] = $this->execute( $num );
return $this->cache[ $num ];
}
```
| Uses | Description |
| --- | --- |
| [Plural\_Forms::execute()](execute) wp-includes/pomo/plural-forms.php | Execute the plural form function. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Theme_Install_List_Table::single_row( stdClass $theme ) WP\_Theme\_Install\_List\_Table::single\_row( stdClass $theme )
===============================================================
Prints a theme from the WordPress.org API.
`$theme` stdClass Required An object that contains theme data returned by the WordPress.org API.
* `name`stringTheme name, e.g. 'Twenty Twenty-One'.
* `slug`stringTheme slug, e.g. `'twentytwentyone'`.
* `version`stringTheme version, e.g. `'1.1'`.
* `author`stringTheme author username, e.g. `'melchoyce'`.
* `preview_url`stringPreview URL, e.g. `<a href="https://2021.wordpress.net/">https://2021.wordpress.net/</a>`.
* `screenshot_url`stringScreenshot URL, e.g. `<a href="https://wordpress.org/themes/twentytwentyone/">https://wordpress.org/themes/twentytwentyone/</a>`.
* `rating`floatRating score.
* `num_ratings`intThe number of ratings.
* `homepage`stringTheme homepage, e.g. `<a href="https://wordpress.org/themes/twentytwentyone/">https://wordpress.org/themes/twentytwentyone/</a>`.
* `description`stringTheme description.
* `download_link`stringTheme ZIP download URL.
File: `wp-admin/includes/class-wp-theme-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-theme-install-list-table.php/)
```
public function single_row( $theme ) {
global $themes_allowedtags;
if ( empty( $theme ) ) {
return;
}
$name = wp_kses( $theme->name, $themes_allowedtags );
$author = wp_kses( $theme->author, $themes_allowedtags );
/* translators: %s: Theme name. */
$preview_title = sprintf( __( 'Preview “%s”' ), $name );
$preview_url = add_query_arg(
array(
'tab' => 'theme-information',
'theme' => $theme->slug,
),
self_admin_url( 'theme-install.php' )
);
$actions = array();
$install_url = add_query_arg(
array(
'action' => 'install-theme',
'theme' => $theme->slug,
),
self_admin_url( 'update.php' )
);
$update_url = add_query_arg(
array(
'action' => 'upgrade-theme',
'theme' => $theme->slug,
),
self_admin_url( 'update.php' )
);
$status = $this->_get_theme_status( $theme );
switch ( $status ) {
case 'update_available':
$actions[] = sprintf(
'<a class="install-now" href="%s" title="%s">%s</a>',
esc_url( wp_nonce_url( $update_url, 'upgrade-theme_' . $theme->slug ) ),
/* translators: %s: Theme version. */
esc_attr( sprintf( __( 'Update to version %s' ), $theme->version ) ),
__( 'Update' )
);
break;
case 'newer_installed':
case 'latest_installed':
$actions[] = sprintf(
'<span class="install-now" title="%s">%s</span>',
esc_attr__( 'This theme is already installed and is up to date' ),
_x( 'Installed', 'theme' )
);
break;
case 'install':
default:
$actions[] = sprintf(
'<a class="install-now" href="%s" title="%s">%s</a>',
esc_url( wp_nonce_url( $install_url, 'install-theme_' . $theme->slug ) ),
/* translators: %s: Theme name. */
esc_attr( sprintf( _x( 'Install %s', 'theme' ), $name ) ),
__( 'Install Now' )
);
break;
}
$actions[] = sprintf(
'<a class="install-theme-preview" href="%s" title="%s">%s</a>',
esc_url( $preview_url ),
/* translators: %s: Theme name. */
esc_attr( sprintf( __( 'Preview %s' ), $name ) ),
__( 'Preview' )
);
/**
* Filters the install action links for a theme in the Install Themes list table.
*
* @since 3.4.0
*
* @param string[] $actions An array of theme action links. Defaults are
* links to Install Now, Preview, and Details.
* @param stdClass $theme An object that contains theme data returned by the
* WordPress.org API.
*/
$actions = apply_filters( 'theme_install_actions', $actions, $theme );
?>
<a class="screenshot install-theme-preview" href="<?php echo esc_url( $preview_url ); ?>" title="<?php echo esc_attr( $preview_title ); ?>">
<img src="<?php echo esc_url( $theme->screenshot_url . '?ver=' . $theme->version ); ?>" width="150" alt="" />
</a>
<h3><?php echo $name; ?></h3>
<div class="theme-author">
<?php
/* translators: %s: Theme author. */
printf( __( 'By %s' ), $author );
?>
</div>
<div class="action-links">
<ul>
<?php foreach ( $actions as $action ) : ?>
<li><?php echo $action; ?></li>
<?php endforeach; ?>
<li class="hide-if-no-js"><a href="#" class="theme-detail"><?php _e( 'Details' ); ?></a></li>
</ul>
</div>
<?php
$this->install_theme_info( $theme );
}
```
[apply\_filters( 'theme\_install\_actions', string[] $actions, stdClass $theme )](../../hooks/theme_install_actions)
Filters the install action links for a theme in the Install Themes list table.
| Uses | Description |
| --- | --- |
| [WP\_Theme\_Install\_List\_Table::\_get\_theme\_status()](_get_theme_status) wp-admin/includes/class-wp-theme-install-list-table.php | Check to see if the theme is already installed. |
| [WP\_Theme\_Install\_List\_Table::install\_theme\_info()](install_theme_info) wp-admin/includes/class-wp-theme-install-list-table.php | Prints the info for a theme (to be used in the theme installer modal). |
| [esc\_attr\_\_()](../../functions/esc_attr__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in an attribute. |
| [wp\_kses()](../../functions/wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| [self\_admin\_url()](../../functions/self_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for either the current site or the network depending on context. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [wp\_nonce\_url()](../../functions/wp_nonce_url) wp-includes/functions.php | Retrieves URL with nonce added to URL query. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Theme\_Install\_List\_Table::display\_rows()](display_rows) wp-admin/includes/class-wp-theme-install-list-table.php | |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Theme_Install_List_Table::theme_installer_single( stdClass $theme ) WP\_Theme\_Install\_List\_Table::theme\_installer\_single( stdClass $theme )
============================================================================
Prints the wrapper for the theme installer with a provided theme’s data.
Used to make the theme installer work for no-js.
`$theme` stdClass Required A WordPress.org Theme API object. File: `wp-admin/includes/class-wp-theme-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-theme-install-list-table.php/)
```
public function theme_installer_single( $theme ) {
?>
<div id="theme-installer" class="wp-full-overlay single-theme">
<div class="wp-full-overlay-sidebar">
<?php $this->install_theme_info( $theme ); ?>
</div>
<div class="wp-full-overlay-main">
<iframe src="<?php echo esc_url( $theme->preview_url ); ?>"></iframe>
</div>
</div>
<?php
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme\_Install\_List\_Table::install\_theme\_info()](install_theme_info) wp-admin/includes/class-wp-theme-install-list-table.php | Prints the info for a theme (to be used in the theme installer modal). |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
wordpress WP_Theme_Install_List_Table::prepare_items() WP\_Theme\_Install\_List\_Table::prepare\_items()
=================================================
File: `wp-admin/includes/class-wp-theme-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-theme-install-list-table.php/)
```
public function prepare_items() {
require ABSPATH . 'wp-admin/includes/theme-install.php';
global $tabs, $tab, $paged, $type, $theme_field_defaults;
wp_reset_vars( array( 'tab' ) );
$search_terms = array();
$search_string = '';
if ( ! empty( $_REQUEST['s'] ) ) {
$search_string = strtolower( wp_unslash( $_REQUEST['s'] ) );
$search_terms = array_unique( array_filter( array_map( 'trim', explode( ',', $search_string ) ) ) );
}
if ( ! empty( $_REQUEST['features'] ) ) {
$this->features = $_REQUEST['features'];
}
$paged = $this->get_pagenum();
$per_page = 36;
// These are the tabs which are shown on the page,
$tabs = array();
$tabs['dashboard'] = __( 'Search' );
if ( 'search' === $tab ) {
$tabs['search'] = __( 'Search Results' );
}
$tabs['upload'] = __( 'Upload' );
$tabs['featured'] = _x( 'Featured', 'themes' );
//$tabs['popular'] = _x( 'Popular', 'themes' );
$tabs['new'] = _x( 'Latest', 'themes' );
$tabs['updated'] = _x( 'Recently Updated', 'themes' );
$nonmenu_tabs = array( 'theme-information' ); // Valid actions to perform which do not have a Menu item.
/** This filter is documented in wp-admin/theme-install.php */
$tabs = apply_filters( 'install_themes_tabs', $tabs );
/**
* Filters tabs not associated with a menu item on the Install Themes screen.
*
* @since 2.8.0
*
* @param string[] $nonmenu_tabs The tabs that don't have a menu item on
* the Install Themes screen.
*/
$nonmenu_tabs = apply_filters( 'install_themes_nonmenu_tabs', $nonmenu_tabs );
// If a non-valid menu tab has been selected, And it's not a non-menu action.
if ( empty( $tab ) || ( ! isset( $tabs[ $tab ] ) && ! in_array( $tab, (array) $nonmenu_tabs, true ) ) ) {
$tab = key( $tabs );
}
$args = array(
'page' => $paged,
'per_page' => $per_page,
'fields' => $theme_field_defaults,
);
switch ( $tab ) {
case 'search':
$type = isset( $_REQUEST['type'] ) ? wp_unslash( $_REQUEST['type'] ) : 'term';
switch ( $type ) {
case 'tag':
$args['tag'] = array_map( 'sanitize_key', $search_terms );
break;
case 'term':
$args['search'] = $search_string;
break;
case 'author':
$args['author'] = $search_string;
break;
}
if ( ! empty( $this->features ) ) {
$args['tag'] = $this->features;
$_REQUEST['s'] = implode( ',', $this->features );
$_REQUEST['type'] = 'tag';
}
add_action( 'install_themes_table_header', 'install_theme_search_form', 10, 0 );
break;
case 'featured':
// case 'popular':
case 'new':
case 'updated':
$args['browse'] = $tab;
break;
default:
$args = false;
break;
}
/**
* Filters API request arguments for each Install Themes screen tab.
*
* The dynamic portion of the hook name, `$tab`, refers to the theme install
* tab.
*
* Possible hook names include:
*
* - `install_themes_table_api_args_dashboard`
* - `install_themes_table_api_args_featured`
* - `install_themes_table_api_args_new`
* - `install_themes_table_api_args_search`
* - `install_themes_table_api_args_updated`
* - `install_themes_table_api_args_upload`
*
* @since 3.7.0
*
* @param array|false $args Theme install API arguments.
*/
$args = apply_filters( "install_themes_table_api_args_{$tab}", $args );
if ( ! $args ) {
return;
}
$api = themes_api( 'query_themes', $args );
if ( is_wp_error( $api ) ) {
wp_die( '<p>' . $api->get_error_message() . '</p> <p><a href="#" onclick="document.location.reload(); return false;">' . __( 'Try Again' ) . '</a></p>' );
}
$this->items = $api->themes;
$this->set_pagination_args(
array(
'total_items' => $api->info['results'],
'per_page' => $args['per_page'],
'infinite_scroll' => true,
)
);
}
```
[apply\_filters( 'install\_themes\_nonmenu\_tabs', string[] $nonmenu\_tabs )](../../hooks/install_themes_nonmenu_tabs)
Filters tabs not associated with a menu item on the Install Themes screen.
[apply\_filters( "install\_themes\_table\_api\_args\_{$tab}", array|false $args )](../../hooks/install_themes_table_api_args_tab)
Filters API request arguments for each Install Themes screen tab.
[apply\_filters( 'install\_themes\_tabs', string[] $tabs )](../../hooks/install_themes_tabs)
Filters the tabs shown on the Add Themes screen.
| Uses | Description |
| --- | --- |
| [themes\_api()](../../functions/themes_api) wp-admin/includes/theme.php | Retrieves theme installer pages from the WordPress.org Themes API. |
| [wp\_reset\_vars()](../../functions/wp_reset_vars) wp-admin/includes/misc.php | Resets global variables based on $\_GET and $\_POST. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
wordpress WP_Theme_Install_List_Table::ajax_user_can(): bool WP\_Theme\_Install\_List\_Table::ajax\_user\_can(): bool
========================================================
bool
File: `wp-admin/includes/class-wp-theme-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-theme-install-list-table.php/)
```
public function ajax_user_can() {
return current_user_can( 'install_themes' );
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| programming_docs |
wordpress WP_Theme_Install_List_Table::display_rows() WP\_Theme\_Install\_List\_Table::display\_rows()
================================================
File: `wp-admin/includes/class-wp-theme-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-theme-install-list-table.php/)
```
public function display_rows() {
$themes = $this->items;
foreach ( $themes as $theme ) {
?>
<div class="available-theme installable-theme">
<?php
$this->single_row( $theme );
?>
</div>
<?php
} // End foreach $theme_names.
$this->theme_installer();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme\_Install\_List\_Table::single\_row()](single_row) wp-admin/includes/class-wp-theme-install-list-table.php | Prints a theme from the WordPress.org API. |
| [WP\_Theme\_Install\_List\_Table::theme\_installer()](theme_installer) wp-admin/includes/class-wp-theme-install-list-table.php | Prints the wrapper for the theme installer. |
wordpress WP_Theme_Install_List_Table::no_items() WP\_Theme\_Install\_List\_Table::no\_items()
============================================
File: `wp-admin/includes/class-wp-theme-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-theme-install-list-table.php/)
```
public function no_items() {
_e( 'No themes match your request.' );
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
wordpress WP_Theme_Install_List_Table::_js_vars( array $extra_args = array() ) WP\_Theme\_Install\_List\_Table::\_js\_vars( array $extra\_args = array() )
===========================================================================
Send required variables to JavaScript land
`$extra_args` array Optional Unused. Default: `array()`
File: `wp-admin/includes/class-wp-theme-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-theme-install-list-table.php/)
```
public function _js_vars( $extra_args = array() ) {
global $tab, $type;
parent::_js_vars( compact( 'tab', 'type' ) );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Themes\_List\_Table::\_js\_vars()](../wp_themes_list_table/_js_vars) wp-admin/includes/class-wp-themes-list-table.php | Send required variables to JavaScript land |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme_Install_List_Table::theme_installer() WP\_Theme\_Install\_List\_Table::theme\_installer()
===================================================
Prints the wrapper for the theme installer.
File: `wp-admin/includes/class-wp-theme-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-theme-install-list-table.php/)
```
public function theme_installer() {
?>
<div id="theme-installer" class="wp-full-overlay expanded">
<div class="wp-full-overlay-sidebar">
<div class="wp-full-overlay-header">
<a href="#" class="close-full-overlay button"><?php _e( 'Close' ); ?></a>
<span class="theme-install"></span>
</div>
<div class="wp-full-overlay-sidebar-content">
<div class="install-theme-info"></div>
</div>
<div class="wp-full-overlay-footer">
<button type="button" class="collapse-sidebar button" aria-expanded="true" aria-label="<?php esc_attr_e( 'Collapse Sidebar' ); ?>">
<span class="collapse-sidebar-arrow"></span>
<span class="collapse-sidebar-label"><?php _e( 'Collapse' ); ?></span>
</button>
</div>
</div>
<div class="wp-full-overlay-main"></div>
</div>
<?php
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr\_e()](../../functions/esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| Used By | Description |
| --- | --- |
| [WP\_Theme\_Install\_List\_Table::display\_rows()](display_rows) wp-admin/includes/class-wp-theme-install-list-table.php | |
wordpress WP_Theme_Install_List_Table::get_views(): array WP\_Theme\_Install\_List\_Table::get\_views(): array
====================================================
array
File: `wp-admin/includes/class-wp-theme-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-theme-install-list-table.php/)
```
protected function get_views() {
global $tabs, $tab;
$display_tabs = array();
foreach ( (array) $tabs as $action => $text ) {
$display_tabs[ 'theme-install-' . $action ] = array(
'url' => self_admin_url( 'theme-install.php?tab=' . $action ),
'label' => $text,
'current' => $action === $tab,
);
}
return $this->get_views_links( $display_tabs );
}
```
| Uses | Description |
| --- | --- |
| [self\_admin\_url()](../../functions/self_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for either the current site or the network depending on context. |
wordpress WP_Theme_Install_List_Table::display() WP\_Theme\_Install\_List\_Table::display()
==========================================
Displays the theme install table.
Overrides the parent display() method to provide a different container.
File: `wp-admin/includes/class-wp-theme-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-theme-install-list-table.php/)
```
public function display() {
wp_nonce_field( 'fetch-list-' . get_class( $this ), '_ajax_fetch_list_nonce' );
?>
<div class="tablenav top themes">
<div class="alignleft actions">
<?php
/**
* Fires in the Install Themes list table header.
*
* @since 2.8.0
*/
do_action( 'install_themes_table_header' );
?>
</div>
<?php $this->pagination( 'top' ); ?>
<br class="clear" />
</div>
<div id="availablethemes">
<?php $this->display_rows_or_placeholder(); ?>
</div>
<?php
$this->tablenav( 'bottom' );
}
```
[do\_action( 'install\_themes\_table\_header' )](../../hooks/install_themes_table_header)
Fires in the Install Themes list table header.
| Uses | Description |
| --- | --- |
| [wp\_nonce\_field()](../../functions/wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Theme_Install_List_Table::install_theme_info( stdClass $theme ) WP\_Theme\_Install\_List\_Table::install\_theme\_info( stdClass $theme )
========================================================================
Prints the info for a theme (to be used in the theme installer modal).
`$theme` stdClass Required A WordPress.org Theme API object. File: `wp-admin/includes/class-wp-theme-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-theme-install-list-table.php/)
```
public function install_theme_info( $theme ) {
global $themes_allowedtags;
if ( empty( $theme ) ) {
return;
}
$name = wp_kses( $theme->name, $themes_allowedtags );
$author = wp_kses( $theme->author, $themes_allowedtags );
$install_url = add_query_arg(
array(
'action' => 'install-theme',
'theme' => $theme->slug,
),
self_admin_url( 'update.php' )
);
$update_url = add_query_arg(
array(
'action' => 'upgrade-theme',
'theme' => $theme->slug,
),
self_admin_url( 'update.php' )
);
$status = $this->_get_theme_status( $theme );
?>
<div class="install-theme-info">
<?php
switch ( $status ) {
case 'update_available':
printf(
'<a class="theme-install button button-primary" href="%s" title="%s">%s</a>',
esc_url( wp_nonce_url( $update_url, 'upgrade-theme_' . $theme->slug ) ),
/* translators: %s: Theme version. */
esc_attr( sprintf( __( 'Update to version %s' ), $theme->version ) ),
__( 'Update' )
);
break;
case 'newer_installed':
case 'latest_installed':
printf(
'<span class="theme-install" title="%s">%s</span>',
esc_attr__( 'This theme is already installed and is up to date' ),
_x( 'Installed', 'theme' )
);
break;
case 'install':
default:
printf(
'<a class="theme-install button button-primary" href="%s">%s</a>',
esc_url( wp_nonce_url( $install_url, 'install-theme_' . $theme->slug ) ),
__( 'Install' )
);
break;
}
?>
<h3 class="theme-name"><?php echo $name; ?></h3>
<span class="theme-by">
<?php
/* translators: %s: Theme author. */
printf( __( 'By %s' ), $author );
?>
</span>
<?php if ( isset( $theme->screenshot_url ) ) : ?>
<img class="theme-screenshot" src="<?php echo esc_url( $theme->screenshot_url . '?ver=' . $theme->version ); ?>" alt="" />
<?php endif; ?>
<div class="theme-details">
<?php
wp_star_rating(
array(
'rating' => $theme->rating,
'type' => 'percent',
'number' => $theme->num_ratings,
)
);
?>
<div class="theme-version">
<strong><?php _e( 'Version:' ); ?> </strong>
<?php echo wp_kses( $theme->version, $themes_allowedtags ); ?>
</div>
<div class="theme-description">
<?php echo wp_kses( $theme->description, $themes_allowedtags ); ?>
</div>
</div>
<input class="theme-preview-url" type="hidden" value="<?php echo esc_url( $theme->preview_url ); ?>" />
</div>
<?php
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme\_Install\_List\_Table::\_get\_theme\_status()](_get_theme_status) wp-admin/includes/class-wp-theme-install-list-table.php | Check to see if the theme is already installed. |
| [wp\_star\_rating()](../../functions/wp_star_rating) wp-admin/includes/template.php | Outputs a HTML element with a star rating for a given rating. |
| [esc\_attr\_\_()](../../functions/esc_attr__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in an attribute. |
| [wp\_kses()](../../functions/wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| [self\_admin\_url()](../../functions/self_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for either the current site or the network depending on context. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [wp\_nonce\_url()](../../functions/wp_nonce_url) wp-includes/functions.php | Retrieves URL with nonce added to URL query. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| Used By | Description |
| --- | --- |
| [WP\_Theme\_Install\_List\_Table::single\_row()](single_row) wp-admin/includes/class-wp-theme-install-list-table.php | Prints a theme from the WordPress.org API. |
| [WP\_Theme\_Install\_List\_Table::theme\_installer\_single()](theme_installer_single) wp-admin/includes/class-wp-theme-install-list-table.php | Prints the wrapper for the theme installer with a provided theme’s data. |
wordpress WP_Theme_Install_List_Table::_get_theme_status( stdClass $theme ): string WP\_Theme\_Install\_List\_Table::\_get\_theme\_status( stdClass $theme ): string
================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Check to see if the theme is already installed.
`$theme` stdClass Required A WordPress.org Theme API object. string Theme status.
File: `wp-admin/includes/class-wp-theme-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-theme-install-list-table.php/)
```
private function _get_theme_status( $theme ) {
$status = 'install';
$installed_theme = wp_get_theme( $theme->slug );
if ( $installed_theme->exists() ) {
if ( version_compare( $installed_theme->get( 'Version' ), $theme->version, '=' ) ) {
$status = 'latest_installed';
} elseif ( version_compare( $installed_theme->get( 'Version' ), $theme->version, '>' ) ) {
$status = 'newer_installed';
} else {
$status = 'update_available';
}
}
return $status;
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| Used By | Description |
| --- | --- |
| [WP\_Theme\_Install\_List\_Table::install\_theme\_info()](install_theme_info) wp-admin/includes/class-wp-theme-install-list-table.php | Prints the info for a theme (to be used in the theme installer modal). |
| [WP\_Theme\_Install\_List\_Table::single\_row()](single_row) wp-admin/includes/class-wp-theme-install-list-table.php | Prints a theme from the WordPress.org API. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress POP3::reset() POP3::reset()
=============
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function reset () {
// Resets the status of the remote server. This includes
// resetting the status of ALL msgs to not be deleted.
// This method automatically closes the connection to the server.
if(!isset($this->FP))
{
$this->ERROR = "POP3 reset: " . _("No connection to server");
return false;
}
$reply = $this->send_cmd("RSET");
if(!$this->is_ok($reply))
{
// The POP3 RSET command -never- gives a -ERR
// response - if it ever does, something truly
// wild is going on.
$this->ERROR = "POP3 reset: " . _("Error ") . "[$reply]";
@error_log("POP3 reset: ERROR [$reply]",0);
}
$this->quit();
return true;
}
```
| Uses | Description |
| --- | --- |
| [POP3::send\_cmd()](send_cmd) wp-includes/class-pop3.php | |
| [POP3::is\_ok()](is_ok) wp-includes/class-pop3.php | |
| [POP3::quit()](quit) wp-includes/class-pop3.php | |
wordpress POP3::popstat() POP3::popstat()
===============
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function popstat () {
// Returns an array of 2 elements. The number of undeleted
// msgs in the mailbox, and the size of the mbox in octets.
$PopArray = $this->last("array");
if($PopArray == -1) { return false; }
if( (!$PopArray) or (empty($PopArray)) )
{
return false;
}
return $PopArray;
}
```
| Uses | Description |
| --- | --- |
| [POP3::last()](last) wp-includes/class-pop3.php | |
wordpress POP3::last( $type = "count" ) POP3::last( $type = "count" )
=============================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function last ( $type = "count" ) {
// Returns the highest msg number in the mailbox.
// returns -1 on error, 0+ on success, if type != count
// results in a popstat() call (2 element array returned)
$last = -1;
if(!isset($this->FP))
{
$this->ERROR = "POP3 last: " . _("No connection to server");
return $last;
}
$reply = $this->send_cmd("STAT");
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 last: " . _("Error ") . "[$reply]";
return $last;
}
$Vars = preg_split('/\s+/',$reply);
$count = $Vars[1];
$size = $Vars[2];
settype($count,"integer");
settype($size,"integer");
if($type != "count")
{
return array($count,$size);
}
return $count;
}
```
| Uses | Description |
| --- | --- |
| [POP3::send\_cmd()](send_cmd) wp-includes/class-pop3.php | |
| [POP3::is\_ok()](is_ok) wp-includes/class-pop3.php | |
| Used By | Description |
| --- | --- |
| [POP3::pass()](pass) wp-includes/class-pop3.php | |
| [POP3::apop()](apop) wp-includes/class-pop3.php | |
| [POP3::popstat()](popstat) wp-includes/class-pop3.php | |
wordpress POP3::pass( $pass = "" ) POP3::pass( $pass = "" )
========================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function pass ($pass = "") {
// Sends the PASS command, returns # of msgs in mailbox,
// returns false (undef) on Auth failure
if(empty($pass)) {
$this->ERROR = "POP3 pass: " . _("No password submitted");
return false;
} elseif(!isset($this->FP)) {
$this->ERROR = "POP3 pass: " . _("connection not established");
return false;
} else {
$reply = $this->send_cmd("PASS $pass");
if(!$this->is_ok($reply)) {
$this->ERROR = "POP3 pass: " . _("Authentication failed") . " [$reply]";
$this->quit();
return false;
} else {
// Auth successful.
$count = $this->last("count");
$this->COUNT = $count;
return $count;
}
}
}
```
| Uses | Description |
| --- | --- |
| [POP3::send\_cmd()](send_cmd) wp-includes/class-pop3.php | |
| [POP3::is\_ok()](is_ok) wp-includes/class-pop3.php | |
| [POP3::quit()](quit) wp-includes/class-pop3.php | |
| [POP3::last()](last) wp-includes/class-pop3.php | |
| Used By | Description |
| --- | --- |
| [POP3::login()](login) wp-includes/class-pop3.php | |
wordpress POP3::is_ok( $cmd = "" ) POP3::is\_ok( $cmd = "" )
=========================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function is_ok ($cmd = "") {
// Return true or false on +OK or -ERR
if( empty($cmd) )
return false;
else
return( stripos($cmd, '+OK') !== false );
}
```
| Uses | Description |
| --- | --- |
| [stripos()](../../functions/stripos) wp-includes/class-pop3.php | |
| Used By | Description |
| --- | --- |
| [POP3::connect()](connect) wp-includes/class-pop3.php | |
| [POP3::user()](user) wp-includes/class-pop3.php | |
| [POP3::pass()](pass) wp-includes/class-pop3.php | |
| [POP3::apop()](apop) wp-includes/class-pop3.php | |
| [POP3::top()](top) wp-includes/class-pop3.php | |
| [POP3::pop\_list()](pop_list) wp-includes/class-pop3.php | |
| [POP3::get()](get) wp-includes/class-pop3.php | |
| [POP3::last()](last) wp-includes/class-pop3.php | |
| [POP3::reset()](reset) wp-includes/class-pop3.php | |
| [POP3::uidl()](uidl) wp-includes/class-pop3.php | |
| [POP3::delete()](delete) wp-includes/class-pop3.php | |
wordpress POP3::quit() POP3::quit()
============
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function quit() {
// Closes the connection to the POP3 server, deleting
// any msgs marked as deleted.
if(!isset($this->FP))
{
$this->ERROR = "POP3 quit: " . _("connection does not exist");
return false;
}
$fp = $this->FP;
$cmd = "QUIT";
fwrite($fp,"$cmd\r\n");
$reply = fgets($fp,$this->BUFFER);
$reply = $this->strip_clf($reply);
if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); }
fclose($fp);
unset($this->FP);
return true;
}
```
| Uses | Description |
| --- | --- |
| [POP3::strip\_clf()](strip_clf) wp-includes/class-pop3.php | |
| Used By | Description |
| --- | --- |
| [POP3::pass()](pass) wp-includes/class-pop3.php | |
| [POP3::reset()](reset) wp-includes/class-pop3.php | |
| programming_docs |
wordpress POP3::user( $user = "" ) POP3::user( $user = "" )
========================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function user ($user = "") {
// Sends the USER command, returns true or false
if( empty($user) ) {
$this->ERROR = "POP3 user: " . _("no login ID submitted");
return false;
} elseif(!isset($this->FP)) {
$this->ERROR = "POP3 user: " . _("connection not established");
return false;
} else {
$reply = $this->send_cmd("USER $user");
if(!$this->is_ok($reply)) {
$this->ERROR = "POP3 user: " . _("Error ") . "[$reply]";
return false;
} else
return true;
}
}
```
| Uses | Description |
| --- | --- |
| [POP3::send\_cmd()](send_cmd) wp-includes/class-pop3.php | |
| [POP3::is\_ok()](is_ok) wp-includes/class-pop3.php | |
| Used By | Description |
| --- | --- |
| [POP3::login()](login) wp-includes/class-pop3.php | |
wordpress POP3::top( $msgNum, $numLines = "0" ) POP3::top( $msgNum, $numLines = "0" )
=====================================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function top ($msgNum, $numLines = "0") {
// Gets the header and first $numLines of the msg body
// returns data in an array with each returned line being
// an array element. If $numLines is empty, returns
// only the header information, and none of the body.
if(!isset($this->FP)) {
$this->ERROR = "POP3 top: " . _("No connection to server");
return false;
}
$this->update_timer();
$fp = $this->FP;
$buffer = $this->BUFFER;
$cmd = "TOP $msgNum $numLines";
fwrite($fp, "TOP $msgNum $numLines\r\n");
$reply = fgets($fp, $buffer);
$reply = $this->strip_clf($reply);
if($this->DEBUG) {
@error_log("POP3 SEND [$cmd] GOT [$reply]",0);
}
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 top: " . _("Error ") . "[$reply]";
return false;
}
$count = 0;
$MsgArray = array();
$line = fgets($fp,$buffer);
while ( !preg_match('/^\.\r\n/',$line))
{
$MsgArray[$count] = $line;
$count++;
$line = fgets($fp,$buffer);
if(empty($line)) { break; }
}
return $MsgArray;
}
```
| Uses | Description |
| --- | --- |
| [POP3::strip\_clf()](strip_clf) wp-includes/class-pop3.php | |
| [POP3::is\_ok()](is_ok) wp-includes/class-pop3.php | |
| [POP3::update\_timer()](update_timer) wp-includes/class-pop3.php | |
wordpress POP3::login( $login = "", $pass = "" ) POP3::login( $login = "", $pass = "" )
======================================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function login ($login = "", $pass = "") {
// Sends both user and pass. Returns # of msgs in mailbox or
// false on failure (or -1, if the error occurs while getting
// the number of messages.)
if( !isset($this->FP) ) {
$this->ERROR = "POP3 login: " . _("No connection to server");
return false;
} else {
$fp = $this->FP;
if( !$this->user( $login ) ) {
// Preserve the error generated by user()
return false;
} else {
$count = $this->pass($pass);
if( (!$count) || ($count == -1) ) {
// Preserve the error generated by last() and pass()
return false;
} else
return $count;
}
}
}
```
| Uses | Description |
| --- | --- |
| [POP3::user()](user) wp-includes/class-pop3.php | |
| [POP3::pass()](pass) wp-includes/class-pop3.php | |
| Used By | Description |
| --- | --- |
| [POP3::apop()](apop) wp-includes/class-pop3.php | |
wordpress POP3::uidl( $msgNum = "" ) POP3::uidl( $msgNum = "" )
==========================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function uidl ($msgNum = "")
{
// Returns the UIDL of the msg specified. If called with
// no arguments, returns an associative array where each
// undeleted msg num is a key, and the msg's uidl is the element
// Array element 0 will contain the total number of msgs
if(!isset($this->FP)) {
$this->ERROR = "POP3 uidl: " . _("No connection to server");
return false;
}
$fp = $this->FP;
$buffer = $this->BUFFER;
if(!empty($msgNum)) {
$cmd = "UIDL $msgNum";
$reply = $this->send_cmd($cmd);
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 uidl: " . _("Error ") . "[$reply]";
return false;
}
list ($ok,$num,$myUidl) = preg_split('/\s+/',$reply);
return $myUidl;
} else {
$this->update_timer();
$UIDLArray = array();
$Total = $this->COUNT;
$UIDLArray[0] = $Total;
if ($Total < 1)
{
return $UIDLArray;
}
$cmd = "UIDL";
fwrite($fp, "UIDL\r\n");
$reply = fgets($fp, $buffer);
$reply = $this->strip_clf($reply);
if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); }
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 uidl: " . _("Error ") . "[$reply]";
return false;
}
$line = "";
$count = 1;
$line = fgets($fp,$buffer);
while ( !preg_match('/^\.\r\n/',$line)) {
list ($msg,$msgUidl) = preg_split('/\s+/',$line);
$msgUidl = $this->strip_clf($msgUidl);
if($count == $msg) {
$UIDLArray[$msg] = $msgUidl;
}
else
{
$UIDLArray[$count] = 'deleted';
}
$count++;
$line = fgets($fp,$buffer);
}
}
return $UIDLArray;
}
```
| Uses | Description |
| --- | --- |
| [POP3::send\_cmd()](send_cmd) wp-includes/class-pop3.php | |
| [POP3::is\_ok()](is_ok) wp-includes/class-pop3.php | |
| [POP3::strip\_clf()](strip_clf) wp-includes/class-pop3.php | |
| [POP3::update\_timer()](update_timer) wp-includes/class-pop3.php | |
wordpress POP3::send_cmd( $cmd = "" ) POP3::send\_cmd( $cmd = "" )
============================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function send_cmd ( $cmd = "" )
{
// Sends a user defined command string to the
// POP server and returns the results. Useful for
// non-compliant or custom POP servers.
// Do NOT includ the \r\n as part of your command
// string - it will be appended automatically.
// The return value is a standard fgets() call, which
// will read up to $this->BUFFER bytes of data, until it
// encounters a new line, or EOF, whichever happens first.
// This method works best if $cmd responds with only
// one line of data.
if(!isset($this->FP))
{
$this->ERROR = "POP3 send_cmd: " . _("No connection to server");
return false;
}
if(empty($cmd))
{
$this->ERROR = "POP3 send_cmd: " . _("Empty command string");
return "";
}
$fp = $this->FP;
$buffer = $this->BUFFER;
$this->update_timer();
fwrite($fp,"$cmd\r\n");
$reply = fgets($fp,$buffer);
$reply = $this->strip_clf($reply);
if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); }
return $reply;
}
```
| Uses | Description |
| --- | --- |
| [POP3::strip\_clf()](strip_clf) wp-includes/class-pop3.php | |
| [POP3::update\_timer()](update_timer) wp-includes/class-pop3.php | |
| Used By | Description |
| --- | --- |
| [POP3::user()](user) wp-includes/class-pop3.php | |
| [POP3::pass()](pass) wp-includes/class-pop3.php | |
| [POP3::apop()](apop) wp-includes/class-pop3.php | |
| [POP3::pop\_list()](pop_list) wp-includes/class-pop3.php | |
| [POP3::get()](get) wp-includes/class-pop3.php | |
| [POP3::last()](last) wp-includes/class-pop3.php | |
| [POP3::reset()](reset) wp-includes/class-pop3.php | |
| [POP3::uidl()](uidl) wp-includes/class-pop3.php | |
| [POP3::delete()](delete) wp-includes/class-pop3.php | |
wordpress POP3::parse_banner( $server_text ) POP3::parse\_banner( $server\_text )
====================================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function parse_banner ( $server_text ) {
$outside = true;
$banner = "";
$length = strlen($server_text);
for($count =0; $count < $length; $count++)
{
$digit = substr($server_text,$count,1);
if(!empty($digit)) {
if( (!$outside) && ($digit != '<') && ($digit != '>') )
{
$banner .= $digit;
}
if ($digit == '<')
{
$outside = false;
}
if($digit == '>')
{
$outside = true;
}
}
}
$banner = $this->strip_clf($banner); // Just in case
return "<$banner>";
}
```
| Uses | Description |
| --- | --- |
| [POP3::strip\_clf()](strip_clf) wp-includes/class-pop3.php | |
| Used By | Description |
| --- | --- |
| [POP3::connect()](connect) wp-includes/class-pop3.php | |
wordpress POP3::strip_clf( $text = "" ) POP3::strip\_clf( $text = "" )
==============================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function strip_clf ($text = "") {
// Strips \r\n from server responses
if(empty($text))
return $text;
else {
$stripped = str_replace(array("\r","\n"),'',$text);
return $stripped;
}
}
```
| Used By | Description |
| --- | --- |
| [POP3::parse\_banner()](parse_banner) wp-includes/class-pop3.php | |
| [POP3::connect()](connect) wp-includes/class-pop3.php | |
| [POP3::top()](top) wp-includes/class-pop3.php | |
| [POP3::pop\_list()](pop_list) wp-includes/class-pop3.php | |
| [POP3::send\_cmd()](send_cmd) wp-includes/class-pop3.php | |
| [POP3::quit()](quit) wp-includes/class-pop3.php | |
| [POP3::uidl()](uidl) wp-includes/class-pop3.php | |
wordpress POP3::update_timer() POP3::update\_timer()
=====================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function update_timer () {
set_time_limit($this->TIMEOUT);
return true;
}
```
| Used By | Description |
| --- | --- |
| [POP3::connect()](connect) wp-includes/class-pop3.php | |
| [POP3::top()](top) wp-includes/class-pop3.php | |
| [POP3::pop\_list()](pop_list) wp-includes/class-pop3.php | |
| [POP3::get()](get) wp-includes/class-pop3.php | |
| [POP3::send\_cmd()](send_cmd) wp-includes/class-pop3.php | |
| [POP3::uidl()](uidl) wp-includes/class-pop3.php | |
wordpress POP3::__construct( $server = '', $timeout = '' ) POP3::\_\_construct( $server = '', $timeout = '' )
==================================================
PHP5 constructor.
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function __construct ( $server = '', $timeout = '' ) {
settype($this->BUFFER,"integer");
if( !empty($server) ) {
// Do not allow programs to alter MAILSERVER
// if it is already specified. They can get around
// this if they -really- want to, so don't count on it.
if(empty($this->MAILSERVER))
$this->MAILSERVER = $server;
}
if(!empty($timeout)) {
settype($timeout,"integer");
$this->TIMEOUT = $timeout;
set_time_limit($timeout);
}
return true;
}
```
| Used By | Description |
| --- | --- |
| [POP3::POP3()](pop3) wp-includes/class-pop3.php | PHP4 constructor. |
wordpress POP3::pop_list( $msgNum = "" ) POP3::pop\_list( $msgNum = "" )
===============================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function pop_list ($msgNum = "") {
// If called with an argument, returns that msgs' size in octets
// No argument returns an associative array of undeleted
// msg numbers and their sizes in octets
if(!isset($this->FP))
{
$this->ERROR = "POP3 pop_list: " . _("No connection to server");
return false;
}
$fp = $this->FP;
$Total = $this->COUNT;
if( (!$Total) or ($Total == -1) )
{
return false;
}
if($Total == 0)
{
return array("0","0");
// return -1; // mailbox empty
}
$this->update_timer();
if(!empty($msgNum))
{
$cmd = "LIST $msgNum";
fwrite($fp,"$cmd\r\n");
$reply = fgets($fp,$this->BUFFER);
$reply = $this->strip_clf($reply);
if($this->DEBUG) {
@error_log("POP3 SEND [$cmd] GOT [$reply]",0);
}
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 pop_list: " . _("Error ") . "[$reply]";
return false;
}
list($junk,$num,$size) = preg_split('/\s+/',$reply);
return $size;
}
$cmd = "LIST";
$reply = $this->send_cmd($cmd);
if(!$this->is_ok($reply))
{
$reply = $this->strip_clf($reply);
$this->ERROR = "POP3 pop_list: " . _("Error ") . "[$reply]";
return false;
}
$MsgArray = array();
$MsgArray[0] = $Total;
for($msgC=1;$msgC <= $Total; $msgC++)
{
if($msgC > $Total) { break; }
$line = fgets($fp,$this->BUFFER);
$line = $this->strip_clf($line);
if(strpos($line, '.') === 0)
{
$this->ERROR = "POP3 pop_list: " . _("Premature end of list");
return false;
}
list($thisMsg,$msgSize) = preg_split('/\s+/',$line);
settype($thisMsg,"integer");
if($thisMsg != $msgC)
{
$MsgArray[$msgC] = "deleted";
}
else
{
$MsgArray[$msgC] = $msgSize;
}
}
return $MsgArray;
}
```
| Uses | Description |
| --- | --- |
| [POP3::strip\_clf()](strip_clf) wp-includes/class-pop3.php | |
| [POP3::is\_ok()](is_ok) wp-includes/class-pop3.php | |
| [POP3::send\_cmd()](send_cmd) wp-includes/class-pop3.php | |
| [POP3::update\_timer()](update_timer) wp-includes/class-pop3.php | |
wordpress POP3::delete( $msgNum = "" ) POP3::delete( $msgNum = "" )
============================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function delete ($msgNum = "") {
// Flags a specified msg as deleted. The msg will not
// be deleted until a quit() method is called.
if(!isset($this->FP))
{
$this->ERROR = "POP3 delete: " . _("No connection to server");
return false;
}
if(empty($msgNum))
{
$this->ERROR = "POP3 delete: " . _("No msg number submitted");
return false;
}
$reply = $this->send_cmd("DELE $msgNum");
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 delete: " . _("Command failed ") . "[$reply]";
return false;
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [POP3::send\_cmd()](send_cmd) wp-includes/class-pop3.php | |
| [POP3::is\_ok()](is_ok) wp-includes/class-pop3.php | |
wordpress POP3::connect( $server, $port = 110 ) POP3::connect( $server, $port = 110 )
=====================================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function connect ($server, $port = 110) {
// Opens a socket to the specified server. Unless overridden,
// port defaults to 110. Returns true on success, false on fail
// If MAILSERVER is set, override $server with its value.
if (!isset($port) || !$port) {$port = 110;}
if(!empty($this->MAILSERVER))
$server = $this->MAILSERVER;
if(empty($server)){
$this->ERROR = "POP3 connect: " . _("No server specified");
unset($this->FP);
return false;
}
$fp = @fsockopen("$server", $port, $errno, $errstr);
if(!$fp) {
$this->ERROR = "POP3 connect: " . _("Error ") . "[$errno] [$errstr]";
unset($this->FP);
return false;
}
socket_set_blocking($fp,-1);
$this->update_timer();
$reply = fgets($fp,$this->BUFFER);
$reply = $this->strip_clf($reply);
if($this->DEBUG)
error_log("POP3 SEND [connect: $server] GOT [$reply]",0);
if(!$this->is_ok($reply)) {
$this->ERROR = "POP3 connect: " . _("Error ") . "[$reply]";
unset($this->FP);
return false;
}
$this->FP = $fp;
$this->BANNER = $this->parse_banner($reply);
return true;
}
```
| Uses | Description |
| --- | --- |
| [POP3::parse\_banner()](parse_banner) wp-includes/class-pop3.php | |
| [POP3::strip\_clf()](strip_clf) wp-includes/class-pop3.php | |
| [POP3::is\_ok()](is_ok) wp-includes/class-pop3.php | |
| [POP3::update\_timer()](update_timer) wp-includes/class-pop3.php | |
wordpress POP3::get( $msgNum ) POP3::get( $msgNum )
====================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function get ($msgNum) {
// Retrieve the specified msg number. Returns an array
// where each line of the msg is an array element.
if(!isset($this->FP))
{
$this->ERROR = "POP3 get: " . _("No connection to server");
return false;
}
$this->update_timer();
$fp = $this->FP;
$buffer = $this->BUFFER;
$cmd = "RETR $msgNum";
$reply = $this->send_cmd($cmd);
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 get: " . _("Error ") . "[$reply]";
return false;
}
$count = 0;
$MsgArray = array();
$line = fgets($fp,$buffer);
while ( !preg_match('/^\.\r\n/',$line))
{
if ( $line[0] == '.' ) { $line = substr($line,1); }
$MsgArray[$count] = $line;
$count++;
$line = fgets($fp,$buffer);
if(empty($line)) { break; }
}
return $MsgArray;
}
```
| Uses | Description |
| --- | --- |
| [POP3::send\_cmd()](send_cmd) wp-includes/class-pop3.php | |
| [POP3::is\_ok()](is_ok) wp-includes/class-pop3.php | |
| [POP3::update\_timer()](update_timer) wp-includes/class-pop3.php | |
wordpress POP3::apop( $login, $pass ) POP3::apop( $login, $pass )
===========================
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
function apop ($login,$pass) {
// Attempts an APOP login. If this fails, it'll
// try a standard login. YOUR SERVER MUST SUPPORT
// THE USE OF THE APOP COMMAND!
// (apop is optional per rfc1939)
if(!isset($this->FP)) {
$this->ERROR = "POP3 apop: " . _("No connection to server");
return false;
} elseif(!$this->ALLOWAPOP) {
$retVal = $this->login($login,$pass);
return $retVal;
} elseif(empty($login)) {
$this->ERROR = "POP3 apop: " . _("No login ID submitted");
return false;
} elseif(empty($pass)) {
$this->ERROR = "POP3 apop: " . _("No password submitted");
return false;
} else {
$banner = $this->BANNER;
if( (!$banner) or (empty($banner)) ) {
$this->ERROR = "POP3 apop: " . _("No server banner") . ' - ' . _("abort");
$retVal = $this->login($login,$pass);
return $retVal;
} else {
$AuthString = $banner;
$AuthString .= $pass;
$APOPString = md5($AuthString);
$cmd = "APOP $login $APOPString";
$reply = $this->send_cmd($cmd);
if(!$this->is_ok($reply)) {
$this->ERROR = "POP3 apop: " . _("apop authentication failed") . ' - ' . _("abort");
$retVal = $this->login($login,$pass);
return $retVal;
} else {
// Auth successful.
$count = $this->last("count");
$this->COUNT = $count;
return $count;
}
}
}
}
```
| Uses | Description |
| --- | --- |
| [POP3::login()](login) wp-includes/class-pop3.php | |
| [POP3::send\_cmd()](send_cmd) wp-includes/class-pop3.php | |
| [POP3::is\_ok()](is_ok) wp-includes/class-pop3.php | |
| [POP3::last()](last) wp-includes/class-pop3.php | |
| programming_docs |
wordpress POP3::POP3( $server = '', $timeout = '' ) POP3::POP3( $server = '', $timeout = '' )
=========================================
PHP4 constructor.
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
public function POP3( $server = '', $timeout = '' ) {
self::__construct( $server, $timeout );
}
```
| Uses | Description |
| --- | --- |
| [POP3::\_\_construct()](__construct) wp-includes/class-pop3.php | PHP5 constructor. |
wordpress WP_Date_Query::get_sql_clauses(): string[] WP\_Date\_Query::get\_sql\_clauses(): string[]
==============================================
Generates SQL clauses to be appended to a main query.
Called by the public [WP\_Date\_Query::get\_sql()](get_sql), this method is abstracted out to maintain parity with the other Query classes.
string[] Array containing JOIN and WHERE SQL clauses to append to the main query.
* `join`stringSQL fragment to append to the main JOIN clause.
* `where`stringSQL fragment to append to the main WHERE clause.
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
protected function get_sql_clauses() {
$sql = $this->get_sql_for_query( $this->queries );
if ( ! empty( $sql['where'] ) ) {
$sql['where'] = ' AND ' . $sql['where'];
}
return $sql;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Date\_Query::get\_sql\_for\_query()](get_sql_for_query) wp-includes/class-wp-date-query.php | Generates SQL clauses for a single query array. |
| Used By | Description |
| --- | --- |
| [WP\_Date\_Query::get\_sql()](get_sql) wp-includes/class-wp-date-query.php | Generates WHERE clause to be appended to a main query. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Date_Query::is_first_order_clause( array $query ): bool WP\_Date\_Query::is\_first\_order\_clause( array $query ): bool
===============================================================
Determines whether this is a first-order clause.
Checks to see if the current clause has any time-related keys.
If so, it’s first-order.
`$query` array Required Query clause. bool True if this is a first-order clause.
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
protected function is_first_order_clause( $query ) {
$time_keys = array_intersect( $this->time_keys, array_keys( $query ) );
return ! empty( $time_keys );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Date\_Query::sanitize\_query()](sanitize_query) wp-includes/class-wp-date-query.php | Recursive-friendly query sanitizer. |
| [WP\_Date\_Query::get\_sql\_for\_query()](get_sql_for_query) wp-includes/class-wp-date-query.php | Generates SQL clauses for a single query array. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Date_Query::get_sql_for_clause( array $query, array $parent_query ): string[] WP\_Date\_Query::get\_sql\_for\_clause( array $query, array $parent\_query ): string[]
======================================================================================
Turns a first-order date query into SQL for a WHERE clause.
`$query` array Required Date query clause. `$parent_query` array Required Parent query of the current date query. string[] Array containing JOIN and WHERE SQL clauses to append to the main query.
* `join`stringSQL fragment to append to the main JOIN clause.
* `where`stringSQL fragment to append to the main WHERE clause.
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
protected function get_sql_for_clause( $query, $parent_query ) {
global $wpdb;
// The sub-parts of a $where part.
$where_parts = array();
$column = ( ! empty( $query['column'] ) ) ? esc_sql( $query['column'] ) : $this->column;
$column = $this->validate_column( $column );
$compare = $this->get_compare( $query );
$inclusive = ! empty( $query['inclusive'] );
// Assign greater- and less-than values.
$lt = '<';
$gt = '>';
if ( $inclusive ) {
$lt .= '=';
$gt .= '=';
}
// Range queries.
if ( ! empty( $query['after'] ) ) {
$where_parts[] = $wpdb->prepare( "$column $gt %s", $this->build_mysql_datetime( $query['after'], ! $inclusive ) );
}
if ( ! empty( $query['before'] ) ) {
$where_parts[] = $wpdb->prepare( "$column $lt %s", $this->build_mysql_datetime( $query['before'], $inclusive ) );
}
// Specific value queries.
$date_units = array(
'YEAR' => array( 'year' ),
'MONTH' => array( 'month', 'monthnum' ),
'_wp_mysql_week' => array( 'week', 'w' ),
'DAYOFYEAR' => array( 'dayofyear' ),
'DAYOFMONTH' => array( 'day' ),
'DAYOFWEEK' => array( 'dayofweek' ),
'WEEKDAY' => array( 'dayofweek_iso' ),
);
// Check of the possible date units and add them to the query.
foreach ( $date_units as $sql_part => $query_parts ) {
foreach ( $query_parts as $query_part ) {
if ( isset( $query[ $query_part ] ) ) {
$value = $this->build_value( $compare, $query[ $query_part ] );
if ( $value ) {
switch ( $sql_part ) {
case '_wp_mysql_week':
$where_parts[] = _wp_mysql_week( $column ) . " $compare $value";
break;
case 'WEEKDAY':
$where_parts[] = "$sql_part( $column ) + 1 $compare $value";
break;
default:
$where_parts[] = "$sql_part( $column ) $compare $value";
}
break;
}
}
}
}
if ( isset( $query['hour'] ) || isset( $query['minute'] ) || isset( $query['second'] ) ) {
// Avoid notices.
foreach ( array( 'hour', 'minute', 'second' ) as $unit ) {
if ( ! isset( $query[ $unit ] ) ) {
$query[ $unit ] = null;
}
}
$time_query = $this->build_time_query( $column, $compare, $query['hour'], $query['minute'], $query['second'] );
if ( $time_query ) {
$where_parts[] = $time_query;
}
}
/*
* Return an array of 'join' and 'where' for compatibility
* with other query classes.
*/
return array(
'where' => $where_parts,
'join' => array(),
);
}
```
| Uses | Description |
| --- | --- |
| [esc\_sql()](../../functions/esc_sql) wp-includes/formatting.php | Escapes data for use in a MySQL query. |
| [WP\_Date\_Query::build\_mysql\_datetime()](build_mysql_datetime) wp-includes/class-wp-date-query.php | Builds a MySQL format date/time based on some query parameters. |
| [WP\_Date\_Query::build\_value()](build_value) wp-includes/class-wp-date-query.php | Builds and validates a value string based on the comparison operator. |
| [WP\_Date\_Query::build\_time\_query()](build_time_query) wp-includes/class-wp-date-query.php | Builds a query string for comparing time values (hour, minute, second). |
| [WP\_Date\_Query::validate\_column()](validate_column) wp-includes/class-wp-date-query.php | Validates a column name parameter. |
| [WP\_Date\_Query::get\_compare()](get_compare) wp-includes/class-wp-date-query.php | Determines and validates what comparison operator to use. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_Date\_Query::get\_sql\_for\_query()](get_sql_for_query) wp-includes/class-wp-date-query.php | Generates SQL clauses for a single query array. |
| [WP\_Date\_Query::get\_sql\_for\_subquery()](get_sql_for_subquery) wp-includes/class-wp-date-query.php | Turns a single date clause into pieces for a WHERE clause. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Date_Query::validate_column( string $column ): string WP\_Date\_Query::validate\_column( string $column ): string
===========================================================
Validates a column name parameter.
Column names without a table prefix (like ‘post\_date’) are checked against a list of allowed and known tables, and then, if found, have a table prefix (such as ‘wp\_posts.’) prepended. Prefixed column names (such as ‘wp\_posts.post\_date’) bypass this allowed check, and are only sanitized to remove illegal characters.
`$column` string Required The user-supplied column name. string A validated column name value.
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
public function validate_column( $column ) {
global $wpdb;
$valid_columns = array(
'post_date',
'post_date_gmt',
'post_modified',
'post_modified_gmt',
'comment_date',
'comment_date_gmt',
'user_registered',
'registered',
'last_updated',
);
// Attempt to detect a table prefix.
if ( false === strpos( $column, '.' ) ) {
/**
* Filters the list of valid date query columns.
*
* @since 3.7.0
* @since 4.1.0 Added 'user_registered' to the default recognized columns.
* @since 4.6.0 Added 'registered' and 'last_updated' to the default recognized columns.
*
* @param string[] $valid_columns An array of valid date query columns. Defaults
* are 'post_date', 'post_date_gmt', 'post_modified',
* 'post_modified_gmt', 'comment_date', 'comment_date_gmt',
* 'user_registered', 'registered', 'last_updated'.
*/
if ( ! in_array( $column, apply_filters( 'date_query_valid_columns', $valid_columns ), true ) ) {
$column = 'post_date';
}
$known_columns = array(
$wpdb->posts => array(
'post_date',
'post_date_gmt',
'post_modified',
'post_modified_gmt',
),
$wpdb->comments => array(
'comment_date',
'comment_date_gmt',
),
$wpdb->users => array(
'user_registered',
),
$wpdb->blogs => array(
'registered',
'last_updated',
),
);
// If it's a known column name, add the appropriate table prefix.
foreach ( $known_columns as $table_name => $table_columns ) {
if ( in_array( $column, $table_columns, true ) ) {
$column = $table_name . '.' . $column;
break;
}
}
}
// Remove unsafe characters.
return preg_replace( '/[^a-zA-Z0-9_$\.]/', '', $column );
}
```
[apply\_filters( 'date\_query\_valid\_columns', string[] $valid\_columns )](../../hooks/date_query_valid_columns)
Filters the list of valid date query columns.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Date\_Query::get\_sql\_for\_clause()](get_sql_for_clause) wp-includes/class-wp-date-query.php | Turns a first-order date query into SQL for a WHERE clause. |
| [WP\_Date\_Query::\_\_construct()](__construct) wp-includes/class-wp-date-query.php | Constructor. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Date_Query::sanitize_relation( string $relation ): string WP\_Date\_Query::sanitize\_relation( string $relation ): string
===============================================================
Sanitizes a ‘relation’ operator.
`$relation` string Required Raw relation key from the query argument. string Sanitized relation (`'AND'` or `'OR'`).
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
public function sanitize_relation( $relation ) {
if ( 'OR' === strtoupper( $relation ) ) {
return 'OR';
} else {
return 'AND';
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Date\_Query::sanitize\_query()](sanitize_query) wp-includes/class-wp-date-query.php | Recursive-friendly query sanitizer. |
| [WP\_Date\_Query::\_\_construct()](__construct) wp-includes/class-wp-date-query.php | Constructor. |
| Version | Description |
| --- | --- |
| [6.0.3](https://developer.wordpress.org/reference/since/6.0.3/) | Introduced. |
wordpress WP_Date_Query::validate_date_values( array $date_query = array() ): bool WP\_Date\_Query::validate\_date\_values( array $date\_query = array() ): bool
=============================================================================
Validates the given date\_query values and triggers errors if something is not valid.
Note that date queries with invalid date ranges are allowed to continue (though of course no items will be found for impossible dates).
This method only generates debug notices for these cases.
`$date_query` array Optional The date\_query array. Default: `array()`
bool True if all values in the query are valid, false if one or more fail.
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
public function validate_date_values( $date_query = array() ) {
if ( empty( $date_query ) ) {
return false;
}
$valid = true;
/*
* Validate 'before' and 'after' up front, then let the
* validation routine continue to be sure that all invalid
* values generate errors too.
*/
if ( array_key_exists( 'before', $date_query ) && is_array( $date_query['before'] ) ) {
$valid = $this->validate_date_values( $date_query['before'] );
}
if ( array_key_exists( 'after', $date_query ) && is_array( $date_query['after'] ) ) {
$valid = $this->validate_date_values( $date_query['after'] );
}
// Array containing all min-max checks.
$min_max_checks = array();
// Days per year.
if ( array_key_exists( 'year', $date_query ) ) {
/*
* If a year exists in the date query, we can use it to get the days.
* If multiple years are provided (as in a BETWEEN), use the first one.
*/
if ( is_array( $date_query['year'] ) ) {
$_year = reset( $date_query['year'] );
} else {
$_year = $date_query['year'];
}
$max_days_of_year = gmdate( 'z', mktime( 0, 0, 0, 12, 31, $_year ) ) + 1;
} else {
// Otherwise we use the max of 366 (leap-year).
$max_days_of_year = 366;
}
$min_max_checks['dayofyear'] = array(
'min' => 1,
'max' => $max_days_of_year,
);
// Days per week.
$min_max_checks['dayofweek'] = array(
'min' => 1,
'max' => 7,
);
// Days per week.
$min_max_checks['dayofweek_iso'] = array(
'min' => 1,
'max' => 7,
);
// Months per year.
$min_max_checks['month'] = array(
'min' => 1,
'max' => 12,
);
// Weeks per year.
if ( isset( $_year ) ) {
/*
* If we have a specific year, use it to calculate number of weeks.
* Note: the number of weeks in a year is the date in which Dec 28 appears.
*/
$week_count = gmdate( 'W', mktime( 0, 0, 0, 12, 28, $_year ) );
} else {
// Otherwise set the week-count to a maximum of 53.
$week_count = 53;
}
$min_max_checks['week'] = array(
'min' => 1,
'max' => $week_count,
);
// Days per month.
$min_max_checks['day'] = array(
'min' => 1,
'max' => 31,
);
// Hours per day.
$min_max_checks['hour'] = array(
'min' => 0,
'max' => 23,
);
// Minutes per hour.
$min_max_checks['minute'] = array(
'min' => 0,
'max' => 59,
);
// Seconds per minute.
$min_max_checks['second'] = array(
'min' => 0,
'max' => 59,
);
// Concatenate and throw a notice for each invalid value.
foreach ( $min_max_checks as $key => $check ) {
if ( ! array_key_exists( $key, $date_query ) ) {
continue;
}
// Throw a notice for each failing value.
foreach ( (array) $date_query[ $key ] as $_value ) {
$is_between = $_value >= $check['min'] && $_value <= $check['max'];
if ( ! is_numeric( $_value ) || ! $is_between ) {
$error = sprintf(
/* translators: Date query invalid date message. 1: Invalid value, 2: Type of value, 3: Minimum valid value, 4: Maximum valid value. */
__( 'Invalid value %1$s for %2$s. Expected value should be between %3$s and %4$s.' ),
'<code>' . esc_html( $_value ) . '</code>',
'<code>' . esc_html( $key ) . '</code>',
'<code>' . esc_html( $check['min'] ) . '</code>',
'<code>' . esc_html( $check['max'] ) . '</code>'
);
_doing_it_wrong( __CLASS__, $error, '4.1.0' );
$valid = false;
}
}
}
// If we already have invalid date messages, don't bother running through checkdate().
if ( ! $valid ) {
return $valid;
}
$day_month_year_error_msg = '';
$day_exists = array_key_exists( 'day', $date_query ) && is_numeric( $date_query['day'] );
$month_exists = array_key_exists( 'month', $date_query ) && is_numeric( $date_query['month'] );
$year_exists = array_key_exists( 'year', $date_query ) && is_numeric( $date_query['year'] );
if ( $day_exists && $month_exists && $year_exists ) {
// 1. Checking day, month, year combination.
if ( ! wp_checkdate( $date_query['month'], $date_query['day'], $date_query['year'], sprintf( '%s-%s-%s', $date_query['year'], $date_query['month'], $date_query['day'] ) ) ) {
$day_month_year_error_msg = sprintf(
/* translators: 1: Year, 2: Month, 3: Day of month. */
__( 'The following values do not describe a valid date: year %1$s, month %2$s, day %3$s.' ),
'<code>' . esc_html( $date_query['year'] ) . '</code>',
'<code>' . esc_html( $date_query['month'] ) . '</code>',
'<code>' . esc_html( $date_query['day'] ) . '</code>'
);
$valid = false;
}
} elseif ( $day_exists && $month_exists ) {
/*
* 2. checking day, month combination
* We use 2012 because, as a leap year, it's the most permissive.
*/
if ( ! wp_checkdate( $date_query['month'], $date_query['day'], 2012, sprintf( '2012-%s-%s', $date_query['month'], $date_query['day'] ) ) ) {
$day_month_year_error_msg = sprintf(
/* translators: 1: Month, 2: Day of month. */
__( 'The following values do not describe a valid date: month %1$s, day %2$s.' ),
'<code>' . esc_html( $date_query['month'] ) . '</code>',
'<code>' . esc_html( $date_query['day'] ) . '</code>'
);
$valid = false;
}
}
if ( ! empty( $day_month_year_error_msg ) ) {
_doing_it_wrong( __CLASS__, $day_month_year_error_msg, '4.1.0' );
}
return $valid;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Date\_Query::validate\_date\_values()](validate_date_values) wp-includes/class-wp-date-query.php | Validates the given date\_query values and triggers errors if something is not valid. |
| [wp\_checkdate()](../../functions/wp_checkdate) wp-includes/functions.php | Tests if the supplied date is valid for the Gregorian calendar. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [\_doing\_it\_wrong()](../../functions/_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Used By | Description |
| --- | --- |
| [WP\_Date\_Query::sanitize\_query()](sanitize_query) wp-includes/class-wp-date-query.php | Recursive-friendly query sanitizer. |
| [WP\_Date\_Query::validate\_date\_values()](validate_date_values) wp-includes/class-wp-date-query.php | Validates the given date\_query values and triggers errors if something is not valid. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Date_Query::sanitize_query( array $queries, array $parent_query = null ): array WP\_Date\_Query::sanitize\_query( array $queries, array $parent\_query = null ): array
======================================================================================
Recursive-friendly query sanitizer.
Ensures that each query-level clause has a ‘relation’ key, and that each first-order clause contains all the necessary keys from `$defaults`.
`$queries` array Required `$parent_query` array Optional Default: `null`
array Sanitized queries.
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
public function sanitize_query( $queries, $parent_query = null ) {
$cleaned_query = array();
$defaults = array(
'column' => 'post_date',
'compare' => '=',
'relation' => 'AND',
);
// Numeric keys should always have array values.
foreach ( $queries as $qkey => $qvalue ) {
if ( is_numeric( $qkey ) && ! is_array( $qvalue ) ) {
unset( $queries[ $qkey ] );
}
}
// Each query should have a value for each default key. Inherit from the parent when possible.
foreach ( $defaults as $dkey => $dvalue ) {
if ( isset( $queries[ $dkey ] ) ) {
continue;
}
if ( isset( $parent_query[ $dkey ] ) ) {
$queries[ $dkey ] = $parent_query[ $dkey ];
} else {
$queries[ $dkey ] = $dvalue;
}
}
// Validate the dates passed in the query.
if ( $this->is_first_order_clause( $queries ) ) {
$this->validate_date_values( $queries );
}
// Sanitize the relation parameter.
$queries['relation'] = $this->sanitize_relation( $queries['relation'] );
foreach ( $queries as $key => $q ) {
if ( ! is_array( $q ) || in_array( $key, $this->time_keys, true ) ) {
// This is a first-order query. Trust the values and sanitize when building SQL.
$cleaned_query[ $key ] = $q;
} else {
// Any array without a time key is another query, so we recurse.
$cleaned_query[] = $this->sanitize_query( $q, $queries );
}
}
return $cleaned_query;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Date\_Query::sanitize\_relation()](sanitize_relation) wp-includes/class-wp-date-query.php | Sanitizes a ‘relation’ operator. |
| [WP\_Date\_Query::is\_first\_order\_clause()](is_first_order_clause) wp-includes/class-wp-date-query.php | Determines whether this is a first-order clause. |
| [WP\_Date\_Query::validate\_date\_values()](validate_date_values) wp-includes/class-wp-date-query.php | Validates the given date\_query values and triggers errors if something is not valid. |
| [WP\_Date\_Query::sanitize\_query()](sanitize_query) wp-includes/class-wp-date-query.php | Recursive-friendly query sanitizer. |
| Used By | Description |
| --- | --- |
| [WP\_Date\_Query::sanitize\_query()](sanitize_query) wp-includes/class-wp-date-query.php | Recursive-friendly query sanitizer. |
| [WP\_Date\_Query::\_\_construct()](__construct) wp-includes/class-wp-date-query.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Date_Query::get_sql(): string WP\_Date\_Query::get\_sql(): string
===================================
Generates WHERE clause to be appended to a main query.
string MySQL WHERE clause.
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
public function get_sql() {
$sql = $this->get_sql_clauses();
$where = $sql['where'];
/**
* Filters the date query WHERE clause.
*
* @since 3.7.0
*
* @param string $where WHERE clause of the date query.
* @param WP_Date_Query $query The WP_Date_Query instance.
*/
return apply_filters( 'get_date_sql', $where, $this );
}
```
[apply\_filters( 'get\_date\_sql', string $where, WP\_Date\_Query $query )](../../hooks/get_date_sql)
Filters the date query WHERE clause.
| Uses | Description |
| --- | --- |
| [WP\_Date\_Query::get\_sql\_clauses()](get_sql_clauses) wp-includes/class-wp-date-query.php | Generates SQL clauses to be appended to a main query. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Date_Query::build_value( string $compare, string|array $value ): string|false|int WP\_Date\_Query::build\_value( string $compare, string|array $value ): string|false|int
=======================================================================================
Builds and validates a value string based on the comparison operator.
`$compare` string Required The compare operator to use. `$value` string|array Required The value. string|false|int The value to be used in SQL or false on error.
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
public function build_value( $compare, $value ) {
if ( ! isset( $value ) ) {
return false;
}
switch ( $compare ) {
case 'IN':
case 'NOT IN':
$value = (array) $value;
// Remove non-numeric values.
$value = array_filter( $value, 'is_numeric' );
if ( empty( $value ) ) {
return false;
}
return '(' . implode( ',', array_map( 'intval', $value ) ) . ')';
case 'BETWEEN':
case 'NOT BETWEEN':
if ( ! is_array( $value ) || 2 !== count( $value ) ) {
$value = array( $value, $value );
} else {
$value = array_values( $value );
}
// If either value is non-numeric, bail.
foreach ( $value as $v ) {
if ( ! is_numeric( $v ) ) {
return false;
}
}
$value = array_map( 'intval', $value );
return $value[0] . ' AND ' . $value[1];
default:
if ( ! is_numeric( $value ) ) {
return false;
}
return (int) $value;
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Date\_Query::get\_sql\_for\_clause()](get_sql_for_clause) wp-includes/class-wp-date-query.php | Turns a first-order date query into SQL for a WHERE clause. |
| [WP\_Date\_Query::build\_time\_query()](build_time_query) wp-includes/class-wp-date-query.php | Builds a query string for comparing time values (hour, minute, second). |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Date_Query::build_mysql_datetime( string|array $datetime, bool $default_to_max = false ): string|false WP\_Date\_Query::build\_mysql\_datetime( string|array $datetime, bool $default\_to\_max = false ): string|false
===============================================================================================================
Builds a MySQL format date/time based on some query parameters.
You can pass an array of values (year, month, etc.) with missing parameter values being defaulted to either the maximum or minimum values (controlled by the $default\_to parameter). Alternatively you can pass a string that will be passed to date\_create().
`$datetime` string|array Required An array of parameters or a strotime() string. `$default_to_max` bool Optional Whether to round up incomplete dates. Supported by values of $datetime that are arrays, or string values that are a subset of MySQL date format (`'Y'`, `'Y-m'`, `'Y-m-d'`, 'Y-m-d H:i').
Default: false. Default: `false`
string|false A MySQL format date/time or false on failure.
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
public function build_mysql_datetime( $datetime, $default_to_max = false ) {
if ( ! is_array( $datetime ) ) {
/*
* Try to parse some common date formats, so we can detect
* the level of precision and support the 'inclusive' parameter.
*/
if ( preg_match( '/^(\d{4})$/', $datetime, $matches ) ) {
// Y
$datetime = array(
'year' => (int) $matches[1],
);
} elseif ( preg_match( '/^(\d{4})\-(\d{2})$/', $datetime, $matches ) ) {
// Y-m
$datetime = array(
'year' => (int) $matches[1],
'month' => (int) $matches[2],
);
} elseif ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2})$/', $datetime, $matches ) ) {
// Y-m-d
$datetime = array(
'year' => (int) $matches[1],
'month' => (int) $matches[2],
'day' => (int) $matches[3],
);
} elseif ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2})$/', $datetime, $matches ) ) {
// Y-m-d H:i
$datetime = array(
'year' => (int) $matches[1],
'month' => (int) $matches[2],
'day' => (int) $matches[3],
'hour' => (int) $matches[4],
'minute' => (int) $matches[5],
);
}
// If no match is found, we don't support default_to_max.
if ( ! is_array( $datetime ) ) {
$wp_timezone = wp_timezone();
// Assume local timezone if not provided.
$dt = date_create( $datetime, $wp_timezone );
if ( false === $dt ) {
return gmdate( 'Y-m-d H:i:s', false );
}
return $dt->setTimezone( $wp_timezone )->format( 'Y-m-d H:i:s' );
}
}
$datetime = array_map( 'absint', $datetime );
if ( ! isset( $datetime['year'] ) ) {
$datetime['year'] = current_time( 'Y' );
}
if ( ! isset( $datetime['month'] ) ) {
$datetime['month'] = ( $default_to_max ) ? 12 : 1;
}
if ( ! isset( $datetime['day'] ) ) {
$datetime['day'] = ( $default_to_max ) ? (int) gmdate( 't', mktime( 0, 0, 0, $datetime['month'], 1, $datetime['year'] ) ) : 1;
}
if ( ! isset( $datetime['hour'] ) ) {
$datetime['hour'] = ( $default_to_max ) ? 23 : 0;
}
if ( ! isset( $datetime['minute'] ) ) {
$datetime['minute'] = ( $default_to_max ) ? 59 : 0;
}
if ( ! isset( $datetime['second'] ) ) {
$datetime['second'] = ( $default_to_max ) ? 59 : 0;
}
return sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['minute'], $datetime['second'] );
}
```
| Uses | Description |
| --- | --- |
| [wp\_timezone()](../../functions/wp_timezone) wp-includes/functions.php | Retrieves the timezone of the site as a `DateTimeZone` object. |
| [current\_time()](../../functions/current_time) wp-includes/functions.php | Retrieves the current time based on specified type. |
| Used By | Description |
| --- | --- |
| [WP\_Date\_Query::get\_sql\_for\_clause()](get_sql_for_clause) wp-includes/class-wp-date-query.php | Turns a first-order date query into SQL for a WHERE clause. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Date_Query::__construct( array $date_query, string $default_column = 'post_date' ) WP\_Date\_Query::\_\_construct( array $date\_query, string $default\_column = 'post\_date' )
============================================================================================
Constructor.
Time-related parameters that normally require integer values (‘year’, ‘month’, ‘week’, ‘dayofyear’, ‘day’, ‘dayofweek’, ‘dayofweek\_iso’, ‘hour’, ‘minute’, ‘second’) accept arrays of integers for some values of ‘compare’. When ‘compare’ is ‘IN’ or ‘NOT IN’, arrays are accepted; when ‘compare’ is ‘BETWEEN’ or ‘NOT BETWEEN’, arrays of two valid values are required. See individual argument descriptions for accepted values.
`$date_query` array Required Array of date query clauses.
* `...$0`array
+ `column`stringOptional. The column to query against. If undefined, inherits the value of the `$default_column` parameter. See [WP\_Date\_Query::validate\_column()](validate_column) and the ['date\_query\_valid\_columns'](../../hooks/date_query_valid_columns) filter for the list of accepted values.
Default `'post_date'`.
+ `compare`stringOptional. The comparison operator. Accepts `'='`, `'!='`, `'>'`, `'>='`, `'<'`, `'<='`, `'IN'`, 'NOT IN', `'BETWEEN'`, 'NOT BETWEEN'. Default `'='`.
+ `relation`stringOptional. The boolean relationship between the date queries. Accepts `'OR'` or `'AND'`.
Default `'OR'`.
+ `...$0`array Optional. An array of first-order clause parameters, or another fully-formed date query.
- `before`string|array Optional. Date to retrieve posts before. Accepts `strtotime()`-compatible string, or array of 'year', 'month', 'day' values.
* `year`stringThe four-digit year. Default empty. Accepts any four-digit year.
* `month`stringOptional when passing array.The month of the year.
Default (string:empty)|(array:1). Accepts numbers 1-12.
* `day`stringOptional when passing array.The day of the month.
Default (string:empty)|(array:1). Accepts numbers 1-31.
* `after`string|array Optional. Date to retrieve posts after. Accepts `strtotime()`-compatible string, or array of 'year', 'month', 'day' values.
+ `year`stringThe four-digit year. Accepts any four-digit year. Default empty.
+ `month`stringOptional when passing array. The month of the year. Accepts numbers 1-12.
Default (string:empty)|(array:12).
+ `day`stringOptional when passing array.The day of the month. Accepts numbers 1-31.
Default (string:empty)|(array:last day of month).
+ `column`stringOptional. Used to add a clause comparing a column other than the column specified in the top-level `$column` parameter.
See [WP\_Date\_Query::validate\_column()](validate_column) and the ['date\_query\_valid\_columns'](../../hooks/date_query_valid_columns) filter for the list of accepted values. Default is the value of top-level `$column`.
+ `compare`stringOptional. The comparison operator. Accepts `'='`, `'!='`, `'>'`, `'>='`, `'<'`, `'<='`, `'IN'`, 'NOT IN', `'BETWEEN'`, 'NOT BETWEEN'. `'IN'`, 'NOT IN', `'BETWEEN'`, and 'NOT BETWEEN'. Comparisons support arrays in some time-related parameters. Default `'='`.
+ `inclusive`boolOptional. Include results from dates specified in `'before'` or `'after'`. Default false.
+ `year`int|int[]Optional. The four-digit year number. Accepts any four-digit year or an array of years if `$compare` supports it. Default empty.
+ `month`int|int[]Optional. The two-digit month number. Accepts numbers 1-12 or an array of valid numbers if `$compare` supports it. Default empty.
+ `week`int|int[]Optional. The week number of the year. Accepts numbers 0-53 or an array of valid numbers if `$compare` supports it. Default empty.
+ `dayofyear`int|int[]Optional. The day number of the year. Accepts numbers 1-366 or an array of valid numbers if `$compare` supports it.
+ `day`int|int[]Optional. The day of the month. Accepts numbers 1-31 or an array of valid numbers if `$compare` supports it. Default empty.
+ `dayofweek`int|int[]Optional. The day number of the week. Accepts numbers 1-7 (1 is Sunday) or an array of valid numbers if `$compare` supports it.
Default empty.
+ `dayofweek_iso`int|int[]Optional. The day number of the week (ISO). Accepts numbers 1-7 (1 is Monday) or an array of valid numbers if `$compare` supports it.
Default empty.
+ `hour`int|int[]Optional. The hour of the day. Accepts numbers 0-23 or an array of valid numbers if `$compare` supports it. Default empty.
+ `minute`int|int[]Optional. The minute of the hour. Accepts numbers 0-59 or an array of valid numbers if `$compare` supports it. Default empty.
+ `second`int|int[]Optional. The second of the minute. Accepts numbers 0-59 or an array of valid numbers if `$compare` supports it. Default empty.
} `$default_column` string Optional Default column to query against. See [WP\_Date\_Query::validate\_column()](validate_column) and the ['date\_query\_valid\_columns'](../../hooks/date_query_valid_columns) filter for the list of accepted values.
Default `'post_date'`. Default: `'post_date'`
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
public function __construct( $date_query, $default_column = 'post_date' ) {
if ( empty( $date_query ) || ! is_array( $date_query ) ) {
return;
}
if ( isset( $date_query['relation'] ) ) {
$this->relation = $this->sanitize_relation( $date_query['relation'] );
} else {
$this->relation = 'AND';
}
// Support for passing time-based keys in the top level of the $date_query array.
if ( ! isset( $date_query[0] ) ) {
$date_query = array( $date_query );
}
if ( ! empty( $date_query['column'] ) ) {
$date_query['column'] = esc_sql( $date_query['column'] );
} else {
$date_query['column'] = esc_sql( $default_column );
}
$this->column = $this->validate_column( $this->column );
$this->compare = $this->get_compare( $date_query );
$this->queries = $this->sanitize_query( $date_query );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Date\_Query::sanitize\_relation()](sanitize_relation) wp-includes/class-wp-date-query.php | Sanitizes a ‘relation’ operator. |
| [WP\_Date\_Query::sanitize\_query()](sanitize_query) wp-includes/class-wp-date-query.php | Recursive-friendly query sanitizer. |
| [esc\_sql()](../../functions/esc_sql) wp-includes/formatting.php | Escapes data for use in a MySQL query. |
| [WP\_Date\_Query::validate\_column()](validate_column) wp-includes/class-wp-date-query.php | Validates a column name parameter. |
| [WP\_Date\_Query::get\_compare()](get_compare) wp-includes/class-wp-date-query.php | Determines and validates what comparison operator to use. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Query::get\_site\_ids()](../wp_site_query/get_site_ids) wp-includes/class-wp-site-query.php | Used internally to get a list of site IDs matching the query vars. |
| [WP\_Comment\_Query::get\_comment\_ids()](../wp_comment_query/get_comment_ids) wp-includes/class-wp-comment-query.php | Used internally to get a list of comment IDs matching the query vars. |
| [WP\_Query::get\_posts()](../wp_query/get_posts) wp-includes/class-wp-query.php | Retrieves an array of posts based on query variables. |
| [WP\_User\_Query::prepare\_query()](../wp_user_query/prepare_query) wp-includes/class-wp-user-query.php | Prepares the query variables. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced `'dayofweek_iso'` time type parameter. |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | The $inclusive logic was updated to include all times within the date range. |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Date_Query::get_sql_for_subquery( array $query ): string[] WP\_Date\_Query::get\_sql\_for\_subquery( array $query ): string[]
==================================================================
Turns a single date clause into pieces for a WHERE clause.
A wrapper for get\_sql\_for\_clause(), included here for backward compatibility while retaining the naming convention across Query classes.
`$query` array Required Date query arguments. string[] Array containing JOIN and WHERE SQL clauses to append to the main query.
* `join`stringSQL fragment to append to the main JOIN clause.
* `where`stringSQL fragment to append to the main WHERE clause.
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
protected function get_sql_for_subquery( $query ) {
return $this->get_sql_for_clause( $query, '' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Date\_Query::get\_sql\_for\_clause()](get_sql_for_clause) wp-includes/class-wp-date-query.php | Turns a first-order date query into SQL for a WHERE clause. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Date_Query::get_sql_for_query( array $query, int $depth ): array WP\_Date\_Query::get\_sql\_for\_query( array $query, int $depth ): array
========================================================================
Generates SQL clauses for a single query array.
If nested subqueries are found, this method recurses the tree to produce the properly nested SQL.
`$query` array Required Query to parse. `$depth` int Optional Number of tree levels deep we currently are.
Used to calculate indentation. Default 0. array Array containing JOIN and WHERE SQL clauses to append to a single query array.
* `join`stringSQL fragment to append to the main JOIN clause.
* `where`stringSQL fragment to append to the main WHERE clause.
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
protected function get_sql_for_query( $query, $depth = 0 ) {
$sql_chunks = array(
'join' => array(),
'where' => array(),
);
$sql = array(
'join' => '',
'where' => '',
);
$indent = '';
for ( $i = 0; $i < $depth; $i++ ) {
$indent .= ' ';
}
foreach ( $query as $key => $clause ) {
if ( 'relation' === $key ) {
$relation = $query['relation'];
} elseif ( is_array( $clause ) ) {
// This is a first-order clause.
if ( $this->is_first_order_clause( $clause ) ) {
$clause_sql = $this->get_sql_for_clause( $clause, $query );
$where_count = count( $clause_sql['where'] );
if ( ! $where_count ) {
$sql_chunks['where'][] = '';
} elseif ( 1 === $where_count ) {
$sql_chunks['where'][] = $clause_sql['where'][0];
} else {
$sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
}
$sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
// This is a subquery, so we recurse.
} else {
$clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
$sql_chunks['where'][] = $clause_sql['where'];
$sql_chunks['join'][] = $clause_sql['join'];
}
}
}
// Filter to remove empties.
$sql_chunks['join'] = array_filter( $sql_chunks['join'] );
$sql_chunks['where'] = array_filter( $sql_chunks['where'] );
if ( empty( $relation ) ) {
$relation = 'AND';
}
// Filter duplicate JOIN clauses and combine into a single string.
if ( ! empty( $sql_chunks['join'] ) ) {
$sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
}
// Generate a single WHERE clause with proper brackets and indentation.
if ( ! empty( $sql_chunks['where'] ) ) {
$sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
}
return $sql;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Date\_Query::get\_sql\_for\_clause()](get_sql_for_clause) wp-includes/class-wp-date-query.php | Turns a first-order date query into SQL for a WHERE clause. |
| [WP\_Date\_Query::is\_first\_order\_clause()](is_first_order_clause) wp-includes/class-wp-date-query.php | Determines whether this is a first-order clause. |
| [WP\_Date\_Query::get\_sql\_for\_query()](get_sql_for_query) wp-includes/class-wp-date-query.php | Generates SQL clauses for a single query array. |
| Used By | Description |
| --- | --- |
| [WP\_Date\_Query::get\_sql\_clauses()](get_sql_clauses) wp-includes/class-wp-date-query.php | Generates SQL clauses to be appended to a main query. |
| [WP\_Date\_Query::get\_sql\_for\_query()](get_sql_for_query) wp-includes/class-wp-date-query.php | Generates SQL clauses for a single query array. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Date_Query::build_time_query( string $column, string $compare, int|null $hour = null, int|null $minute = null, int|null $second = null ): string|false WP\_Date\_Query::build\_time\_query( string $column, string $compare, int|null $hour = null, int|null $minute = null, int|null $second = null ): string|false
=============================================================================================================================================================
Builds a query string for comparing time values (hour, minute, second).
If just hour, minute, or second is set than a normal comparison will be done.
However if multiple values are passed, a pseudo-decimal time will be created in order to be able to accurately compare against.
`$column` string Required The column to query against. Needs to be pre-validated! `$compare` string Required The comparison operator. Needs to be pre-validated! `$hour` int|null Optional An hour value (0-23). Default: `null`
`$minute` int|null Optional A minute value (0-59). Default: `null`
`$second` int|null Optional A second value (0-59). Default: `null`
string|false A query part or false on failure.
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
public function build_time_query( $column, $compare, $hour = null, $minute = null, $second = null ) {
global $wpdb;
// Have to have at least one.
if ( ! isset( $hour ) && ! isset( $minute ) && ! isset( $second ) ) {
return false;
}
// Complex combined queries aren't supported for multi-value queries.
if ( in_array( $compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ), true ) ) {
$return = array();
$value = $this->build_value( $compare, $hour );
if ( false !== $value ) {
$return[] = "HOUR( $column ) $compare $value";
}
$value = $this->build_value( $compare, $minute );
if ( false !== $value ) {
$return[] = "MINUTE( $column ) $compare $value";
}
$value = $this->build_value( $compare, $second );
if ( false !== $value ) {
$return[] = "SECOND( $column ) $compare $value";
}
return implode( ' AND ', $return );
}
// Cases where just one unit is set.
if ( isset( $hour ) && ! isset( $minute ) && ! isset( $second ) ) {
$value = $this->build_value( $compare, $hour );
if ( false !== $value ) {
return "HOUR( $column ) $compare $value";
}
} elseif ( ! isset( $hour ) && isset( $minute ) && ! isset( $second ) ) {
$value = $this->build_value( $compare, $minute );
if ( false !== $value ) {
return "MINUTE( $column ) $compare $value";
}
} elseif ( ! isset( $hour ) && ! isset( $minute ) && isset( $second ) ) {
$value = $this->build_value( $compare, $second );
if ( false !== $value ) {
return "SECOND( $column ) $compare $value";
}
}
// Single units were already handled. Since hour & second isn't allowed, minute must to be set.
if ( ! isset( $minute ) ) {
return false;
}
$format = '';
$time = '';
// Hour.
if ( null !== $hour ) {
$format .= '%H.';
$time .= sprintf( '%02d', $hour ) . '.';
} else {
$format .= '0.';
$time .= '0.';
}
// Minute.
$format .= '%i';
$time .= sprintf( '%02d', $minute );
if ( isset( $second ) ) {
$format .= '%s';
$time .= sprintf( '%02d', $second );
}
return $wpdb->prepare( "DATE_FORMAT( $column, %s ) $compare %f", $format, $time );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Date\_Query::build\_value()](build_value) wp-includes/class-wp-date-query.php | Builds and validates a value string based on the comparison operator. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_Date\_Query::get\_sql\_for\_clause()](get_sql_for_clause) wp-includes/class-wp-date-query.php | Turns a first-order date query into SQL for a WHERE clause. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Date_Query::get_compare( array $query ): string WP\_Date\_Query::get\_compare( array $query ): string
=====================================================
Determines and validates what comparison operator to use.
`$query` array Required A date query or a date subquery. string The comparison operator.
File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/)
```
public function get_compare( $query ) {
if ( ! empty( $query['compare'] )
&& in_array( $query['compare'], array( '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ), true )
) {
return strtoupper( $query['compare'] );
}
return $this->compare;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Date\_Query::get\_sql\_for\_clause()](get_sql_for_clause) wp-includes/class-wp-date-query.php | Turns a first-order date query into SQL for a WHERE clause. |
| [WP\_Date\_Query::\_\_construct()](__construct) wp-includes/class-wp-date-query.php | Constructor. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Automatic_Updater::send_debug_email() WP\_Automatic\_Updater::send\_debug\_email()
============================================
Prepares and sends an email of a full log of background update results, useful for debugging and geekery.
File: `wp-admin/includes/class-wp-automatic-updater.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-automatic-updater.php/)
```
protected function send_debug_email() {
$update_count = 0;
foreach ( $this->update_results as $type => $updates ) {
$update_count += count( $updates );
}
$body = array();
$failures = 0;
/* translators: %s: Network home URL. */
$body[] = sprintf( __( 'WordPress site: %s' ), network_home_url( '/' ) );
// Core.
if ( isset( $this->update_results['core'] ) ) {
$result = $this->update_results['core'][0];
if ( $result->result && ! is_wp_error( $result->result ) ) {
/* translators: %s: WordPress version. */
$body[] = sprintf( __( 'SUCCESS: WordPress was successfully updated to %s' ), $result->name );
} else {
/* translators: %s: WordPress version. */
$body[] = sprintf( __( 'FAILED: WordPress failed to update to %s' ), $result->name );
$failures++;
}
$body[] = '';
}
// Plugins, Themes, Translations.
foreach ( array( 'plugin', 'theme', 'translation' ) as $type ) {
if ( ! isset( $this->update_results[ $type ] ) ) {
continue;
}
$success_items = wp_list_filter( $this->update_results[ $type ], array( 'result' => true ) );
if ( $success_items ) {
$messages = array(
'plugin' => __( 'The following plugins were successfully updated:' ),
'theme' => __( 'The following themes were successfully updated:' ),
'translation' => __( 'The following translations were successfully updated:' ),
);
$body[] = $messages[ $type ];
foreach ( wp_list_pluck( $success_items, 'name' ) as $name ) {
/* translators: %s: Name of plugin / theme / translation. */
$body[] = ' * ' . sprintf( __( 'SUCCESS: %s' ), $name );
}
}
if ( $success_items !== $this->update_results[ $type ] ) {
// Failed updates.
$messages = array(
'plugin' => __( 'The following plugins failed to update:' ),
'theme' => __( 'The following themes failed to update:' ),
'translation' => __( 'The following translations failed to update:' ),
);
$body[] = $messages[ $type ];
foreach ( $this->update_results[ $type ] as $item ) {
if ( ! $item->result || is_wp_error( $item->result ) ) {
/* translators: %s: Name of plugin / theme / translation. */
$body[] = ' * ' . sprintf( __( 'FAILED: %s' ), $item->name );
$failures++;
}
}
}
$body[] = '';
}
if ( '' !== get_bloginfo( 'name' ) ) {
$site_title = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
} else {
$site_title = parse_url( home_url(), PHP_URL_HOST );
}
if ( $failures ) {
$body[] = trim(
__(
"BETA TESTING?
=============
This debugging email is sent when you are using a development version of WordPress.
If you think these failures might be due to a bug in WordPress, could you report it?
* Open a thread in the support forums: https://wordpress.org/support/forum/alphabeta
* Or, if you're comfortable writing a bug report: https://core.trac.wordpress.org/
Thanks! -- The WordPress Team"
)
);
$body[] = '';
/* translators: Background update failed notification email subject. %s: Site title. */
$subject = sprintf( __( '[%s] Background Update Failed' ), $site_title );
} else {
/* translators: Background update finished notification email subject. %s: Site title. */
$subject = sprintf( __( '[%s] Background Update Finished' ), $site_title );
}
$body[] = trim(
__(
'UPDATE LOG
=========='
)
);
$body[] = '';
foreach ( array( 'core', 'plugin', 'theme', 'translation' ) as $type ) {
if ( ! isset( $this->update_results[ $type ] ) ) {
continue;
}
foreach ( $this->update_results[ $type ] as $update ) {
$body[] = $update->name;
$body[] = str_repeat( '-', strlen( $update->name ) );
foreach ( $update->messages as $message ) {
$body[] = ' ' . html_entity_decode( str_replace( '…', '...', $message ) );
}
if ( is_wp_error( $update->result ) ) {
$results = array( 'update' => $update->result );
// If we rolled back, we want to know an error that occurred then too.
if ( 'rollback_was_required' === $update->result->get_error_code() ) {
$results = (array) $update->result->get_error_data();
}
foreach ( $results as $result_type => $result ) {
if ( ! is_wp_error( $result ) ) {
continue;
}
if ( 'rollback' === $result_type ) {
/* translators: 1: Error code, 2: Error message. */
$body[] = ' ' . sprintf( __( 'Rollback Error: [%1$s] %2$s' ), $result->get_error_code(), $result->get_error_message() );
} else {
/* translators: 1: Error code, 2: Error message. */
$body[] = ' ' . sprintf( __( 'Error: [%1$s] %2$s' ), $result->get_error_code(), $result->get_error_message() );
}
if ( $result->get_error_data() ) {
$body[] = ' ' . implode( ', ', (array) $result->get_error_data() );
}
}
}
$body[] = '';
}
}
$email = array(
'to' => get_site_option( 'admin_email' ),
'subject' => $subject,
'body' => implode( "\n", $body ),
'headers' => '',
);
/**
* Filters the debug email that can be sent following an automatic
* background core update.
*
* @since 3.8.0
*
* @param array $email {
* Array of email arguments that will be passed to wp_mail().
*
* @type string $to The email recipient. An array of emails
* can be returned, as handled by wp_mail().
* @type string $subject Email subject.
* @type string $body Email message body.
* @type string $headers Any email headers. Default empty.
* }
* @param int $failures The number of failures encountered while upgrading.
* @param mixed $results The results of all attempted updates.
*/
$email = apply_filters( 'automatic_updates_debug_email', $email, $failures, $this->update_results );
wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] );
}
```
[apply\_filters( 'automatic\_updates\_debug\_email', array $email, int $failures, mixed $results )](../../hooks/automatic_updates_debug_email)
Filters the debug email that can be sent following an automatic background core update.
| Uses | Description |
| --- | --- |
| [wp\_specialchars\_decode()](../../functions/wp_specialchars_decode) wp-includes/formatting.php | Converts a number of HTML entities into their special characters. |
| [wp\_mail()](../../functions/wp_mail) wp-includes/pluggable.php | Sends an email, similar to PHP’s mail function. |
| [wp\_list\_filter()](../../functions/wp_list_filter) wp-includes/functions.php | Filters a list of objects, based on a set of key => value arguments. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [network\_home\_url()](../../functions/network_home_url) wp-includes/link-template.php | Retrieves the home URL for the current network. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_site\_option()](../../functions/get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Automatic\_Updater::run()](run) wp-admin/includes/class-wp-automatic-updater.php | Kicks off the background update process, looping through all pending updates. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Automatic_Updater::send_email( string $type, object $core_update, mixed $result = null ) WP\_Automatic\_Updater::send\_email( string $type, object $core\_update, mixed $result = null )
===============================================================================================
Sends an email upon the completion or failure of a background core update.
`$type` string Required The type of email to send. Can be one of `'success'`, `'fail'`, `'manual'`, `'critical'`. `$core_update` object Required The update offer that was attempted. `$result` mixed Optional The result for the core update. Can be [WP\_Error](../wp_error). Default: `null`
File: `wp-admin/includes/class-wp-automatic-updater.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-automatic-updater.php/)
```
protected function send_email( $type, $core_update, $result = null ) {
update_site_option(
'auto_core_update_notified',
array(
'type' => $type,
'email' => get_site_option( 'admin_email' ),
'version' => $core_update->current,
'timestamp' => time(),
)
);
$next_user_core_update = get_preferred_from_update_core();
// If the update transient is empty, use the update we just performed.
if ( ! $next_user_core_update ) {
$next_user_core_update = $core_update;
}
if ( 'upgrade' === $next_user_core_update->response
&& version_compare( $next_user_core_update->version, $core_update->version, '>' )
) {
$newer_version_available = true;
} else {
$newer_version_available = false;
}
/**
* Filters whether to send an email following an automatic background core update.
*
* @since 3.7.0
*
* @param bool $send Whether to send the email. Default true.
* @param string $type The type of email to send. Can be one of
* 'success', 'fail', 'critical'.
* @param object $core_update The update offer that was attempted.
* @param mixed $result The result for the core update. Can be WP_Error.
*/
if ( 'manual' !== $type && ! apply_filters( 'auto_core_update_send_email', true, $type, $core_update, $result ) ) {
return;
}
switch ( $type ) {
case 'success': // We updated.
/* translators: Site updated notification email subject. 1: Site title, 2: WordPress version. */
$subject = __( '[%1$s] Your site has updated to WordPress %2$s' );
break;
case 'fail': // We tried to update but couldn't.
case 'manual': // We can't update (and made no attempt).
/* translators: Update available notification email subject. 1: Site title, 2: WordPress version. */
$subject = __( '[%1$s] WordPress %2$s is available. Please update!' );
break;
case 'critical': // We tried to update, started to copy files, then things went wrong.
/* translators: Site down notification email subject. 1: Site title. */
$subject = __( '[%1$s] URGENT: Your site may be down due to a failed update' );
break;
default:
return;
}
// If the auto-update is not to the latest version, say that the current version of WP is available instead.
$version = 'success' === $type ? $core_update->current : $next_user_core_update->current;
$subject = sprintf( $subject, wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ), $version );
$body = '';
switch ( $type ) {
case 'success':
$body .= sprintf(
/* translators: 1: Home URL, 2: WordPress version. */
__( 'Howdy! Your site at %1$s has been updated automatically to WordPress %2$s.' ),
home_url(),
$core_update->current
);
$body .= "\n\n";
if ( ! $newer_version_available ) {
$body .= __( 'No further action is needed on your part.' ) . ' ';
}
// Can only reference the About screen if their update was successful.
list( $about_version ) = explode( '-', $core_update->current, 2 );
/* translators: %s: WordPress version. */
$body .= sprintf( __( 'For more on version %s, see the About WordPress screen:' ), $about_version );
$body .= "\n" . admin_url( 'about.php' );
if ( $newer_version_available ) {
/* translators: %s: WordPress latest version. */
$body .= "\n\n" . sprintf( __( 'WordPress %s is also now available.' ), $next_user_core_update->current ) . ' ';
$body .= __( 'Updating is easy and only takes a few moments:' );
$body .= "\n" . network_admin_url( 'update-core.php' );
}
break;
case 'fail':
case 'manual':
$body .= sprintf(
/* translators: 1: Home URL, 2: WordPress version. */
__( 'Please update your site at %1$s to WordPress %2$s.' ),
home_url(),
$next_user_core_update->current
);
$body .= "\n\n";
// Don't show this message if there is a newer version available.
// Potential for confusion, and also not useful for them to know at this point.
if ( 'fail' === $type && ! $newer_version_available ) {
$body .= __( 'An attempt was made, but your site could not be updated automatically.' ) . ' ';
}
$body .= __( 'Updating is easy and only takes a few moments:' );
$body .= "\n" . network_admin_url( 'update-core.php' );
break;
case 'critical':
if ( $newer_version_available ) {
$body .= sprintf(
/* translators: 1: Home URL, 2: WordPress version. */
__( 'Your site at %1$s experienced a critical failure while trying to update WordPress to version %2$s.' ),
home_url(),
$core_update->current
);
} else {
$body .= sprintf(
/* translators: 1: Home URL, 2: WordPress latest version. */
__( 'Your site at %1$s experienced a critical failure while trying to update to the latest version of WordPress, %2$s.' ),
home_url(),
$core_update->current
);
}
$body .= "\n\n" . __( "This means your site may be offline or broken. Don't panic; this can be fixed." );
$body .= "\n\n" . __( "Please check out your site now. It's possible that everything is working. If it says you need to update, you should do so:" );
$body .= "\n" . network_admin_url( 'update-core.php' );
break;
}
$critical_support = 'critical' === $type && ! empty( $core_update->support_email );
if ( $critical_support ) {
// Support offer if available.
$body .= "\n\n" . sprintf(
/* translators: %s: Support email address. */
__( 'The WordPress team is willing to help you. Forward this email to %s and the team will work with you to make sure your site is working.' ),
$core_update->support_email
);
} else {
// Add a note about the support forums.
$body .= "\n\n" . __( 'If you experience any issues or need support, the volunteers in the WordPress.org support forums may be able to help.' );
$body .= "\n" . __( 'https://wordpress.org/support/forums/' );
}
// Updates are important!
if ( 'success' !== $type || $newer_version_available ) {
$body .= "\n\n" . __( 'Keeping your site updated is important for security. It also makes the internet a safer place for you and your readers.' );
}
if ( $critical_support ) {
$body .= ' ' . __( "Reach out to WordPress Core developers to ensure you'll never have this problem again." );
}
// If things are successful and we're now on the latest, mention plugins and themes if any are out of date.
if ( 'success' === $type && ! $newer_version_available && ( get_plugin_updates() || get_theme_updates() ) ) {
$body .= "\n\n" . __( 'You also have some plugins or themes with updates available. Update them now:' );
$body .= "\n" . network_admin_url();
}
$body .= "\n\n" . __( 'The WordPress Team' ) . "\n";
if ( 'critical' === $type && is_wp_error( $result ) ) {
$body .= "\n***\n\n";
/* translators: %s: WordPress version. */
$body .= sprintf( __( 'Your site was running version %s.' ), get_bloginfo( 'version' ) );
$body .= ' ' . __( 'Some data that describes the error your site encountered has been put together.' );
$body .= ' ' . __( 'Your hosting company, support forum volunteers, or a friendly developer may be able to use this information to help you:' );
// If we had a rollback and we're still critical, then the rollback failed too.
// Loop through all errors (the main WP_Error, the update result, the rollback result) for code, data, etc.
if ( 'rollback_was_required' === $result->get_error_code() ) {
$errors = array( $result, $result->get_error_data()->update, $result->get_error_data()->rollback );
} else {
$errors = array( $result );
}
foreach ( $errors as $error ) {
if ( ! is_wp_error( $error ) ) {
continue;
}
$error_code = $error->get_error_code();
/* translators: %s: Error code. */
$body .= "\n\n" . sprintf( __( 'Error code: %s' ), $error_code );
if ( 'rollback_was_required' === $error_code ) {
continue;
}
if ( $error->get_error_message() ) {
$body .= "\n" . $error->get_error_message();
}
$error_data = $error->get_error_data();
if ( $error_data ) {
$body .= "\n" . implode( ', ', (array) $error_data );
}
}
$body .= "\n";
}
$to = get_site_option( 'admin_email' );
$headers = '';
$email = compact( 'to', 'subject', 'body', 'headers' );
/**
* Filters the email sent following an automatic background core update.
*
* @since 3.7.0
*
* @param array $email {
* Array of email arguments that will be passed to wp_mail().
*
* @type string $to The email recipient. An array of emails
* can be returned, as handled by wp_mail().
* @type string $subject The email's subject.
* @type string $body The email message body.
* @type string $headers Any email headers, defaults to no headers.
* }
* @param string $type The type of email being sent. Can be one of
* 'success', 'fail', 'manual', 'critical'.
* @param object $core_update The update offer that was attempted.
* @param mixed $result The result for the core update. Can be WP_Error.
*/
$email = apply_filters( 'auto_core_update_email', $email, $type, $core_update, $result );
wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] );
}
```
[apply\_filters( 'auto\_core\_update\_email', array $email, string $type, object $core\_update, mixed $result )](../../hooks/auto_core_update_email)
Filters the email sent following an automatic background core update.
[apply\_filters( 'auto\_core\_update\_send\_email', bool $send, string $type, object $core\_update, mixed $result )](../../hooks/auto_core_update_send_email)
Filters whether to send an email following an automatic background core update.
| Uses | Description |
| --- | --- |
| [get\_preferred\_from\_update\_core()](../../functions/get_preferred_from_update_core) wp-admin/includes/update.php | Selects the first update version from the update\_core option. |
| [get\_plugin\_updates()](../../functions/get_plugin_updates) wp-admin/includes/update.php | Retrieves plugins with updates available. |
| [get\_theme\_updates()](../../functions/get_theme_updates) wp-admin/includes/update.php | Retrieves themes with updates available. |
| [wp\_specialchars\_decode()](../../functions/wp_specialchars_decode) wp-includes/formatting.php | Converts a number of HTML entities into their special characters. |
| [wp\_mail()](../../functions/wp_mail) wp-includes/pluggable.php | Sends an email, similar to PHP’s mail function. |
| [network\_admin\_url()](../../functions/network_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the network. |
| [update\_site\_option()](../../functions/update_site_option) wp-includes/option.php | Updates the value of an option that was already added for the current network. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_site\_option()](../../functions/get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Automatic\_Updater::after\_core\_update()](after_core_update) wp-admin/includes/class-wp-automatic-updater.php | If we tried to perform a core update, check if we should send an email, and if we need to avoid processing future updates. |
| [WP\_Automatic\_Updater::send\_core\_update\_notification\_email()](send_core_update_notification_email) wp-admin/includes/class-wp-automatic-updater.php | Notifies an administrator of a core update. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Automatic_Updater::run() WP\_Automatic\_Updater::run()
=============================
Kicks off the background update process, looping through all pending updates.
File: `wp-admin/includes/class-wp-automatic-updater.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-automatic-updater.php/)
```
public function run() {
if ( $this->is_disabled() ) {
return;
}
if ( ! is_main_network() || ! is_main_site() ) {
return;
}
if ( ! WP_Upgrader::create_lock( 'auto_updater' ) ) {
return;
}
// Don't automatically run these things, as we'll handle it ourselves.
remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
remove_action( 'upgrader_process_complete', 'wp_version_check' );
remove_action( 'upgrader_process_complete', 'wp_update_plugins' );
remove_action( 'upgrader_process_complete', 'wp_update_themes' );
// Next, plugins.
wp_update_plugins(); // Check for plugin updates.
$plugin_updates = get_site_transient( 'update_plugins' );
if ( $plugin_updates && ! empty( $plugin_updates->response ) ) {
foreach ( $plugin_updates->response as $plugin ) {
$this->update( 'plugin', $plugin );
}
// Force refresh of plugin update information.
wp_clean_plugins_cache();
}
// Next, those themes we all love.
wp_update_themes(); // Check for theme updates.
$theme_updates = get_site_transient( 'update_themes' );
if ( $theme_updates && ! empty( $theme_updates->response ) ) {
foreach ( $theme_updates->response as $theme ) {
$this->update( 'theme', (object) $theme );
}
// Force refresh of theme update information.
wp_clean_themes_cache();
}
// Next, process any core update.
wp_version_check(); // Check for core updates.
$core_update = find_core_auto_update();
if ( $core_update ) {
$this->update( 'core', $core_update );
}
// Clean up, and check for any pending translations.
// (Core_Upgrader checks for core updates.)
$theme_stats = array();
if ( isset( $this->update_results['theme'] ) ) {
foreach ( $this->update_results['theme'] as $upgrade ) {
$theme_stats[ $upgrade->item->theme ] = ( true === $upgrade->result );
}
}
wp_update_themes( $theme_stats ); // Check for theme updates.
$plugin_stats = array();
if ( isset( $this->update_results['plugin'] ) ) {
foreach ( $this->update_results['plugin'] as $upgrade ) {
$plugin_stats[ $upgrade->item->plugin ] = ( true === $upgrade->result );
}
}
wp_update_plugins( $plugin_stats ); // Check for plugin updates.
// Finally, process any new translations.
$language_updates = wp_get_translation_updates();
if ( $language_updates ) {
foreach ( $language_updates as $update ) {
$this->update( 'translation', $update );
}
// Clear existing caches.
wp_clean_update_cache();
wp_version_check(); // Check for core updates.
wp_update_themes(); // Check for theme updates.
wp_update_plugins(); // Check for plugin updates.
}
// Send debugging email to admin for all development installations.
if ( ! empty( $this->update_results ) ) {
$development_version = false !== strpos( get_bloginfo( 'version' ), '-' );
/**
* Filters whether to send a debugging email for each automatic background update.
*
* @since 3.7.0
*
* @param bool $development_version By default, emails are sent if the
* install is a development version.
* Return false to avoid the email.
*/
if ( apply_filters( 'automatic_updates_send_debug_email', $development_version ) ) {
$this->send_debug_email();
}
if ( ! empty( $this->update_results['core'] ) ) {
$this->after_core_update( $this->update_results['core'][0] );
} elseif ( ! empty( $this->update_results['plugin'] ) || ! empty( $this->update_results['theme'] ) ) {
$this->after_plugin_theme_update( $this->update_results );
}
/**
* Fires after all automatic updates have run.
*
* @since 3.8.0
*
* @param array $update_results The results of all attempted updates.
*/
do_action( 'automatic_updates_complete', $this->update_results );
}
WP_Upgrader::release_lock( 'auto_updater' );
}
```
[do\_action( 'automatic\_updates\_complete', array $update\_results )](../../hooks/automatic_updates_complete)
Fires after all automatic updates have run.
[apply\_filters( 'automatic\_updates\_send\_debug\_email', bool $development\_version )](../../hooks/automatic_updates_send_debug_email)
Filters whether to send a debugging email for each automatic background update.
| Uses | Description |
| --- | --- |
| [WP\_Automatic\_Updater::after\_plugin\_theme\_update()](after_plugin_theme_update) wp-admin/includes/class-wp-automatic-updater.php | If we tried to perform plugin or theme updates, check if we should send an email. |
| [WP\_Upgrader::create\_lock()](../wp_upgrader/create_lock) wp-admin/includes/class-wp-upgrader.php | Creates a lock using WordPress options. |
| [remove\_action()](../../functions/remove_action) wp-includes/plugin.php | Removes a callback function from an action hook. |
| [wp\_get\_translation\_updates()](../../functions/wp_get_translation_updates) wp-includes/update.php | Retrieves a list of all language updates available. |
| [wp\_version\_check()](../../functions/wp_version_check) wp-includes/update.php | Checks WordPress version against the newest version. |
| [wp\_update\_themes()](../../functions/wp_update_themes) wp-includes/update.php | Checks for available updates to themes based on the latest versions hosted on WordPress.org. |
| [wp\_update\_plugins()](../../functions/wp_update_plugins) wp-includes/update.php | Checks for available updates to plugins based on the latest versions hosted on WordPress.org. |
| [is\_main\_site()](../../functions/is_main_site) wp-includes/functions.php | Determines whether a site is the main site of the current network. |
| [is\_main\_network()](../../functions/is_main_network) wp-includes/functions.php | Determines whether a network is the main network of the Multisite installation. |
| [get\_site\_transient()](../../functions/get_site_transient) wp-includes/option.php | Retrieves the value of a site transient. |
| [wp\_clean\_themes\_cache()](../../functions/wp_clean_themes_cache) wp-includes/theme.php | Clears the cache held by [get\_theme\_roots()](../../functions/get_theme_roots) and [WP\_Theme](../wp_theme). |
| [wp\_clean\_plugins\_cache()](../../functions/wp_clean_plugins_cache) wp-admin/includes/plugin.php | Clears the plugins cache used by [get\_plugins()](../../functions/get_plugins) and by default, the plugin updates cache. |
| [find\_core\_auto\_update()](../../functions/find_core_auto_update) wp-admin/includes/update.php | Gets the best available (and enabled) Auto-Update for WordPress core. |
| [WP\_Automatic\_Updater::is\_disabled()](is_disabled) wp-admin/includes/class-wp-automatic-updater.php | Determines whether the entire automatic updater is disabled. |
| [WP\_Automatic\_Updater::after\_core\_update()](after_core_update) wp-admin/includes/class-wp-automatic-updater.php | If we tried to perform a core update, check if we should send an email, and if we need to avoid processing future updates. |
| [WP\_Automatic\_Updater::send\_debug\_email()](send_debug_email) wp-admin/includes/class-wp-automatic-updater.php | Prepares and sends an email of a full log of background update results, useful for debugging and geekery. |
| [WP\_Automatic\_Updater::update()](update) wp-admin/includes/class-wp-automatic-updater.php | Updates an item, if appropriate. |
| [wp\_clean\_update\_cache()](../../functions/wp_clean_update_cache) wp-includes/update.php | Clears existing update caches for plugins, themes, and core. |
| [WP\_Upgrader::release\_lock()](../wp_upgrader/release_lock) wp-admin/includes/class-wp-upgrader.php | Releases an upgrader lock. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Automatic_Updater::send_core_update_notification_email( object $item ): bool WP\_Automatic\_Updater::send\_core\_update\_notification\_email( object $item ): bool
=====================================================================================
Notifies an administrator of a core update.
`$item` object Required The update offer. bool True if the site administrator is notified of a core update, false otherwise.
File: `wp-admin/includes/class-wp-automatic-updater.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-automatic-updater.php/)
```
protected function send_core_update_notification_email( $item ) {
$notified = get_site_option( 'auto_core_update_notified' );
// Don't notify if we've already notified the same email address of the same version.
if ( $notified
&& get_site_option( 'admin_email' ) === $notified['email']
&& $notified['version'] === $item->current
) {
return false;
}
// See if we need to notify users of a core update.
$notify = ! empty( $item->notify_email );
/**
* Filters whether to notify the site administrator of a new core update.
*
* By default, administrators are notified when the update offer received
* from WordPress.org sets a particular flag. This allows some discretion
* in if and when to notify.
*
* This filter is only evaluated once per release. If the same email address
* was already notified of the same new version, WordPress won't repeatedly
* email the administrator.
*
* This filter is also used on about.php to check if a plugin has disabled
* these notifications.
*
* @since 3.7.0
*
* @param bool $notify Whether the site administrator is notified.
* @param object $item The update offer.
*/
if ( ! apply_filters( 'send_core_update_notification_email', $notify, $item ) ) {
return false;
}
$this->send_email( 'manual', $item );
return true;
}
```
[apply\_filters( 'send\_core\_update\_notification\_email', bool $notify, object $item )](../../hooks/send_core_update_notification_email)
Filters whether to notify the site administrator of a new core update.
| Uses | Description |
| --- | --- |
| [WP\_Automatic\_Updater::send\_email()](send_email) wp-admin/includes/class-wp-automatic-updater.php | Sends an email upon the completion or failure of a background core update. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_site\_option()](../../functions/get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| Used By | Description |
| --- | --- |
| [WP\_Automatic\_Updater::should\_update()](should_update) wp-admin/includes/class-wp-automatic-updater.php | Tests to see if we can and should update a specific item. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Automatic_Updater::update( string $type, object $item ): null|WP_Error WP\_Automatic\_Updater::update( string $type, object $item ): null|WP\_Error
============================================================================
Updates an item, if appropriate.
`$type` string Required The type of update being checked: `'core'`, `'theme'`, `'plugin'`, `'translation'`. `$item` object Required The update offer. null|[WP\_Error](../wp_error)
File: `wp-admin/includes/class-wp-automatic-updater.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-automatic-updater.php/)
```
public function update( $type, $item ) {
$skin = new Automatic_Upgrader_Skin;
switch ( $type ) {
case 'core':
// The Core upgrader doesn't use the Upgrader's skin during the actual main part of the upgrade, instead, firing a filter.
add_filter( 'update_feedback', array( $skin, 'feedback' ) );
$upgrader = new Core_Upgrader( $skin );
$context = ABSPATH;
break;
case 'plugin':
$upgrader = new Plugin_Upgrader( $skin );
$context = WP_PLUGIN_DIR; // We don't support custom Plugin directories, or updates for WPMU_PLUGIN_DIR.
break;
case 'theme':
$upgrader = new Theme_Upgrader( $skin );
$context = get_theme_root( $item->theme );
break;
case 'translation':
$upgrader = new Language_Pack_Upgrader( $skin );
$context = WP_CONTENT_DIR; // WP_LANG_DIR;
break;
}
// Determine whether we can and should perform this update.
if ( ! $this->should_update( $type, $item, $context ) ) {
return false;
}
/**
* Fires immediately prior to an auto-update.
*
* @since 4.4.0
*
* @param string $type The type of update being checked: 'core', 'theme', 'plugin', or 'translation'.
* @param object $item The update offer.
* @param string $context The filesystem context (a path) against which filesystem access and status
* should be checked.
*/
do_action( 'pre_auto_update', $type, $item, $context );
$upgrader_item = $item;
switch ( $type ) {
case 'core':
/* translators: %s: WordPress version. */
$skin->feedback( __( 'Updating to WordPress %s' ), $item->version );
/* translators: %s: WordPress version. */
$item_name = sprintf( __( 'WordPress %s' ), $item->version );
break;
case 'theme':
$upgrader_item = $item->theme;
$theme = wp_get_theme( $upgrader_item );
$item_name = $theme->Get( 'Name' );
// Add the current version so that it can be reported in the notification email.
$item->current_version = $theme->get( 'Version' );
if ( empty( $item->current_version ) ) {
$item->current_version = false;
}
/* translators: %s: Theme name. */
$skin->feedback( __( 'Updating theme: %s' ), $item_name );
break;
case 'plugin':
$upgrader_item = $item->plugin;
$plugin_data = get_plugin_data( $context . '/' . $upgrader_item );
$item_name = $plugin_data['Name'];
// Add the current version so that it can be reported in the notification email.
$item->current_version = $plugin_data['Version'];
if ( empty( $item->current_version ) ) {
$item->current_version = false;
}
/* translators: %s: Plugin name. */
$skin->feedback( __( 'Updating plugin: %s' ), $item_name );
break;
case 'translation':
$language_item_name = $upgrader->get_name_for_update( $item );
/* translators: %s: Project name (plugin, theme, or WordPress). */
$item_name = sprintf( __( 'Translations for %s' ), $language_item_name );
/* translators: 1: Project name (plugin, theme, or WordPress), 2: Language. */
$skin->feedback( sprintf( __( 'Updating translations for %1$s (%2$s)…' ), $language_item_name, $item->language ) );
break;
}
$allow_relaxed_file_ownership = false;
if ( 'core' === $type && isset( $item->new_files ) && ! $item->new_files ) {
$allow_relaxed_file_ownership = true;
}
// Boom, this site's about to get a whole new splash of paint!
$upgrade_result = $upgrader->upgrade(
$upgrader_item,
array(
'clear_update_cache' => false,
// Always use partial builds if possible for core updates.
'pre_check_md5' => false,
// Only available for core updates.
'attempt_rollback' => true,
// Allow relaxed file ownership in some scenarios.
'allow_relaxed_file_ownership' => $allow_relaxed_file_ownership,
)
);
// If the filesystem is unavailable, false is returned.
if ( false === $upgrade_result ) {
$upgrade_result = new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
}
if ( 'core' === $type ) {
if ( is_wp_error( $upgrade_result )
&& ( 'up_to_date' === $upgrade_result->get_error_code()
|| 'locked' === $upgrade_result->get_error_code() )
) {
// These aren't actual errors, treat it as a skipped-update instead
// to avoid triggering the post-core update failure routines.
return false;
}
// Core doesn't output this, so let's append it, so we don't get confused.
if ( is_wp_error( $upgrade_result ) ) {
$upgrade_result->add( 'installation_failed', __( 'Installation failed.' ) );
$skin->error( $upgrade_result );
} else {
$skin->feedback( __( 'WordPress updated successfully.' ) );
}
}
$this->update_results[ $type ][] = (object) array(
'item' => $item,
'result' => $upgrade_result,
'name' => $item_name,
'messages' => $skin->get_upgrade_messages(),
);
return $upgrade_result;
}
```
[do\_action( 'pre\_auto\_update', string $type, object $item, string $context )](../../hooks/pre_auto_update)
Fires immediately prior to an auto-update.
| Uses | Description |
| --- | --- |
| [WP\_Automatic\_Updater::should\_update()](should_update) wp-admin/includes/class-wp-automatic-updater.php | Tests to see if we can and should update a specific item. |
| [get\_plugin\_data()](../../functions/get_plugin_data) wp-admin/includes/plugin.php | Parses the plugin contents to retrieve plugin’s metadata. |
| [get\_theme\_root()](../../functions/get_theme_root) wp-includes/theme.php | Retrieves path to themes directory. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Automatic\_Updater::run()](run) wp-admin/includes/class-wp-automatic-updater.php | Kicks off the background update process, looping through all pending updates. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Automatic_Updater::is_vcs_checkout( string $context ): bool WP\_Automatic\_Updater::is\_vcs\_checkout( string $context ): bool
==================================================================
Checks for version control checkouts.
Checks for Subversion, Git, Mercurial, and Bazaar. It recursively looks up the filesystem to the top of the drive, erring on the side of detecting a VCS checkout somewhere.
ABSPATH is always checked in addition to whatever `$context` is (which may be the wp-content directory, for example). The underlying assumption is that if you are using version control *anywhere*, then you should be making decisions for how things get updated.
`$context` string Required The filesystem path to check, in addition to ABSPATH. bool True if a VCS checkout was discovered at `$context` or ABSPATH, or anywhere higher. False otherwise.
File: `wp-admin/includes/class-wp-automatic-updater.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-automatic-updater.php/)
```
public function is_vcs_checkout( $context ) {
$context_dirs = array( untrailingslashit( $context ) );
if ( ABSPATH !== $context ) {
$context_dirs[] = untrailingslashit( ABSPATH );
}
$vcs_dirs = array( '.svn', '.git', '.hg', '.bzr' );
$check_dirs = array();
foreach ( $context_dirs as $context_dir ) {
// Walk up from $context_dir to the root.
do {
$check_dirs[] = $context_dir;
// Once we've hit '/' or 'C:\', we need to stop. dirname will keep returning the input here.
if ( dirname( $context_dir ) === $context_dir ) {
break;
}
// Continue one level at a time.
} while ( $context_dir = dirname( $context_dir ) );
}
$check_dirs = array_unique( $check_dirs );
// Search all directories we've found for evidence of version control.
foreach ( $vcs_dirs as $vcs_dir ) {
foreach ( $check_dirs as $check_dir ) {
$checkout = @is_dir( rtrim( $check_dir, '\\/' ) . "/$vcs_dir" );
if ( $checkout ) {
break 2;
}
}
}
/**
* Filters whether the automatic updater should consider a filesystem
* location to be potentially managed by a version control system.
*
* @since 3.7.0
*
* @param bool $checkout Whether a VCS checkout was discovered at `$context`
* or ABSPATH, or anywhere higher.
* @param string $context The filesystem context (a path) against which
* filesystem status should be checked.
*/
return apply_filters( 'automatic_updates_is_vcs_checkout', $checkout, $context );
}
```
[apply\_filters( 'automatic\_updates\_is\_vcs\_checkout', bool $checkout, string $context )](../../hooks/automatic_updates_is_vcs_checkout)
Filters whether the automatic updater should consider a filesystem location to be potentially managed by a version control system.
| Uses | Description |
| --- | --- |
| [untrailingslashit()](../../functions/untrailingslashit) wp-includes/formatting.php | Removes trailing forward slashes and backslashes if they exist. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Automatic\_Updater::should\_update()](should_update) wp-admin/includes/class-wp-automatic-updater.php | Tests to see if we can and should update a specific item. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Automatic_Updater::is_disabled() WP\_Automatic\_Updater::is\_disabled()
======================================
Determines whether the entire automatic updater is disabled.
File: `wp-admin/includes/class-wp-automatic-updater.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-automatic-updater.php/)
```
public function is_disabled() {
// Background updates are disabled if you don't want file changes.
if ( ! wp_is_file_mod_allowed( 'automatic_updater' ) ) {
return true;
}
if ( wp_installing() ) {
return true;
}
// More fine grained control can be done through the WP_AUTO_UPDATE_CORE constant and filters.
$disabled = defined( 'AUTOMATIC_UPDATER_DISABLED' ) && AUTOMATIC_UPDATER_DISABLED;
/**
* Filters whether to entirely disable background updates.
*
* There are more fine-grained filters and controls for selective disabling.
* This filter parallels the AUTOMATIC_UPDATER_DISABLED constant in name.
*
* This also disables update notification emails. That may change in the future.
*
* @since 3.7.0
*
* @param bool $disabled Whether the updater should be disabled.
*/
return apply_filters( 'automatic_updater_disabled', $disabled );
}
```
[apply\_filters( 'automatic\_updater\_disabled', bool $disabled )](../../hooks/automatic_updater_disabled)
Filters whether to entirely disable background updates.
| Uses | Description |
| --- | --- |
| [wp\_is\_file\_mod\_allowed()](../../functions/wp_is_file_mod_allowed) wp-includes/load.php | Determines whether file modifications are allowed. |
| [wp\_installing()](../../functions/wp_installing) wp-includes/load.php | Check or set whether WordPress is in “installation” mode. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Automatic\_Updater::run()](run) wp-admin/includes/class-wp-automatic-updater.php | Kicks off the background update process, looping through all pending updates. |
| [WP\_Automatic\_Updater::should\_update()](should_update) wp-admin/includes/class-wp-automatic-updater.php | Tests to see if we can and should update a specific item. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Automatic_Updater::after_core_update( object $update_result ) WP\_Automatic\_Updater::after\_core\_update( object $update\_result )
=====================================================================
If we tried to perform a core update, check if we should send an email, and if we need to avoid processing future updates.
`$update_result` object Required The result of the core update. Includes the update offer and result. File: `wp-admin/includes/class-wp-automatic-updater.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-automatic-updater.php/)
```
protected function after_core_update( $update_result ) {
$wp_version = get_bloginfo( 'version' );
$core_update = $update_result->item;
$result = $update_result->result;
if ( ! is_wp_error( $result ) ) {
$this->send_email( 'success', $core_update );
return;
}
$error_code = $result->get_error_code();
// Any of these WP_Error codes are critical failures, as in they occurred after we started to copy core files.
// We should not try to perform a background update again until there is a successful one-click update performed by the user.
$critical = false;
if ( 'disk_full' === $error_code || false !== strpos( $error_code, '__copy_dir' ) ) {
$critical = true;
} elseif ( 'rollback_was_required' === $error_code && is_wp_error( $result->get_error_data()->rollback ) ) {
// A rollback is only critical if it failed too.
$critical = true;
$rollback_result = $result->get_error_data()->rollback;
} elseif ( false !== strpos( $error_code, 'do_rollback' ) ) {
$critical = true;
}
if ( $critical ) {
$critical_data = array(
'attempted' => $core_update->current,
'current' => $wp_version,
'error_code' => $error_code,
'error_data' => $result->get_error_data(),
'timestamp' => time(),
'critical' => true,
);
if ( isset( $rollback_result ) ) {
$critical_data['rollback_code'] = $rollback_result->get_error_code();
$critical_data['rollback_data'] = $rollback_result->get_error_data();
}
update_site_option( 'auto_core_update_failed', $critical_data );
$this->send_email( 'critical', $core_update, $result );
return;
}
/*
* Any other WP_Error code (like download_failed or files_not_writable) occurs before
* we tried to copy over core files. Thus, the failures are early and graceful.
*
* We should avoid trying to perform a background update again for the same version.
* But we can try again if another version is released.
*
* For certain 'transient' failures, like download_failed, we should allow retries.
* In fact, let's schedule a special update for an hour from now. (It's possible
* the issue could actually be on WordPress.org's side.) If that one fails, then email.
*/
$send = true;
$transient_failures = array( 'incompatible_archive', 'download_failed', 'insane_distro', 'locked' );
if ( in_array( $error_code, $transient_failures, true ) && ! get_site_option( 'auto_core_update_failed' ) ) {
wp_schedule_single_event( time() + HOUR_IN_SECONDS, 'wp_maybe_auto_update' );
$send = false;
}
$notified = get_site_option( 'auto_core_update_notified' );
// Don't notify if we've already notified the same email address of the same version of the same notification type.
if ( $notified
&& 'fail' === $notified['type']
&& get_site_option( 'admin_email' ) === $notified['email']
&& $notified['version'] === $core_update->current
) {
$send = false;
}
update_site_option(
'auto_core_update_failed',
array(
'attempted' => $core_update->current,
'current' => $wp_version,
'error_code' => $error_code,
'error_data' => $result->get_error_data(),
'timestamp' => time(),
'retry' => in_array( $error_code, $transient_failures, true ),
)
);
if ( $send ) {
$this->send_email( 'fail', $core_update, $result );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Automatic\_Updater::send\_email()](send_email) wp-admin/includes/class-wp-automatic-updater.php | Sends an email upon the completion or failure of a background core update. |
| [wp\_schedule\_single\_event()](../../functions/wp_schedule_single_event) wp-includes/cron.php | Schedules an event to run only once. |
| [update\_site\_option()](../../functions/update_site_option) wp-includes/option.php | Updates the value of an option that was already added for the current network. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| [get\_site\_option()](../../functions/get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Automatic\_Updater::run()](run) wp-admin/includes/class-wp-automatic-updater.php | Kicks off the background update process, looping through all pending updates. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Automatic_Updater::should_update( string $type, object $item, string $context ): bool WP\_Automatic\_Updater::should\_update( string $type, object $item, string $context ): bool
===========================================================================================
Tests to see if we can and should update a specific item.
`$type` string Required The type of update being checked: `'core'`, `'theme'`, `'plugin'`, `'translation'`. `$item` object Required The update offer. `$context` string Required The filesystem context (a path) against which filesystem access and status should be checked. bool True if the item should be updated, false otherwise.
File: `wp-admin/includes/class-wp-automatic-updater.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-automatic-updater.php/)
```
public function should_update( $type, $item, $context ) {
// Used to see if WP_Filesystem is set up to allow unattended updates.
$skin = new Automatic_Upgrader_Skin;
if ( $this->is_disabled() ) {
return false;
}
// Only relax the filesystem checks when the update doesn't include new files.
$allow_relaxed_file_ownership = false;
if ( 'core' === $type && isset( $item->new_files ) && ! $item->new_files ) {
$allow_relaxed_file_ownership = true;
}
// If we can't do an auto core update, we may still be able to email the user.
if ( ! $skin->request_filesystem_credentials( false, $context, $allow_relaxed_file_ownership )
|| $this->is_vcs_checkout( $context )
) {
if ( 'core' === $type ) {
$this->send_core_update_notification_email( $item );
}
return false;
}
// Next up, is this an item we can update?
if ( 'core' === $type ) {
$update = Core_Upgrader::should_update_to_version( $item->current );
} elseif ( 'plugin' === $type || 'theme' === $type ) {
$update = ! empty( $item->autoupdate );
if ( ! $update && wp_is_auto_update_enabled_for_type( $type ) ) {
// Check if the site admin has enabled auto-updates by default for the specific item.
$auto_updates = (array) get_site_option( "auto_update_{$type}s", array() );
$update = in_array( $item->{$type}, $auto_updates, true );
}
} else {
$update = ! empty( $item->autoupdate );
}
// If the `disable_autoupdate` flag is set, override any user-choice, but allow filters.
if ( ! empty( $item->disable_autoupdate ) ) {
$update = $item->disable_autoupdate;
}
/**
* Filters whether to automatically update core, a plugin, a theme, or a language.
*
* The dynamic portion of the hook name, `$type`, refers to the type of update
* being checked.
*
* Possible hook names include:
*
* - `auto_update_core`
* - `auto_update_plugin`
* - `auto_update_theme`
* - `auto_update_translation`
*
* Since WordPress 3.7, minor and development versions of core, and translations have
* been auto-updated by default. New installs on WordPress 5.6 or higher will also
* auto-update major versions by default. Starting in 5.6, older sites can opt-in to
* major version auto-updates, and auto-updates for plugins and themes.
*
* See the {@see 'allow_dev_auto_core_updates'}, {@see 'allow_minor_auto_core_updates'},
* and {@see 'allow_major_auto_core_updates'} filters for a more straightforward way to
* adjust core updates.
*
* @since 3.7.0
* @since 5.5.0 The `$update` parameter accepts the value of null.
*
* @param bool|null $update Whether to update. The value of null is internally used
* to detect whether nothing has hooked into this filter.
* @param object $item The update offer.
*/
$update = apply_filters( "auto_update_{$type}", $update, $item );
if ( ! $update ) {
if ( 'core' === $type ) {
$this->send_core_update_notification_email( $item );
}
return false;
}
// If it's a core update, are we actually compatible with its requirements?
if ( 'core' === $type ) {
global $wpdb;
$php_compat = version_compare( PHP_VERSION, $item->php_version, '>=' );
if ( file_exists( WP_CONTENT_DIR . '/db.php' ) && empty( $wpdb->is_mysql ) ) {
$mysql_compat = true;
} else {
$mysql_compat = version_compare( $wpdb->db_version(), $item->mysql_version, '>=' );
}
if ( ! $php_compat || ! $mysql_compat ) {
return false;
}
}
// If updating a plugin or theme, ensure the minimum PHP version requirements are satisfied.
if ( in_array( $type, array( 'plugin', 'theme' ), true ) ) {
if ( ! empty( $item->requires_php ) && version_compare( PHP_VERSION, $item->requires_php, '<' ) ) {
return false;
}
}
return true;
}
```
[apply\_filters( "auto\_update\_{$type}", bool|null $update, object $item )](../../hooks/auto_update_type)
Filters whether to automatically update core, a plugin, a theme, or a language.
| Uses | Description |
| --- | --- |
| [wp\_is\_auto\_update\_enabled\_for\_type()](../../functions/wp_is_auto_update_enabled_for_type) wp-admin/includes/update.php | Checks whether auto-updates are enabled. |
| [WP\_Automatic\_Updater::is\_disabled()](is_disabled) wp-admin/includes/class-wp-automatic-updater.php | Determines whether the entire automatic updater is disabled. |
| [WP\_Automatic\_Updater::is\_vcs\_checkout()](is_vcs_checkout) wp-admin/includes/class-wp-automatic-updater.php | Checks for version control checkouts. |
| [WP\_Automatic\_Updater::send\_core\_update\_notification\_email()](send_core_update_notification_email) wp-admin/includes/class-wp-automatic-updater.php | Notifies an administrator of a core update. |
| [Core\_Upgrader::should\_update\_to\_version()](../core_upgrader/should_update_to_version) wp-admin/includes/class-core-upgrader.php | Determines if this WordPress Core version should update to an offered version or not. |
| [wpdb::db\_version()](../wpdb/db_version) wp-includes/class-wpdb.php | Retrieves the database server version. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_site\_option()](../../functions/get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| Used By | Description |
| --- | --- |
| [WP\_Automatic\_Updater::update()](update) wp-admin/includes/class-wp-automatic-updater.php | Updates an item, if appropriate. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Automatic_Updater::send_plugin_theme_email( string $type, array $successful_updates, array $failed_updates ) WP\_Automatic\_Updater::send\_plugin\_theme\_email( string $type, array $successful\_updates, array $failed\_updates )
======================================================================================================================
Sends an email upon the completion or failure of a plugin or theme background update.
`$type` string Required The type of email to send. Can be one of `'success'`, `'fail'`, `'mixed'`. `$successful_updates` array Required A list of updates that succeeded. `$failed_updates` array Required A list of updates that failed. File: `wp-admin/includes/class-wp-automatic-updater.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-automatic-updater.php/)
```
protected function send_plugin_theme_email( $type, $successful_updates, $failed_updates ) {
// No updates were attempted.
if ( empty( $successful_updates ) && empty( $failed_updates ) ) {
return;
}
$unique_failures = false;
$past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() );
/*
* When only failures have occurred, an email should only be sent if there are unique failures.
* A failure is considered unique if an email has not been sent for an update attempt failure
* to a plugin or theme with the same new_version.
*/
if ( 'fail' === $type ) {
foreach ( $failed_updates as $update_type => $failures ) {
foreach ( $failures as $failed_update ) {
if ( ! isset( $past_failure_emails[ $failed_update->item->{$update_type} ] ) ) {
$unique_failures = true;
continue;
}
// Check that the failure represents a new failure based on the new_version.
if ( version_compare( $past_failure_emails[ $failed_update->item->{$update_type} ], $failed_update->item->new_version, '<' ) ) {
$unique_failures = true;
}
}
}
if ( ! $unique_failures ) {
return;
}
}
$body = array();
$successful_plugins = ( ! empty( $successful_updates['plugin'] ) );
$successful_themes = ( ! empty( $successful_updates['theme'] ) );
$failed_plugins = ( ! empty( $failed_updates['plugin'] ) );
$failed_themes = ( ! empty( $failed_updates['theme'] ) );
switch ( $type ) {
case 'success':
if ( $successful_plugins && $successful_themes ) {
/* translators: %s: Site title. */
$subject = __( '[%s] Some plugins and themes have automatically updated' );
$body[] = sprintf(
/* translators: %s: Home URL. */
__( 'Howdy! Some plugins and themes have automatically updated to their latest versions on your site at %s. No further action is needed on your part.' ),
home_url()
);
} elseif ( $successful_plugins ) {
/* translators: %s: Site title. */
$subject = __( '[%s] Some plugins were automatically updated' );
$body[] = sprintf(
/* translators: %s: Home URL. */
__( 'Howdy! Some plugins have automatically updated to their latest versions on your site at %s. No further action is needed on your part.' ),
home_url()
);
} else {
/* translators: %s: Site title. */
$subject = __( '[%s] Some themes were automatically updated' );
$body[] = sprintf(
/* translators: %s: Home URL. */
__( 'Howdy! Some themes have automatically updated to their latest versions on your site at %s. No further action is needed on your part.' ),
home_url()
);
}
break;
case 'fail':
case 'mixed':
if ( $failed_plugins && $failed_themes ) {
/* translators: %s: Site title. */
$subject = __( '[%s] Some plugins and themes have failed to update' );
$body[] = sprintf(
/* translators: %s: Home URL. */
__( 'Howdy! Plugins and themes failed to update on your site at %s.' ),
home_url()
);
} elseif ( $failed_plugins ) {
/* translators: %s: Site title. */
$subject = __( '[%s] Some plugins have failed to update' );
$body[] = sprintf(
/* translators: %s: Home URL. */
__( 'Howdy! Plugins failed to update on your site at %s.' ),
home_url()
);
} else {
/* translators: %s: Site title. */
$subject = __( '[%s] Some themes have failed to update' );
$body[] = sprintf(
/* translators: %s: Home URL. */
__( 'Howdy! Themes failed to update on your site at %s.' ),
home_url()
);
}
break;
}
if ( in_array( $type, array( 'fail', 'mixed' ), true ) ) {
$body[] = "\n";
$body[] = __( 'Please check your site now. It’s possible that everything is working. If there are updates available, you should update.' );
$body[] = "\n";
// List failed plugin updates.
if ( ! empty( $failed_updates['plugin'] ) ) {
$body[] = __( 'These plugins failed to update:' );
foreach ( $failed_updates['plugin'] as $item ) {
$body_message = '';
$item_url = '';
if ( ! empty( $item->item->url ) ) {
$item_url = ' : ' . esc_url( $item->item->url );
}
if ( $item->item->current_version ) {
$body_message .= sprintf(
/* translators: 1: Plugin name, 2: Current version number, 3: New version number, 4: Plugin URL. */
__( '- %1$s (from version %2$s to %3$s)%4$s' ),
$item->name,
$item->item->current_version,
$item->item->new_version,
$item_url
);
} else {
$body_message .= sprintf(
/* translators: 1: Plugin name, 2: Version number, 3: Plugin URL. */
__( '- %1$s version %2$s%3$s' ),
$item->name,
$item->item->new_version,
$item_url
);
}
$body[] = $body_message;
$past_failure_emails[ $item->item->plugin ] = $item->item->new_version;
}
$body[] = "\n";
}
// List failed theme updates.
if ( ! empty( $failed_updates['theme'] ) ) {
$body[] = __( 'These themes failed to update:' );
foreach ( $failed_updates['theme'] as $item ) {
if ( $item->item->current_version ) {
$body[] = sprintf(
/* translators: 1: Theme name, 2: Current version number, 3: New version number. */
__( '- %1$s (from version %2$s to %3$s)' ),
$item->name,
$item->item->current_version,
$item->item->new_version
);
} else {
$body[] = sprintf(
/* translators: 1: Theme name, 2: Version number. */
__( '- %1$s version %2$s' ),
$item->name,
$item->item->new_version
);
}
$past_failure_emails[ $item->item->theme ] = $item->item->new_version;
}
$body[] = "\n";
}
}
// List successful updates.
if ( in_array( $type, array( 'success', 'mixed' ), true ) ) {
$body[] = "\n";
// List successful plugin updates.
if ( ! empty( $successful_updates['plugin'] ) ) {
$body[] = __( 'These plugins are now up to date:' );
foreach ( $successful_updates['plugin'] as $item ) {
$body_message = '';
$item_url = '';
if ( ! empty( $item->item->url ) ) {
$item_url = ' : ' . esc_url( $item->item->url );
}
if ( $item->item->current_version ) {
$body_message .= sprintf(
/* translators: 1: Plugin name, 2: Current version number, 3: New version number, 4: Plugin URL. */
__( '- %1$s (from version %2$s to %3$s)%4$s' ),
$item->name,
$item->item->current_version,
$item->item->new_version,
$item_url
);
} else {
$body_message .= sprintf(
/* translators: 1: Plugin name, 2: Version number, 3: Plugin URL. */
__( '- %1$s version %2$s%3$s' ),
$item->name,
$item->item->new_version,
$item_url
);
}
$body[] = $body_message;
unset( $past_failure_emails[ $item->item->plugin ] );
}
$body[] = "\n";
}
// List successful theme updates.
if ( ! empty( $successful_updates['theme'] ) ) {
$body[] = __( 'These themes are now up to date:' );
foreach ( $successful_updates['theme'] as $item ) {
if ( $item->item->current_version ) {
$body[] = sprintf(
/* translators: 1: Theme name, 2: Current version number, 3: New version number. */
__( '- %1$s (from version %2$s to %3$s)' ),
$item->name,
$item->item->current_version,
$item->item->new_version
);
} else {
$body[] = sprintf(
/* translators: 1: Theme name, 2: Version number. */
__( '- %1$s version %2$s' ),
$item->name,
$item->item->new_version
);
}
unset( $past_failure_emails[ $item->item->theme ] );
}
$body[] = "\n";
}
}
if ( $failed_plugins ) {
$body[] = sprintf(
/* translators: %s: Plugins screen URL. */
__( 'To manage plugins on your site, visit the Plugins page: %s' ),
admin_url( 'plugins.php' )
);
$body[] = "\n";
}
if ( $failed_themes ) {
$body[] = sprintf(
/* translators: %s: Themes screen URL. */
__( 'To manage themes on your site, visit the Themes page: %s' ),
admin_url( 'themes.php' )
);
$body[] = "\n";
}
// Add a note about the support forums.
$body[] = __( 'If you experience any issues or need support, the volunteers in the WordPress.org support forums may be able to help.' );
$body[] = __( 'https://wordpress.org/support/forums/' );
$body[] = "\n" . __( 'The WordPress Team' );
if ( '' !== get_option( 'blogname' ) ) {
$site_title = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
} else {
$site_title = parse_url( home_url(), PHP_URL_HOST );
}
$body = implode( "\n", $body );
$to = get_site_option( 'admin_email' );
$subject = sprintf( $subject, $site_title );
$headers = '';
$email = compact( 'to', 'subject', 'body', 'headers' );
/**
* Filters the email sent following an automatic background update for plugins and themes.
*
* @since 5.5.0
*
* @param array $email {
* Array of email arguments that will be passed to wp_mail().
*
* @type string $to The email recipient. An array of emails
* can be returned, as handled by wp_mail().
* @type string $subject The email's subject.
* @type string $body The email message body.
* @type string $headers Any email headers, defaults to no headers.
* }
* @param string $type The type of email being sent. Can be one of 'success', 'fail', 'mixed'.
* @param array $successful_updates A list of updates that succeeded.
* @param array $failed_updates A list of updates that failed.
*/
$email = apply_filters( 'auto_plugin_theme_update_email', $email, $type, $successful_updates, $failed_updates );
$result = wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] );
if ( $result ) {
update_option( 'auto_plugin_theme_update_emails', $past_failure_emails );
}
}
```
[apply\_filters( 'auto\_plugin\_theme\_update\_email', array $email, string $type, array $successful\_updates, array $failed\_updates )](../../hooks/auto_plugin_theme_update_email)
Filters the email sent following an automatic background update for plugins and themes.
| Uses | Description |
| --- | --- |
| [wp\_specialchars\_decode()](../../functions/wp_specialchars_decode) wp-includes/formatting.php | Converts a number of HTML entities into their special characters. |
| [wp\_mail()](../../functions/wp_mail) wp-includes/pluggable.php | Sends an email, similar to PHP’s mail function. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_site\_option()](../../functions/get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Automatic\_Updater::after\_plugin\_theme\_update()](after_plugin_theme_update) wp-admin/includes/class-wp-automatic-updater.php | If we tried to perform plugin or theme updates, check if we should send an email. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
| programming_docs |
wordpress WP_Automatic_Updater::after_plugin_theme_update( array $update_results ) WP\_Automatic\_Updater::after\_plugin\_theme\_update( array $update\_results )
==============================================================================
If we tried to perform plugin or theme updates, check if we should send an email.
`$update_results` array Required The results of update tasks. File: `wp-admin/includes/class-wp-automatic-updater.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-automatic-updater.php/)
```
protected function after_plugin_theme_update( $update_results ) {
$successful_updates = array();
$failed_updates = array();
if ( ! empty( $update_results['plugin'] ) ) {
/**
* Filters whether to send an email following an automatic background plugin update.
*
* @since 5.5.0
* @since 5.5.1 Added the `$update_results` parameter.
*
* @param bool $enabled True if plugin update notifications are enabled, false otherwise.
* @param array $update_results The results of plugins update tasks.
*/
$notifications_enabled = apply_filters( 'auto_plugin_update_send_email', true, $update_results['plugin'] );
if ( $notifications_enabled ) {
foreach ( $update_results['plugin'] as $update_result ) {
if ( true === $update_result->result ) {
$successful_updates['plugin'][] = $update_result;
} else {
$failed_updates['plugin'][] = $update_result;
}
}
}
}
if ( ! empty( $update_results['theme'] ) ) {
/**
* Filters whether to send an email following an automatic background theme update.
*
* @since 5.5.0
* @since 5.5.1 Added the `$update_results` parameter.
*
* @param bool $enabled True if theme update notifications are enabled, false otherwise.
* @param array $update_results The results of theme update tasks.
*/
$notifications_enabled = apply_filters( 'auto_theme_update_send_email', true, $update_results['theme'] );
if ( $notifications_enabled ) {
foreach ( $update_results['theme'] as $update_result ) {
if ( true === $update_result->result ) {
$successful_updates['theme'][] = $update_result;
} else {
$failed_updates['theme'][] = $update_result;
}
}
}
}
if ( empty( $successful_updates ) && empty( $failed_updates ) ) {
return;
}
if ( empty( $failed_updates ) ) {
$this->send_plugin_theme_email( 'success', $successful_updates, $failed_updates );
} elseif ( empty( $successful_updates ) ) {
$this->send_plugin_theme_email( 'fail', $successful_updates, $failed_updates );
} else {
$this->send_plugin_theme_email( 'mixed', $successful_updates, $failed_updates );
}
}
```
[apply\_filters( 'auto\_plugin\_update\_send\_email', bool $enabled, array $update\_results )](../../hooks/auto_plugin_update_send_email)
Filters whether to send an email following an automatic background plugin update.
[apply\_filters( 'auto\_theme\_update\_send\_email', bool $enabled, array $update\_results )](../../hooks/auto_theme_update_send_email)
Filters whether to send an email following an automatic background theme update.
| Uses | Description |
| --- | --- |
| [WP\_Automatic\_Updater::send\_plugin\_theme\_email()](send_plugin_theme_email) wp-admin/includes/class-wp-automatic-updater.php | Sends an email upon the completion or failure of a plugin or theme background update. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Automatic\_Updater::run()](run) wp-admin/includes/class-wp-automatic-updater.php | Kicks off the background update process, looping through all pending updates. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress AtomParser::start_element( $parser, $name, $attrs ) AtomParser::start\_element( $parser, $name, $attrs )
====================================================
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
function start_element($parser, $name, $attrs) {
$name_parts = explode(":", $name);
$tag = array_pop($name_parts);
switch($name) {
case $this->NS . ':feed':
$this->current = $this->feed;
break;
case $this->NS . ':entry':
$this->current = new AtomEntry();
break;
};
$this->_p("start_element('$name')");
#$this->_p(print_r($this->ns_contexts,true));
#$this->_p('current(' . $this->current . ')');
array_unshift($this->ns_contexts, $this->ns_decls);
$this->depth++;
if(!empty($this->in_content)) {
$this->content_ns_decls = array();
if($this->is_html || $this->is_text)
trigger_error("Invalid content in element found. Content must not be of type text or html if it contains markup.");
$attrs_prefix = array();
// resolve prefixes for attributes
foreach($attrs as $key => $value) {
$with_prefix = $this->ns_to_prefix($key, true);
$attrs_prefix[$with_prefix[1]] = $this->xml_escape($value);
}
$attrs_str = join(' ', array_map($this->map_attrs_func, array_keys($attrs_prefix), array_values($attrs_prefix)));
if(strlen($attrs_str) > 0) {
$attrs_str = " " . $attrs_str;
}
$with_prefix = $this->ns_to_prefix($name);
if(!$this->is_declared_content_ns($with_prefix[0])) {
array_push($this->content_ns_decls, $with_prefix[0]);
}
$xmlns_str = '';
if(count($this->content_ns_decls) > 0) {
array_unshift($this->content_ns_contexts, $this->content_ns_decls);
$xmlns_str .= join(' ', array_map($this->map_xmlns_func, array_keys($this->content_ns_contexts[0]), array_values($this->content_ns_contexts[0])));
if(strlen($xmlns_str) > 0) {
$xmlns_str = " " . $xmlns_str;
}
}
array_push($this->in_content, array($tag, $this->depth, "<". $with_prefix[1] ."{$xmlns_str}{$attrs_str}" . ">"));
} else if(in_array($tag, $this->ATOM_CONTENT_ELEMENTS) || in_array($tag, $this->ATOM_SIMPLE_ELEMENTS)) {
$this->in_content = array();
$this->is_xhtml = $attrs['type'] == 'xhtml';
$this->is_html = $attrs['type'] == 'html' || $attrs['type'] == 'text/html';
$this->is_text = !in_array('type',array_keys($attrs)) || $attrs['type'] == 'text';
$type = $this->is_xhtml ? 'XHTML' : ($this->is_html ? 'HTML' : ($this->is_text ? 'TEXT' : $attrs['type']));
if(in_array('src',array_keys($attrs))) {
$this->current->$tag = $attrs;
} else {
array_push($this->in_content, array($tag,$this->depth, $type));
}
} else if($tag == 'link') {
array_push($this->current->links, $attrs);
} else if($tag == 'category') {
array_push($this->current->categories, $attrs);
}
$this->ns_decls = array();
}
```
| Uses | Description |
| --- | --- |
| [AtomParser::ns\_to\_prefix()](ns_to_prefix) wp-includes/atomlib.php | |
| [AtomParser::xml\_escape()](xml_escape) wp-includes/atomlib.php | |
| [AtomParser::is\_declared\_content\_ns()](is_declared_content_ns) wp-includes/atomlib.php | |
| [AtomParser::\_p()](_p) wp-includes/atomlib.php | |
wordpress AtomParser::map_attrs( string $k, string $v ): string AtomParser::map\_attrs( string $k, string $v ): string
======================================================
Map attributes to key=”val”
`$k` string Required Key `$v` string Required Value string
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
public static function map_attrs($k, $v) {
return "$k=\"$v\"";
}
```
wordpress AtomParser::cdata( $parser, $data ) AtomParser::cdata( $parser, $data )
===================================
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
function cdata($parser, $data) {
$this->_p("data: #" . str_replace(array("\n"), array("\\n"), trim($data)) . "#");
if(!empty($this->in_content)) {
array_push($this->in_content, $data);
}
}
```
| Uses | Description |
| --- | --- |
| [AtomParser::\_p()](_p) wp-includes/atomlib.php | |
wordpress AtomParser::xml_escape( $content ) AtomParser::xml\_escape( $content )
===================================
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
function xml_escape($content)
{
return str_replace(array('&','"',"'",'<','>'),
array('&','"',''','<','>'),
$content );
}
```
| Used By | Description |
| --- | --- |
| [AtomParser::end\_element()](end_element) wp-includes/atomlib.php | |
| [AtomParser::start\_element()](start_element) wp-includes/atomlib.php | |
wordpress AtomParser::end_ns( $parser, $prefix ) AtomParser::end\_ns( $parser, $prefix )
=======================================
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
function end_ns($parser, $prefix) {
$this->_p("ending: #" . $prefix . "#");
}
```
| Uses | Description |
| --- | --- |
| [AtomParser::\_p()](_p) wp-includes/atomlib.php | |
wordpress AtomParser::_default( $parser, $data ) AtomParser::\_default( $parser, $data )
=======================================
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
function _default($parser, $data) {
# when does this gets called?
}
```
wordpress AtomParser::error_handler( $log_level, $log_text, $error_file, $error_line ) AtomParser::error\_handler( $log\_level, $log\_text, $error\_file, $error\_line )
=================================================================================
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
function error_handler($log_level, $log_text, $error_file, $error_line) {
$this->error = $log_text;
}
```
wordpress AtomParser::ns_to_prefix( $qname, $attr = false ) AtomParser::ns\_to\_prefix( $qname, $attr = false )
===================================================
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
function ns_to_prefix($qname, $attr=false) {
# split 'http://www.w3.org/1999/xhtml:div' into ('http','//www.w3.org/1999/xhtml','div')
$components = explode(":", $qname);
# grab the last one (e.g 'div')
$name = array_pop($components);
if(!empty($components)) {
# re-join back the namespace component
$ns = join(":",$components);
foreach($this->ns_contexts as $context) {
foreach($context as $mapping) {
if($mapping[1] == $ns && strlen($mapping[0]) > 0) {
return array($mapping, "$mapping[0]:$name");
}
}
}
}
if($attr) {
return array(null, $name);
} else {
foreach($this->ns_contexts as $context) {
foreach($context as $mapping) {
if(strlen($mapping[0]) == 0) {
return array($mapping, $name);
}
}
}
}
}
```
| Used By | Description |
| --- | --- |
| [AtomParser::end\_element()](end_element) wp-includes/atomlib.php | |
| [AtomParser::start\_element()](start_element) wp-includes/atomlib.php | |
wordpress AtomParser::end_element( $parser, $name ) AtomParser::end\_element( $parser, $name )
==========================================
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
function end_element($parser, $name) {
$name_parts = explode(":", $name);
$tag = array_pop($name_parts);
$ccount = count($this->in_content);
# if we are *in* content, then let's proceed to serialize it
if(!empty($this->in_content)) {
# if we are ending the original content element
# then let's finalize the content
if($this->in_content[0][0] == $tag &&
$this->in_content[0][1] == $this->depth) {
$origtype = $this->in_content[0][2];
array_shift($this->in_content);
$newcontent = array();
foreach($this->in_content as $c) {
if(count($c) == 3) {
array_push($newcontent, $c[2]);
} else {
if($this->is_xhtml || $this->is_text) {
array_push($newcontent, $this->xml_escape($c));
} else {
array_push($newcontent, $c);
}
}
}
if(in_array($tag, $this->ATOM_CONTENT_ELEMENTS)) {
$this->current->$tag = array($origtype, join('',$newcontent));
} else {
$this->current->$tag = join('',$newcontent);
}
$this->in_content = array();
} else if($this->in_content[$ccount-1][0] == $tag &&
$this->in_content[$ccount-1][1] == $this->depth) {
$this->in_content[$ccount-1][2] = substr($this->in_content[$ccount-1][2],0,-1) . "/>";
} else {
# else, just finalize the current element's content
$endtag = $this->ns_to_prefix($name);
array_push($this->in_content, array($tag, $this->depth, "</$endtag[1]>"));
}
}
array_shift($this->ns_contexts);
$this->depth--;
if($name == ($this->NS . ':entry')) {
array_push($this->feed->entries, $this->current);
$this->current = null;
}
$this->_p("end_element('$name')");
}
```
| Uses | Description |
| --- | --- |
| [AtomParser::xml\_escape()](xml_escape) wp-includes/atomlib.php | |
| [AtomParser::ns\_to\_prefix()](ns_to_prefix) wp-includes/atomlib.php | |
| [AtomParser::\_p()](_p) wp-includes/atomlib.php | |
wordpress AtomParser::is_declared_content_ns( $new_mapping ) AtomParser::is\_declared\_content\_ns( $new\_mapping )
======================================================
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
function is_declared_content_ns($new_mapping) {
foreach($this->content_ns_contexts as $context) {
foreach($context as $mapping) {
if($new_mapping == $mapping) {
return true;
}
}
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [AtomParser::start\_element()](start_element) wp-includes/atomlib.php | |
wordpress AtomParser::_p( $msg ) AtomParser::\_p( $msg )
=======================
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
function _p($msg) {
if($this->debug) {
print str_repeat(" ", $this->depth * $this->indent) . $msg ."\n";
}
}
```
| Used By | Description |
| --- | --- |
| [AtomParser::end\_element()](end_element) wp-includes/atomlib.php | |
| [AtomParser::start\_ns()](start_ns) wp-includes/atomlib.php | |
| [AtomParser::end\_ns()](end_ns) wp-includes/atomlib.php | |
| [AtomParser::cdata()](cdata) wp-includes/atomlib.php | |
| [AtomParser::start\_element()](start_element) wp-includes/atomlib.php | |
wordpress AtomParser::AtomParser() AtomParser::AtomParser()
========================
PHP4 constructor.
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
public function AtomParser() {
self::__construct();
}
```
| Uses | Description |
| --- | --- |
| [AtomParser::\_\_construct()](__construct) wp-includes/atomlib.php | PHP5 constructor. |
wordpress AtomParser::__construct() AtomParser::\_\_construct()
===========================
PHP5 constructor.
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
function __construct() {
$this->feed = new AtomFeed();
$this->current = null;
$this->map_attrs_func = array( __CLASS__, 'map_attrs' );
$this->map_xmlns_func = array( __CLASS__, 'map_xmlns' );
}
```
| Used By | Description |
| --- | --- |
| [AtomParser::AtomParser()](atomparser) wp-includes/atomlib.php | PHP4 constructor. |
wordpress AtomParser::parse() AtomParser::parse()
===================
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
function parse() {
set_error_handler(array(&$this, 'error_handler'));
array_unshift($this->ns_contexts, array());
if ( ! function_exists( 'xml_parser_create_ns' ) ) {
trigger_error( __( "PHP's XML extension is not available. Please contact your hosting provider to enable PHP's XML extension." ) );
return false;
}
$parser = xml_parser_create_ns();
xml_set_object($parser, $this);
xml_set_element_handler($parser, "start_element", "end_element");
xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,0);
xml_set_character_data_handler($parser, "cdata");
xml_set_default_handler($parser, "_default");
xml_set_start_namespace_decl_handler($parser, "start_ns");
xml_set_end_namespace_decl_handler($parser, "end_ns");
$this->content = '';
$ret = true;
$fp = fopen($this->FILE, "r");
while ($data = fread($fp, 4096)) {
if($this->debug) $this->content .= $data;
if(!xml_parse($parser, $data, feof($fp))) {
/* translators: 1: Error message, 2: Line number. */
trigger_error(sprintf(__('XML Error: %1$s at line %2$s')."\n",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
$ret = false;
break;
}
}
fclose($fp);
xml_parser_free($parser);
unset($parser);
restore_error_handler();
return $ret;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
wordpress AtomParser::map_xmlns( indexish $p, array $n ): string AtomParser::map\_xmlns( indexish $p, array $n ): string
=======================================================
Map XML namespace to string.
`$p` indexish Required XML Namespace element index `$n` array Required Two-element array pair. [ 0 => {namespace}, 1 => {url} ] string `'xmlns="{url}"'` or `'xmlns:{namespace}="{url}"'`
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
public static function map_xmlns($p, $n) {
$xd = "xmlns";
if( 0 < strlen($n[0]) ) {
$xd .= ":{$n[0]}";
}
return "{$xd}=\"{$n[1]}\"";
}
```
wordpress AtomParser::start_ns( $parser, $prefix, $uri ) AtomParser::start\_ns( $parser, $prefix, $uri )
===============================================
File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/)
```
function start_ns($parser, $prefix, $uri) {
$this->_p("starting: " . $prefix . ":" . $uri);
array_push($this->ns_decls, array($prefix,$uri));
}
```
| Uses | Description |
| --- | --- |
| [AtomParser::\_p()](_p) wp-includes/atomlib.php | |
| programming_docs |
wordpress NOOP_Translations::get_plural_forms_count(): int NOOP\_Translations::get\_plural\_forms\_count(): int
====================================================
int
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function get_plural_forms_count() {
return 2;
}
```
wordpress NOOP_Translations::add_entry( $entry ) NOOP\_Translations::add\_entry( $entry )
========================================
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function add_entry( $entry ) {
return true;
}
```
wordpress NOOP_Translations::translate_plural( string $singular, string $plural, int $count, string $context = null ) NOOP\_Translations::translate\_plural( string $singular, string $plural, int $count, string $context = null )
=============================================================================================================
`$singular` string Required `$plural` string Required `$count` int Required `$context` string Optional Default: `null`
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function translate_plural( $singular, $plural, $count, $context = null ) {
return 1 == $count ? $singular : $plural;
}
```
wordpress NOOP_Translations::translate_entry( Translation_Entry $entry ): false NOOP\_Translations::translate\_entry( Translation\_Entry $entry ): false
========================================================================
`$entry` [Translation\_Entry](../translation_entry) Required false
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function translate_entry( &$entry ) {
return false;
}
```
wordpress NOOP_Translations::get_header( string $header ): false NOOP\_Translations::get\_header( string $header ): false
========================================================
`$header` string Required false
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function get_header( $header ) {
return false;
}
```
wordpress NOOP_Translations::set_headers( array $headers ) NOOP\_Translations::set\_headers( array $headers )
==================================================
`$headers` array Required File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function set_headers( $headers ) {
}
```
wordpress NOOP_Translations::merge_with( object $other ) NOOP\_Translations::merge\_with( object $other )
================================================
`$other` object Required File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function merge_with( &$other ) {
}
```
wordpress NOOP_Translations::set_header( string $header, string $value ) NOOP\_Translations::set\_header( string $header, string $value )
================================================================
`$header` string Required `$value` string Required File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function set_header( $header, $value ) {
}
```
wordpress NOOP_Translations::select_plural_form( int $count ): bool NOOP\_Translations::select\_plural\_form( int $count ): bool
============================================================
`$count` int Required bool
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function select_plural_form( $count ) {
return 1 == $count ? 0 : 1;
}
```
wordpress NOOP_Translations::translate( string $singular, string $context = null ) NOOP\_Translations::translate( string $singular, string $context = null )
=========================================================================
`$singular` string Required `$context` string Optional Default: `null`
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function translate( $singular, $context = null ) {
return $singular;
}
```
wordpress Walker_Category::start_lvl( string $output, int $depth, array $args = array() ) Walker\_Category::start\_lvl( string $output, int $depth, array $args = array() )
=================================================================================
Starts the list before the elements are added.
* [Walker::start\_lvl()](../walker/start_lvl)
`$output` string Required Used to append additional content. Passed by reference. `$depth` int Optional Depth of category. Used for tab indentation. Default 0. `$args` array Optional An array of arguments. Will only append content if style argument value is `'list'`. See [wp\_list\_categories()](../../functions/wp_list_categories) . More Arguments from wp\_list\_categories( ... $args ) Array or string of arguments. See [WP\_Term\_Query::\_\_construct()](../wp_term_query/__construct) for information on accepted arguments. Default: `array()`
File: `wp-includes/class-walker-category.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-category.php/)
```
public function start_lvl( &$output, $depth = 0, $args = array() ) {
if ( 'list' !== $args['style'] ) {
return;
}
$indent = str_repeat( "\t", $depth );
$output .= "$indent<ul class='children'>\n";
}
```
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Walker_Category::start_el( string $output, WP_Term $data_object, int $depth, array $args = array(), int $current_object_id ) Walker\_Category::start\_el( string $output, WP\_Term $data\_object, int $depth, array $args = array(), int $current\_object\_id )
==================================================================================================================================
Starts the element output.
* [Walker::start\_el()](../walker/start_el)
`$output` string Required Used to append additional content (passed by reference). `$data_object` [WP\_Term](../wp_term) Required Category data object. `$depth` int Optional Depth of category in reference to parents. Default 0. `$args` array Optional An array of arguments. See [wp\_list\_categories()](../../functions/wp_list_categories) .
More Arguments from wp\_list\_categories( ... $args ) Array or string of arguments. See [WP\_Term\_Query::\_\_construct()](../wp_term_query/__construct) for information on accepted arguments. Default: `array()`
`$current_object_id` int Optional ID of the current category. Default 0. File: `wp-includes/class-walker-category.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-category.php/)
```
public function start_el( &$output, $data_object, $depth = 0, $args = array(), $current_object_id = 0 ) {
// Restores the more descriptive, specific name for use within this method.
$category = $data_object;
/** This filter is documented in wp-includes/category-template.php */
$cat_name = apply_filters( 'list_cats', esc_attr( $category->name ), $category );
// Don't generate an element if the category name is empty.
if ( '' === $cat_name ) {
return;
}
$atts = array();
$atts['href'] = get_term_link( $category );
if ( $args['use_desc_for_title'] && ! empty( $category->description ) ) {
/**
* Filters the category description for display.
*
* @since 1.2.0
*
* @param string $description Category description.
* @param WP_Term $category Category object.
*/
$atts['title'] = strip_tags( apply_filters( 'category_description', $category->description, $category ) );
}
/**
* Filters the HTML attributes applied to a category list item's anchor element.
*
* @since 5.2.0
*
* @param array $atts {
* The HTML attributes applied to the list item's `<a>` element, empty strings are ignored.
*
* @type string $href The href attribute.
* @type string $title The title attribute.
* }
* @param WP_Term $category Term data object.
* @param int $depth Depth of category, used for padding.
* @param array $args An array of arguments.
* @param int $current_object_id ID of the current category.
*/
$atts = apply_filters( 'category_list_link_attributes', $atts, $category, $depth, $args, $current_object_id );
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( is_scalar( $value ) && '' !== $value && false !== $value ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
$link = sprintf(
'<a%s>%s</a>',
$attributes,
$cat_name
);
if ( ! empty( $args['feed_image'] ) || ! empty( $args['feed'] ) ) {
$link .= ' ';
if ( empty( $args['feed_image'] ) ) {
$link .= '(';
}
$link .= '<a href="' . esc_url( get_term_feed_link( $category, $category->taxonomy, $args['feed_type'] ) ) . '"';
if ( empty( $args['feed'] ) ) {
/* translators: %s: Category name. */
$alt = ' alt="' . sprintf( __( 'Feed for all posts filed under %s' ), $cat_name ) . '"';
} else {
$alt = ' alt="' . $args['feed'] . '"';
$name = $args['feed'];
$link .= empty( $args['title'] ) ? '' : $args['title'];
}
$link .= '>';
if ( empty( $args['feed_image'] ) ) {
$link .= $name;
} else {
$link .= "<img src='" . esc_url( $args['feed_image'] ) . "'$alt" . ' />';
}
$link .= '</a>';
if ( empty( $args['feed_image'] ) ) {
$link .= ')';
}
}
if ( ! empty( $args['show_count'] ) ) {
$link .= ' (' . number_format_i18n( $category->count ) . ')';
}
if ( 'list' === $args['style'] ) {
$output .= "\t<li";
$css_classes = array(
'cat-item',
'cat-item-' . $category->term_id,
);
if ( ! empty( $args['current_category'] ) ) {
// 'current_category' can be an array, so we use `get_terms()`.
$_current_terms = get_terms(
array(
'taxonomy' => $category->taxonomy,
'include' => $args['current_category'],
'hide_empty' => false,
)
);
foreach ( $_current_terms as $_current_term ) {
if ( $category->term_id == $_current_term->term_id ) {
$css_classes[] = 'current-cat';
$link = str_replace( '<a', '<a aria-current="page"', $link );
} elseif ( $category->term_id == $_current_term->parent ) {
$css_classes[] = 'current-cat-parent';
}
while ( $_current_term->parent ) {
if ( $category->term_id == $_current_term->parent ) {
$css_classes[] = 'current-cat-ancestor';
break;
}
$_current_term = get_term( $_current_term->parent, $category->taxonomy );
}
}
}
/**
* Filters the list of CSS classes to include with each category in the list.
*
* @since 4.2.0
*
* @see wp_list_categories()
*
* @param string[] $css_classes An array of CSS classes to be applied to each list item.
* @param WP_Term $category Category data object.
* @param int $depth Depth of page, used for padding.
* @param array $args An array of wp_list_categories() arguments.
*/
$css_classes = implode( ' ', apply_filters( 'category_css_class', $css_classes, $category, $depth, $args ) );
$css_classes = $css_classes ? ' class="' . esc_attr( $css_classes ) . '"' : '';
$output .= $css_classes;
$output .= ">$link\n";
} elseif ( isset( $args['separator'] ) ) {
$output .= "\t$link" . $args['separator'] . "\n";
} else {
$output .= "\t$link<br />\n";
}
}
```
[apply\_filters( 'category\_css\_class', string[] $css\_classes, WP\_Term $category, int $depth, array $args )](../../hooks/category_css_class)
Filters the list of CSS classes to include with each category in the list.
[apply\_filters( 'category\_description', string $description, WP\_Term $category )](../../hooks/category_description)
Filters the category description for display.
[apply\_filters( 'category\_list\_link\_attributes', array $atts, WP\_Term $category, int $depth, array $args, int $current\_object\_id )](../../hooks/category_list_link_attributes)
Filters the HTML attributes applied to a category list item’s anchor element.
[apply\_filters( 'list\_cats', string $element, WP\_Term|null $category )](../../hooks/list_cats)
Filters a taxonomy drop-down display element.
| Uses | Description |
| --- | --- |
| [get\_term\_link()](../../functions/get_term_link) wp-includes/taxonomy.php | Generates a permalink for a taxonomy term archive. |
| [get\_terms()](../../functions/get_terms) wp-includes/taxonomy.php | Retrieves the terms in a given taxonomy or list of taxonomies. |
| [get\_term\_feed\_link()](../../functions/get_term_feed_link) wp-includes/link-template.php | Retrieves the feed link for a term. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| [get\_term()](../../functions/get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$category` to `$data_object` and `$id` to `$current_object_id` to match parent class for PHP 8 named parameter support. |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Walker_Category::end_lvl( string $output, int $depth, array $args = array() ) Walker\_Category::end\_lvl( string $output, int $depth, array $args = array() )
===============================================================================
Ends the list of after the elements are added.
* [Walker::end\_lvl()](../walker/end_lvl)
`$output` string Required Used to append additional content. Passed by reference. `$depth` int Optional Depth of category. Used for tab indentation. Default 0. `$args` array Optional An array of arguments. Will only append content if style argument value is `'list'`. See [wp\_list\_categories()](../../functions/wp_list_categories) . More Arguments from wp\_list\_categories( ... $args ) Array or string of arguments. See [WP\_Term\_Query::\_\_construct()](../wp_term_query/__construct) for information on accepted arguments. Default: `array()`
File: `wp-includes/class-walker-category.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-category.php/)
```
public function end_lvl( &$output, $depth = 0, $args = array() ) {
if ( 'list' !== $args['style'] ) {
return;
}
$indent = str_repeat( "\t", $depth );
$output .= "$indent</ul>\n";
}
```
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Walker_Category::end_el( string $output, object $data_object, int $depth, array $args = array() ) Walker\_Category::end\_el( string $output, object $data\_object, int $depth, array $args = array() )
====================================================================================================
Ends the element output, if needed.
* [Walker::end\_el()](../walker/end_el)
`$output` string Required Used to append additional content (passed by reference). `$data_object` object Required Category data object. Not used. `$depth` int Optional Depth of category. Not used. `$args` array Optional An array of arguments. Only uses `'list'` for whether should append to output. See [wp\_list\_categories()](../../functions/wp_list_categories) . More Arguments from wp\_list\_categories( ... $args ) Array or string of arguments. See [WP\_Term\_Query::\_\_construct()](../wp_term_query/__construct) for information on accepted arguments. Default: `array()`
File: `wp-includes/class-walker-category.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-category.php/)
```
public function end_el( &$output, $data_object, $depth = 0, $args = array() ) {
if ( 'list' !== $args['style'] ) {
return;
}
$output .= "</li>\n";
}
```
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$page` to `$data_object` to match parent class for PHP 8 named parameter support. |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress IXR_Base64::IXR_Base64( $data ) IXR\_Base64::IXR\_Base64( $data )
=================================
PHP4 constructor.
File: `wp-includes/IXR/class-IXR-base64.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-base64.php/)
```
public function IXR_Base64( $data ) {
self::__construct( $data );
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Base64::\_\_construct()](__construct) wp-includes/IXR/class-IXR-base64.php | PHP5 constructor. |
wordpress IXR_Base64::getXml() IXR\_Base64::getXml()
=====================
File: `wp-includes/IXR/class-IXR-base64.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-base64.php/)
```
function getXml()
{
return '<base64>'.base64_encode($this->data).'</base64>';
}
```
wordpress IXR_Base64::__construct( $data ) IXR\_Base64::\_\_construct( $data )
===================================
PHP5 constructor.
File: `wp-includes/IXR/class-IXR-base64.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-base64.php/)
```
function __construct( $data )
{
$this->data = $data;
}
```
| Used By | Description |
| --- | --- |
| [IXR\_Base64::IXR\_Base64()](ixr_base64) wp-includes/IXR/class-IXR-base64.php | PHP4 constructor. |
| [IXR\_IntrospectionServer::methodSignature()](../ixr_introspectionserver/methodsignature) wp-includes/IXR/class-IXR-introspectionserver.php | |
wordpress WP_Posts_List_Table::is_base_request(): bool WP\_Posts\_List\_Table::is\_base\_request(): bool
=================================================
Determine if the current view is the “All” view.
bool Whether the current view is the "All" view.
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
protected function is_base_request() {
$vars = $_GET;
unset( $vars['paged'] );
if ( empty( $vars ) ) {
return true;
} elseif ( 1 === count( $vars ) && ! empty( $vars['post_type'] ) ) {
return $this->screen->post_type === $vars['post_type'];
}
return 1 === count( $vars ) && ! empty( $vars['mode'] );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::get\_views()](get_views) wp-admin/includes/class-wp-posts-list-table.php | |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Posts_List_Table::single_row( int|WP_Post $post, int $level ) WP\_Posts\_List\_Table::single\_row( int|WP\_Post $post, int $level )
=====================================================================
`$post` int|[WP\_Post](../wp_post) Required `$level` int Required File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function single_row( $post, $level = 0 ) {
$global_post = get_post();
$post = get_post( $post );
$this->current_level = $level;
$GLOBALS['post'] = $post;
setup_postdata( $post );
$classes = 'iedit author-' . ( get_current_user_id() === (int) $post->post_author ? 'self' : 'other' );
$lock_holder = wp_check_post_lock( $post->ID );
if ( $lock_holder ) {
$classes .= ' wp-locked';
}
if ( $post->post_parent ) {
$count = count( get_post_ancestors( $post->ID ) );
$classes .= ' level-' . $count;
} else {
$classes .= ' level-0';
}
?>
<tr id="post-<?php echo $post->ID; ?>" class="<?php echo implode( ' ', get_post_class( $classes, $post->ID ) ); ?>">
<?php $this->single_row_columns( $post ); ?>
</tr>
<?php
$GLOBALS['post'] = $global_post;
}
```
| Uses | Description |
| --- | --- |
| [wp\_check\_post\_lock()](../../functions/wp_check_post_lock) wp-admin/includes/post.php | Determines whether the post is currently being edited by another user. |
| [setup\_postdata()](../../functions/setup_postdata) wp-includes/query.php | Set up global post data. |
| [get\_post\_class()](../../functions/get_post_class) wp-includes/post-template.php | Retrieves an array of the class names for the post container element. |
| [get\_post\_ancestors()](../../functions/get_post_ancestors) wp-includes/post.php | Retrieves the IDs of the ancestors of a post. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::\_display\_rows()](_display_rows) wp-admin/includes/class-wp-posts-list-table.php | |
| [WP\_Posts\_List\_Table::\_display\_rows\_hierarchical()](_display_rows_hierarchical) wp-admin/includes/class-wp-posts-list-table.php | |
wordpress WP_Posts_List_Table::extra_tablenav( string $which ) WP\_Posts\_List\_Table::extra\_tablenav( string $which )
========================================================
`$which` string Required File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
protected function extra_tablenav( $which ) {
?>
<div class="alignleft actions">
<?php
if ( 'top' === $which ) {
ob_start();
$this->months_dropdown( $this->screen->post_type );
$this->categories_dropdown( $this->screen->post_type );
$this->formats_dropdown( $this->screen->post_type );
/**
* Fires before the Filter button on the Posts and Pages list tables.
*
* The Filter button allows sorting by date and/or category on the
* Posts list table, and sorting by date on the Pages list table.
*
* @since 2.1.0
* @since 4.4.0 The `$post_type` parameter was added.
* @since 4.6.0 The `$which` parameter was added.
*
* @param string $post_type The post type slug.
* @param string $which The location of the extra table nav markup:
* 'top' or 'bottom' for WP_Posts_List_Table,
* 'bar' for WP_Media_List_Table.
*/
do_action( 'restrict_manage_posts', $this->screen->post_type, $which );
$output = ob_get_clean();
if ( ! empty( $output ) ) {
echo $output;
submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
}
}
if ( $this->is_trash && $this->has_items()
&& current_user_can( get_post_type_object( $this->screen->post_type )->cap->edit_others_posts )
) {
submit_button( __( 'Empty Trash' ), 'apply', 'delete_all', false );
}
?>
</div>
<?php
/**
* Fires immediately following the closing "actions" div in the tablenav for the posts
* list table.
*
* @since 4.4.0
*
* @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
*/
do_action( 'manage_posts_extra_tablenav', $which );
}
```
[do\_action( 'manage\_posts\_extra\_tablenav', string $which )](../../hooks/manage_posts_extra_tablenav)
Fires immediately following the closing “actions” div in the tablenav for the posts list table.
[do\_action( 'restrict\_manage\_posts', string $post\_type, string $which )](../../hooks/restrict_manage_posts)
Fires before the Filter button on the Posts and Pages list tables.
| Uses | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::formats\_dropdown()](formats_dropdown) wp-admin/includes/class-wp-posts-list-table.php | Displays a formats drop-down for filtering items. |
| [WP\_Posts\_List\_Table::categories\_dropdown()](categories_dropdown) wp-admin/includes/class-wp-posts-list-table.php | Displays a categories drop-down for filtering on the Posts list table. |
| [submit\_button()](../../functions/submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [WP\_Posts\_List\_Table::has\_items()](has_items) wp-admin/includes/class-wp-posts-list-table.php | |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
wordpress WP_Posts_List_Table::current_action(): string WP\_Posts\_List\_Table::current\_action(): string
=================================================
string
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function current_action() {
if ( isset( $_REQUEST['delete_all'] ) || isset( $_REQUEST['delete_all2'] ) ) {
return 'delete_all';
}
return parent::current_action();
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::current\_action()](../wp_list_table/current_action) wp-admin/includes/class-wp-list-table.php | Gets the current action selected from the bulk actions dropdown. |
wordpress WP_Posts_List_Table::get_edit_link( string[] $args, string $link_text, string $css_class = '' ): string WP\_Posts\_List\_Table::get\_edit\_link( string[] $args, string $link\_text, string $css\_class = '' ): string
==============================================================================================================
Helper to create links to edit.php with params.
`$args` string[] Required Associative array of URL parameters for the link. `$link_text` string Required Link text. `$css_class` string Optional Class attribute. Default: `''`
string The formatted link string.
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
protected function get_edit_link( $args, $link_text, $css_class = '' ) {
$url = add_query_arg( $args, 'edit.php' );
$class_html = '';
$aria_current = '';
if ( ! empty( $css_class ) ) {
$class_html = sprintf(
' class="%s"',
esc_attr( $css_class )
);
if ( 'current' === $css_class ) {
$aria_current = ' aria-current="page"';
}
}
return sprintf(
'<a href="%s"%s%s>%s</a>',
esc_url( $url ),
$class_html,
$aria_current,
$link_text
);
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::column\_author()](column_author) wp-admin/includes/class-wp-posts-list-table.php | Handles the post author column output. |
| [WP\_Posts\_List\_Table::column\_default()](column_default) wp-admin/includes/class-wp-posts-list-table.php | Handles the default column output. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Posts_List_Table::prepare_items() WP\_Posts\_List\_Table::prepare\_items()
========================================
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function prepare_items() {
global $mode, $avail_post_stati, $wp_query, $per_page;
if ( ! empty( $_REQUEST['mode'] ) ) {
$mode = 'excerpt' === $_REQUEST['mode'] ? 'excerpt' : 'list';
set_user_setting( 'posts_list_mode', $mode );
} else {
$mode = get_user_setting( 'posts_list_mode', 'list' );
}
// Is going to call wp().
$avail_post_stati = wp_edit_posts_query();
$this->set_hierarchical_display(
is_post_type_hierarchical( $this->screen->post_type )
&& 'menu_order title' === $wp_query->query['orderby']
);
$post_type = $this->screen->post_type;
$per_page = $this->get_items_per_page( 'edit_' . $post_type . '_per_page' );
/** This filter is documented in wp-admin/includes/post.php */
$per_page = apply_filters( 'edit_posts_per_page', $per_page, $post_type );
if ( $this->hierarchical_display ) {
$total_items = $wp_query->post_count;
} elseif ( $wp_query->found_posts || $this->get_pagenum() === 1 ) {
$total_items = $wp_query->found_posts;
} else {
$post_counts = (array) wp_count_posts( $post_type, 'readable' );
if ( isset( $_REQUEST['post_status'] ) && in_array( $_REQUEST['post_status'], $avail_post_stati, true ) ) {
$total_items = $post_counts[ $_REQUEST['post_status'] ];
} elseif ( isset( $_REQUEST['show_sticky'] ) && $_REQUEST['show_sticky'] ) {
$total_items = $this->sticky_posts_count;
} elseif ( isset( $_GET['author'] ) && get_current_user_id() === (int) $_GET['author'] ) {
$total_items = $this->user_posts_count;
} else {
$total_items = array_sum( $post_counts );
// Subtract post types that are not included in the admin all list.
foreach ( get_post_stati( array( 'show_in_admin_all_list' => false ) ) as $state ) {
$total_items -= $post_counts[ $state ];
}
}
}
$this->is_trash = isset( $_REQUEST['post_status'] ) && 'trash' === $_REQUEST['post_status'];
$this->set_pagination_args(
array(
'total_items' => $total_items,
'per_page' => $per_page,
)
);
}
```
[apply\_filters( 'edit\_posts\_per\_page', int $posts\_per\_page, string $post\_type )](../../hooks/edit_posts_per_page)
Filters the number of posts displayed per page when specifically listing “posts”.
| Uses | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::set\_hierarchical\_display()](set_hierarchical_display) wp-admin/includes/class-wp-posts-list-table.php | Sets whether the table layout should be hierarchical or not. |
| [wp\_edit\_posts\_query()](../../functions/wp_edit_posts_query) wp-admin/includes/post.php | Runs the query to fetch the posts for listing on the edit posts page. |
| [set\_user\_setting()](../../functions/set_user_setting) wp-includes/option.php | Adds or updates user interface setting. |
| [get\_user\_setting()](../../functions/get_user_setting) wp-includes/option.php | Retrieves user interface setting value based on setting name. |
| [wp\_count\_posts()](../../functions/wp_count_posts) wp-includes/post.php | Counts number of posts of a post type and if user has permissions to view. |
| [is\_post\_type\_hierarchical()](../../functions/is_post_type_hierarchical) wp-includes/post.php | Determines whether the post type is hierarchical. |
| [get\_post\_stati()](../../functions/get_post_stati) wp-includes/post.php | Gets a list of post statuses. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
wordpress WP_Posts_List_Table::column_title( WP_Post $post ) WP\_Posts\_List\_Table::column\_title( WP\_Post $post )
=======================================================
Handles the title column output.
`$post` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function column_title( $post ) {
global $mode;
if ( $this->hierarchical_display ) {
if ( 0 === $this->current_level && (int) $post->post_parent > 0 ) {
// Sent level 0 by accident, by default, or because we don't know the actual level.
$find_main_page = (int) $post->post_parent;
while ( $find_main_page > 0 ) {
$parent = get_post( $find_main_page );
if ( is_null( $parent ) ) {
break;
}
$this->current_level++;
$find_main_page = (int) $parent->post_parent;
if ( ! isset( $parent_name ) ) {
/** This filter is documented in wp-includes/post-template.php */
$parent_name = apply_filters( 'the_title', $parent->post_title, $parent->ID );
}
}
}
}
$can_edit_post = current_user_can( 'edit_post', $post->ID );
if ( $can_edit_post && 'trash' !== $post->post_status ) {
$lock_holder = wp_check_post_lock( $post->ID );
if ( $lock_holder ) {
$lock_holder = get_userdata( $lock_holder );
$locked_avatar = get_avatar( $lock_holder->ID, 18 );
/* translators: %s: User's display name. */
$locked_text = esc_html( sprintf( __( '%s is currently editing' ), $lock_holder->display_name ) );
} else {
$locked_avatar = '';
$locked_text = '';
}
echo '<div class="locked-info"><span class="locked-avatar">' . $locked_avatar . '</span> <span class="locked-text">' . $locked_text . "</span></div>\n";
}
$pad = str_repeat( '— ', $this->current_level );
echo '<strong>';
$title = _draft_or_post_title();
if ( $can_edit_post && 'trash' !== $post->post_status ) {
printf(
'<a class="row-title" href="%s" aria-label="%s">%s%s</a>',
get_edit_post_link( $post->ID ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( '“%s” (Edit)' ), $title ) ),
$pad,
$title
);
} else {
printf(
'<span>%s%s</span>',
$pad,
$title
);
}
_post_states( $post );
if ( isset( $parent_name ) ) {
$post_type_object = get_post_type_object( $post->post_type );
echo ' | ' . $post_type_object->labels->parent_item_colon . ' ' . esc_html( $parent_name );
}
echo "</strong>\n";
if ( 'excerpt' === $mode
&& ! is_post_type_hierarchical( $this->screen->post_type )
&& current_user_can( 'read_post', $post->ID )
) {
if ( post_password_required( $post ) ) {
echo '<span class="protected-post-excerpt">' . esc_html( get_the_excerpt() ) . '</span>';
} else {
echo esc_html( get_the_excerpt() );
}
}
get_inline_data( $post );
}
```
[apply\_filters( 'the\_title', string $post\_title, int $post\_id )](../../hooks/the_title)
Filters the post title.
| Uses | Description |
| --- | --- |
| [\_draft\_or\_post\_title()](../../functions/_draft_or_post_title) wp-admin/includes/template.php | Gets the post title. |
| [\_post\_states()](../../functions/_post_states) wp-admin/includes/template.php | Echoes or returns the post states as HTML. |
| [get\_the\_excerpt()](../../functions/get_the_excerpt) wp-includes/post-template.php | Retrieves the post excerpt. |
| [post\_password\_required()](../../functions/post_password_required) wp-includes/post-template.php | Determines whether the post requires password and whether a correct password has been provided. |
| [get\_edit\_post\_link()](../../functions/get_edit_post_link) wp-includes/link-template.php | Retrieves the edit post link for post. |
| [get\_avatar()](../../functions/get_avatar) wp-includes/pluggable.php | Retrieves the avatar `<img>` tag for a user, email address, MD5 hash, comment, or post. |
| [wp\_check\_post\_lock()](../../functions/wp_check_post_lock) wp-admin/includes/post.php | Determines whether the post is currently being edited by another user. |
| [get\_inline\_data()](../../functions/get_inline_data) wp-admin/includes/template.php | Adds hidden fields with the data for use in the inline editor for posts and pages. |
| [is\_post\_type\_hierarchical()](../../functions/is_post_type_hierarchical) wp-includes/post.php | Determines whether the post type is hierarchical. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_userdata()](../../functions/get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::\_column\_title()](_column_title) wp-admin/includes/class-wp-posts-list-table.php | |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Posts_List_Table::ajax_user_can(): bool WP\_Posts\_List\_Table::ajax\_user\_can(): bool
===============================================
bool
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function ajax_user_can() {
return current_user_can( get_post_type_object( $this->screen->post_type )->cap->edit_posts );
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
wordpress WP_Posts_List_Table::display_rows( array $posts = array(), int $level ) WP\_Posts\_List\_Table::display\_rows( array $posts = array(), int $level )
===========================================================================
`$posts` array Optional Default: `array()`
`$level` int Required File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function display_rows( $posts = array(), $level = 0 ) {
global $wp_query, $per_page;
if ( empty( $posts ) ) {
$posts = $wp_query->posts;
}
add_filter( 'the_title', 'esc_html' );
if ( $this->hierarchical_display ) {
$this->_display_rows_hierarchical( $posts, $this->get_pagenum(), $per_page );
} else {
$this->_display_rows( $posts, $level );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::\_display\_rows\_hierarchical()](_display_rows_hierarchical) wp-admin/includes/class-wp-posts-list-table.php | |
| [WP\_Posts\_List\_Table::\_display\_rows()](_display_rows) wp-admin/includes/class-wp-posts-list-table.php | |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| programming_docs |
wordpress WP_Posts_List_Table::column_author( WP_Post $post ) WP\_Posts\_List\_Table::column\_author( WP\_Post $post )
========================================================
Handles the post author column output.
`$post` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function column_author( $post ) {
$args = array(
'post_type' => $post->post_type,
'author' => get_the_author_meta( 'ID' ),
);
echo $this->get_edit_link( $args, get_the_author() );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::get\_edit\_link()](get_edit_link) wp-admin/includes/class-wp-posts-list-table.php | Helper to create links to edit.php with params. |
| [get\_the\_author\_meta()](../../functions/get_the_author_meta) wp-includes/author-template.php | Retrieves the requested data of the author of the current post. |
| [get\_the\_author()](../../functions/get_the_author) wp-includes/author-template.php | Retrieves the author of the current post. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Posts_List_Table::_column_title( WP_Post $post, string $classes, string $data, string $primary ) WP\_Posts\_List\_Table::\_column\_title( WP\_Post $post, string $classes, string $data, string $primary )
=========================================================================================================
`$post` [WP\_Post](../wp_post) Required `$classes` string Required `$data` string Required `$primary` string Required File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
protected function _column_title( $post, $classes, $data, $primary ) {
echo '<td class="' . $classes . ' page-title" ', $data, '>';
echo $this->column_title( $post );
echo $this->handle_row_actions( $post, 'title', $primary );
echo '</td>';
}
```
| Uses | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::handle\_row\_actions()](handle_row_actions) wp-admin/includes/class-wp-posts-list-table.php | Generates and displays row action links. |
| [WP\_Posts\_List\_Table::column\_title()](column_title) wp-admin/includes/class-wp-posts-list-table.php | Handles the title column output. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Posts_List_Table::no_items() WP\_Posts\_List\_Table::no\_items()
===================================
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function no_items() {
if ( isset( $_REQUEST['post_status'] ) && 'trash' === $_REQUEST['post_status'] ) {
echo get_post_type_object( $this->screen->post_type )->labels->not_found_in_trash;
} else {
echo get_post_type_object( $this->screen->post_type )->labels->not_found;
}
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
wordpress WP_Posts_List_Table::_page_rows( array $children_pages, int $count, int $parent_page, int $level, int $pagenum, int $per_page, array $to_display ) WP\_Posts\_List\_Table::\_page\_rows( array $children\_pages, int $count, int $parent\_page, int $level, int $pagenum, int $per\_page, array $to\_display )
===========================================================================================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Given a top level page ID, display the nested hierarchy of sub-pages together with paging support
`$children_pages` array Required `$count` int Required `$parent_page` int Required `$level` int Required `$pagenum` int Required `$per_page` int Required `$to_display` array Required List of pages to be displayed. Passed by reference. File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
private function _page_rows( &$children_pages, &$count, $parent_page, $level, $pagenum, $per_page, &$to_display ) {
if ( ! isset( $children_pages[ $parent_page ] ) ) {
return;
}
$start = ( $pagenum - 1 ) * $per_page;
$end = $start + $per_page;
foreach ( $children_pages[ $parent_page ] as $page ) {
if ( $count >= $end ) {
break;
}
// If the page starts in a subtree, print the parents.
if ( $count === $start && $page->post_parent > 0 ) {
$my_parents = array();
$my_parent = $page->post_parent;
while ( $my_parent ) {
// Get the ID from the list or the attribute if my_parent is an object.
$parent_id = $my_parent;
if ( is_object( $my_parent ) ) {
$parent_id = $my_parent->ID;
}
$my_parent = get_post( $parent_id );
$my_parents[] = $my_parent;
if ( ! $my_parent->post_parent ) {
break;
}
$my_parent = $my_parent->post_parent;
}
$num_parents = count( $my_parents );
while ( $my_parent = array_pop( $my_parents ) ) {
$to_display[ $my_parent->ID ] = $level - $num_parents;
$num_parents--;
}
}
if ( $count >= $start ) {
$to_display[ $page->ID ] = $level;
}
$count++;
$this->_page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page, $to_display );
}
unset( $children_pages[ $parent_page ] ); // Required in order to keep track of orphans.
}
```
| Uses | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::\_page\_rows()](_page_rows) wp-admin/includes/class-wp-posts-list-table.php | Given a top level page ID, display the nested hierarchy of sub-pages together with paging support |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::\_display\_rows\_hierarchical()](_display_rows_hierarchical) wp-admin/includes/class-wp-posts-list-table.php | |
| [WP\_Posts\_List\_Table::\_page\_rows()](_page_rows) wp-admin/includes/class-wp-posts-list-table.php | Given a top level page ID, display the nested hierarchy of sub-pages together with paging support |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Added the `$to_display` parameter. |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Posts_List_Table::get_default_primary_column_name(): string WP\_Posts\_List\_Table::get\_default\_primary\_column\_name(): string
=====================================================================
Gets the name of the default primary column.
string Name of the default primary column, in this case, `'title'`.
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
protected function get_default_primary_column_name() {
return 'title';
}
```
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Posts_List_Table::_display_rows( array $posts, int $level ) WP\_Posts\_List\_Table::\_display\_rows( array $posts, int $level )
===================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
`$posts` array Required `$level` int Required File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
private function _display_rows( $posts, $level = 0 ) {
$post_type = $this->screen->post_type;
// Create array of post IDs.
$post_ids = array();
foreach ( $posts as $a_post ) {
$post_ids[] = $a_post->ID;
}
if ( post_type_supports( $post_type, 'comments' ) ) {
$this->comment_pending_count = get_pending_comments_num( $post_ids );
}
update_post_author_caches( $posts );
foreach ( $posts as $post ) {
$this->single_row( $post, $level );
}
}
```
| Uses | Description |
| --- | --- |
| [update\_post\_author\_caches()](../../functions/update_post_author_caches) wp-includes/post.php | Updates post author user caches for a list of post objects. |
| [WP\_Posts\_List\_Table::single\_row()](single_row) wp-admin/includes/class-wp-posts-list-table.php | |
| [get\_pending\_comments\_num()](../../functions/get_pending_comments_num) wp-admin/includes/comment.php | Gets the number of pending comments on a post or posts. |
| [post\_type\_supports()](../../functions/post_type_supports) wp-includes/post.php | Checks a post type’s support for a given feature. |
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::display\_rows()](display_rows) wp-admin/includes/class-wp-posts-list-table.php | |
wordpress WP_Posts_List_Table::handle_row_actions( WP_Post $item, string $column_name, string $primary ): string WP\_Posts\_List\_Table::handle\_row\_actions( WP\_Post $item, string $column\_name, string $primary ): string
=============================================================================================================
Generates and displays row action links.
`$item` [WP\_Post](../wp_post) Required Post being acted upon. `$column_name` string Required Current column name. `$primary` string Required Primary column name. string Row actions output for posts, or an empty string if the current column is not the primary column.
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
protected function handle_row_actions( $item, $column_name, $primary ) {
if ( $primary !== $column_name ) {
return '';
}
// Restores the more descriptive, specific name for use within this method.
$post = $item;
$post_type_object = get_post_type_object( $post->post_type );
$can_edit_post = current_user_can( 'edit_post', $post->ID );
$actions = array();
$title = _draft_or_post_title();
if ( $can_edit_post && 'trash' !== $post->post_status ) {
$actions['edit'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
get_edit_post_link( $post->ID ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Edit “%s”' ), $title ) ),
__( 'Edit' )
);
if ( 'wp_block' !== $post->post_type ) {
$actions['inline hide-if-no-js'] = sprintf(
'<button type="button" class="button-link editinline" aria-label="%s" aria-expanded="false">%s</button>',
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Quick edit “%s” inline' ), $title ) ),
__( 'Quick Edit' )
);
}
}
if ( current_user_can( 'delete_post', $post->ID ) ) {
if ( 'trash' === $post->post_status ) {
$actions['untrash'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
wp_nonce_url( admin_url( sprintf( $post_type_object->_edit_link . '&action=untrash', $post->ID ) ), 'untrash-post_' . $post->ID ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Restore “%s” from the Trash' ), $title ) ),
__( 'Restore' )
);
} elseif ( EMPTY_TRASH_DAYS ) {
$actions['trash'] = sprintf(
'<a href="%s" class="submitdelete" aria-label="%s">%s</a>',
get_delete_post_link( $post->ID ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Move “%s” to the Trash' ), $title ) ),
_x( 'Trash', 'verb' )
);
}
if ( 'trash' === $post->post_status || ! EMPTY_TRASH_DAYS ) {
$actions['delete'] = sprintf(
'<a href="%s" class="submitdelete" aria-label="%s">%s</a>',
get_delete_post_link( $post->ID, '', true ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Delete “%s” permanently' ), $title ) ),
__( 'Delete Permanently' )
);
}
}
if ( is_post_type_viewable( $post_type_object ) ) {
if ( in_array( $post->post_status, array( 'pending', 'draft', 'future' ), true ) ) {
if ( $can_edit_post ) {
$preview_link = get_preview_post_link( $post );
$actions['view'] = sprintf(
'<a href="%s" rel="bookmark" aria-label="%s">%s</a>',
esc_url( $preview_link ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Preview “%s”' ), $title ) ),
__( 'Preview' )
);
}
} elseif ( 'trash' !== $post->post_status ) {
$actions['view'] = sprintf(
'<a href="%s" rel="bookmark" aria-label="%s">%s</a>',
get_permalink( $post->ID ),
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'View “%s”' ), $title ) ),
__( 'View' )
);
}
}
if ( 'wp_block' === $post->post_type ) {
$actions['export'] = sprintf(
'<button type="button" class="wp-list-reusable-blocks__export button-link" data-id="%s" aria-label="%s">%s</button>',
$post->ID,
/* translators: %s: Post title. */
esc_attr( sprintf( __( 'Export “%s” as JSON' ), $title ) ),
__( 'Export as JSON' )
);
}
if ( is_post_type_hierarchical( $post->post_type ) ) {
/**
* Filters the array of row action links on the Pages list table.
*
* The filter is evaluated only for hierarchical post types.
*
* @since 2.8.0
*
* @param string[] $actions An array of row action links. Defaults are
* 'Edit', 'Quick Edit', 'Restore', 'Trash',
* 'Delete Permanently', 'Preview', and 'View'.
* @param WP_Post $post The post object.
*/
$actions = apply_filters( 'page_row_actions', $actions, $post );
} else {
/**
* Filters the array of row action links on the Posts list table.
*
* The filter is evaluated only for non-hierarchical post types.
*
* @since 2.8.0
*
* @param string[] $actions An array of row action links. Defaults are
* 'Edit', 'Quick Edit', 'Restore', 'Trash',
* 'Delete Permanently', 'Preview', and 'View'.
* @param WP_Post $post The post object.
*/
$actions = apply_filters( 'post_row_actions', $actions, $post );
}
return $this->row_actions( $actions );
}
```
[apply\_filters( 'page\_row\_actions', string[] $actions, WP\_Post $post )](../../hooks/page_row_actions)
Filters the array of row action links on the Pages list table.
[apply\_filters( 'post\_row\_actions', string[] $actions, WP\_Post $post )](../../hooks/post_row_actions)
Filters the array of row action links on the Posts list table.
| Uses | Description |
| --- | --- |
| [get\_preview\_post\_link()](../../functions/get_preview_post_link) wp-includes/link-template.php | Retrieves the URL used for the post preview. |
| [is\_post\_type\_viewable()](../../functions/is_post_type_viewable) wp-includes/post.php | Determines whether a post type is considered “viewable”. |
| [\_draft\_or\_post\_title()](../../functions/_draft_or_post_title) wp-admin/includes/template.php | Gets the post title. |
| [get\_edit\_post\_link()](../../functions/get_edit_post_link) wp-includes/link-template.php | Retrieves the edit post link for post. |
| [get\_delete\_post\_link()](../../functions/get_delete_post_link) wp-includes/link-template.php | Retrieves the delete posts link for post. |
| [is\_post\_type\_hierarchical()](../../functions/is_post_type_hierarchical) wp-includes/post.php | Determines whether the post type is hierarchical. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [wp\_nonce\_url()](../../functions/wp_nonce_url) wp-includes/functions.php | Retrieves URL with nonce added to URL query. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [get\_permalink()](../../functions/get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::\_column\_title()](_column_title) wp-admin/includes/class-wp-posts-list-table.php | |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Posts_List_Table::get_views(): array WP\_Posts\_List\_Table::get\_views(): array
===========================================
array
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
protected function get_views() {
global $locked_post_status, $avail_post_stati;
$post_type = $this->screen->post_type;
if ( ! empty( $locked_post_status ) ) {
return array();
}
$status_links = array();
$num_posts = wp_count_posts( $post_type, 'readable' );
$total_posts = array_sum( (array) $num_posts );
$class = '';
$current_user_id = get_current_user_id();
$all_args = array( 'post_type' => $post_type );
$mine = '';
// Subtract post types that are not included in the admin all list.
foreach ( get_post_stati( array( 'show_in_admin_all_list' => false ) ) as $state ) {
$total_posts -= $num_posts->$state;
}
if ( $this->user_posts_count && $this->user_posts_count !== $total_posts ) {
if ( isset( $_GET['author'] ) && ( $current_user_id === (int) $_GET['author'] ) ) {
$class = 'current';
}
$mine_args = array(
'post_type' => $post_type,
'author' => $current_user_id,
);
$mine_inner_html = sprintf(
/* translators: %s: Number of posts. */
_nx(
'Mine <span class="count">(%s)</span>',
'Mine <span class="count">(%s)</span>',
$this->user_posts_count,
'posts'
),
number_format_i18n( $this->user_posts_count )
);
$mine = array(
'url' => esc_url( add_query_arg( $mine_args, 'edit.php' ) ),
'label' => $mine_inner_html,
'current' => isset( $_GET['author'] ) && ( $current_user_id === (int) $_GET['author'] ),
);
$all_args['all_posts'] = 1;
$class = '';
}
$all_inner_html = sprintf(
/* translators: %s: Number of posts. */
_nx(
'All <span class="count">(%s)</span>',
'All <span class="count">(%s)</span>',
$total_posts,
'posts'
),
number_format_i18n( $total_posts )
);
$status_links['all'] = array(
'url' => esc_url( add_query_arg( $all_args, 'edit.php' ) ),
'label' => $all_inner_html,
'current' => empty( $class ) && ( $this->is_base_request() || isset( $_REQUEST['all_posts'] ) ),
);
if ( $mine ) {
$status_links['mine'] = $mine;
}
foreach ( get_post_stati( array( 'show_in_admin_status_list' => true ), 'objects' ) as $status ) {
$class = '';
$status_name = $status->name;
if ( ! in_array( $status_name, $avail_post_stati, true ) || empty( $num_posts->$status_name ) ) {
continue;
}
if ( isset( $_REQUEST['post_status'] ) && $status_name === $_REQUEST['post_status'] ) {
$class = 'current';
}
$status_args = array(
'post_status' => $status_name,
'post_type' => $post_type,
);
$status_label = sprintf(
translate_nooped_plural( $status->label_count, $num_posts->$status_name ),
number_format_i18n( $num_posts->$status_name )
);
$status_links[ $status_name ] = array(
'url' => esc_url( add_query_arg( $status_args, 'edit.php' ) ),
'label' => $status_label,
'current' => isset( $_REQUEST['post_status'] ) && $status_name === $_REQUEST['post_status'],
);
}
if ( ! empty( $this->sticky_posts_count ) ) {
$class = ! empty( $_REQUEST['show_sticky'] ) ? 'current' : '';
$sticky_args = array(
'post_type' => $post_type,
'show_sticky' => 1,
);
$sticky_inner_html = sprintf(
/* translators: %s: Number of posts. */
_nx(
'Sticky <span class="count">(%s)</span>',
'Sticky <span class="count">(%s)</span>',
$this->sticky_posts_count,
'posts'
),
number_format_i18n( $this->sticky_posts_count )
);
$sticky_link = array(
'sticky' => array(
'url' => esc_url( add_query_arg( $sticky_args, 'edit.php' ) ),
'label' => $sticky_inner_html,
'current' => ! empty( $_REQUEST['show_sticky'] ),
),
);
// Sticky comes after Publish, or if not listed, after All.
$split = 1 + array_search( ( isset( $status_links['publish'] ) ? 'publish' : 'all' ), array_keys( $status_links ), true );
$status_links = array_merge( array_slice( $status_links, 0, $split ), $sticky_link, array_slice( $status_links, $split ) );
}
return $this->get_views_links( $status_links );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::is\_base\_request()](is_base_request) wp-admin/includes/class-wp-posts-list-table.php | Determine if the current view is the “All” view. |
| [translate\_nooped\_plural()](../../functions/translate_nooped_plural) wp-includes/l10n.php | Translates and returns the singular or plural form of a string that’s been registered with [\_n\_noop()](../../functions/_n_noop) or [\_nx\_noop()](../../functions/_nx_noop) . |
| [\_nx()](../../functions/_nx) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number, with gettext context. |
| [wp\_count\_posts()](../../functions/wp_count_posts) wp-includes/post.php | Counts number of posts of a post type and if user has permissions to view. |
| [get\_post\_stati()](../../functions/get_post_stati) wp-includes/post.php | Gets a list of post statuses. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| programming_docs |
wordpress WP_Posts_List_Table::get_sortable_columns(): array WP\_Posts\_List\_Table::get\_sortable\_columns(): array
=======================================================
array
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
protected function get_sortable_columns() {
return array(
'title' => 'title',
'parent' => 'parent',
'comments' => 'comment_count',
'date' => array( 'date', true ),
);
}
```
wordpress WP_Posts_List_Table::categories_dropdown( string $post_type ) WP\_Posts\_List\_Table::categories\_dropdown( string $post\_type )
==================================================================
Displays a categories drop-down for filtering on the Posts list table.
`$post_type` string Required Post type slug. File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
protected function categories_dropdown( $post_type ) {
global $cat;
/**
* Filters whether to remove the 'Categories' drop-down from the post list table.
*
* @since 4.6.0
*
* @param bool $disable Whether to disable the categories drop-down. Default false.
* @param string $post_type Post type slug.
*/
if ( false !== apply_filters( 'disable_categories_dropdown', false, $post_type ) ) {
return;
}
if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
$dropdown_options = array(
'show_option_all' => get_taxonomy( 'category' )->labels->all_items,
'hide_empty' => 0,
'hierarchical' => 1,
'show_count' => 0,
'orderby' => 'name',
'selected' => $cat,
);
echo '<label class="screen-reader-text" for="cat">' . get_taxonomy( 'category' )->labels->filter_by_item . '</label>';
wp_dropdown_categories( $dropdown_options );
}
}
```
[apply\_filters( 'disable\_categories\_dropdown', bool $disable, string $post\_type )](../../hooks/disable_categories_dropdown)
Filters whether to remove the ‘Categories’ drop-down from the post list table.
| Uses | Description |
| --- | --- |
| [wp\_dropdown\_categories()](../../functions/wp_dropdown_categories) wp-includes/category-template.php | Displays or retrieves the HTML dropdown list of categories. |
| [is\_object\_in\_taxonomy()](../../functions/is_object_in_taxonomy) wp-includes/taxonomy.php | Determines if the given object type is associated with the given taxonomy. |
| [get\_taxonomy()](../../functions/get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::extra\_tablenav()](extra_tablenav) wp-admin/includes/class-wp-posts-list-table.php | |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Posts_List_Table::has_items(): bool WP\_Posts\_List\_Table::has\_items(): bool
==========================================
bool
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function has_items() {
return have_posts();
}
```
| Uses | Description |
| --- | --- |
| [have\_posts()](../../functions/have_posts) wp-includes/query.php | Determines whether current WordPress query has posts to loop over. |
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::extra\_tablenav()](extra_tablenav) wp-admin/includes/class-wp-posts-list-table.php | |
wordpress WP_Posts_List_Table::set_hierarchical_display( bool $display ) WP\_Posts\_List\_Table::set\_hierarchical\_display( bool $display )
===================================================================
Sets whether the table layout should be hierarchical or not.
`$display` bool Required Whether the table layout should be hierarchical. File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function set_hierarchical_display( $display ) {
$this->hierarchical_display = $display;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::prepare\_items()](prepare_items) wp-admin/includes/class-wp-posts-list-table.php | |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Posts_List_Table::get_table_classes(): array WP\_Posts\_List\_Table::get\_table\_classes(): array
====================================================
array
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
protected function get_table_classes() {
global $mode;
$mode_class = esc_attr( 'table-view-' . $mode );
return array(
'widefat',
'fixed',
'striped',
$mode_class,
is_post_type_hierarchical( $this->screen->post_type ) ? 'pages' : 'posts',
);
}
```
| Uses | Description |
| --- | --- |
| [is\_post\_type\_hierarchical()](../../functions/is_post_type_hierarchical) wp-includes/post.php | Determines whether the post type is hierarchical. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
wordpress WP_Posts_List_Table::column_cb( WP_Post $item ) WP\_Posts\_List\_Table::column\_cb( WP\_Post $item )
====================================================
Handles the checkbox column output.
`$item` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$post = $item;
$show = current_user_can( 'edit_post', $post->ID );
/**
* Filters whether to show the bulk edit checkbox for a post in its list table.
*
* By default the checkbox is only shown if the current user can edit the post.
*
* @since 5.7.0
*
* @param bool $show Whether to show the checkbox.
* @param WP_Post $post The current WP_Post object.
*/
if ( apply_filters( 'wp_list_table_show_post_checkbox', $show, $post ) ) :
?>
<label class="screen-reader-text" for="cb-select-<?php the_ID(); ?>">
<?php
/* translators: %s: Post title. */
printf( __( 'Select %s' ), _draft_or_post_title() );
?>
</label>
<input id="cb-select-<?php the_ID(); ?>" type="checkbox" name="post[]" value="<?php the_ID(); ?>" />
<div class="locked-indicator">
<span class="locked-indicator-icon" aria-hidden="true"></span>
<span class="screen-reader-text">
<?php
printf(
/* translators: %s: Post title. */
__( '“%s” is locked' ),
_draft_or_post_title()
);
?>
</span>
</div>
<?php
endif;
}
```
[apply\_filters( 'wp\_list\_table\_show\_post\_checkbox', bool $show, WP\_Post $post )](../../hooks/wp_list_table_show_post_checkbox)
Filters whether to show the bulk edit checkbox for a post in its list table.
| Uses | Description |
| --- | --- |
| [\_draft\_or\_post\_title()](../../functions/_draft_or_post_title) wp-admin/includes/template.php | Gets the post title. |
| [the\_ID()](../../functions/the_id) wp-includes/post-template.php | Displays the ID of the current item in the WordPress Loop. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Posts_List_Table::get_columns(): array WP\_Posts\_List\_Table::get\_columns(): array
=============================================
array
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function get_columns() {
$post_type = $this->screen->post_type;
$posts_columns = array();
$posts_columns['cb'] = '<input type="checkbox" />';
/* translators: Posts screen column name. */
$posts_columns['title'] = _x( 'Title', 'column name' );
if ( post_type_supports( $post_type, 'author' ) ) {
$posts_columns['author'] = __( 'Author' );
}
$taxonomies = get_object_taxonomies( $post_type, 'objects' );
$taxonomies = wp_filter_object_list( $taxonomies, array( 'show_admin_column' => true ), 'and', 'name' );
/**
* Filters the taxonomy columns in the Posts list table.
*
* The dynamic portion of the hook name, `$post_type`, refers to the post
* type slug.
*
* Possible hook names include:
*
* - `manage_taxonomies_for_post_columns`
* - `manage_taxonomies_for_page_columns`
*
* @since 3.5.0
*
* @param string[] $taxonomies Array of taxonomy names to show columns for.
* @param string $post_type The post type.
*/
$taxonomies = apply_filters( "manage_taxonomies_for_{$post_type}_columns", $taxonomies, $post_type );
$taxonomies = array_filter( $taxonomies, 'taxonomy_exists' );
foreach ( $taxonomies as $taxonomy ) {
if ( 'category' === $taxonomy ) {
$column_key = 'categories';
} elseif ( 'post_tag' === $taxonomy ) {
$column_key = 'tags';
} else {
$column_key = 'taxonomy-' . $taxonomy;
}
$posts_columns[ $column_key ] = get_taxonomy( $taxonomy )->labels->name;
}
$post_status = ! empty( $_REQUEST['post_status'] ) ? $_REQUEST['post_status'] : 'all';
if ( post_type_supports( $post_type, 'comments' )
&& ! in_array( $post_status, array( 'pending', 'draft', 'future' ), true )
) {
$posts_columns['comments'] = sprintf(
'<span class="vers comment-grey-bubble" title="%1$s" aria-hidden="true"></span><span class="screen-reader-text">%2$s</span>',
esc_attr__( 'Comments' ),
__( 'Comments' )
);
}
$posts_columns['date'] = __( 'Date' );
if ( 'page' === $post_type ) {
/**
* Filters the columns displayed in the Pages list table.
*
* @since 2.5.0
*
* @param string[] $post_columns An associative array of column headings.
*/
$posts_columns = apply_filters( 'manage_pages_columns', $posts_columns );
} else {
/**
* Filters the columns displayed in the Posts list table.
*
* @since 1.5.0
*
* @param string[] $post_columns An associative array of column headings.
* @param string $post_type The post type slug.
*/
$posts_columns = apply_filters( 'manage_posts_columns', $posts_columns, $post_type );
}
/**
* Filters the columns displayed in the Posts list table for a specific post type.
*
* The dynamic portion of the hook name, `$post_type`, refers to the post type slug.
*
* Possible hook names include:
*
* - `manage_post_posts_columns`
* - `manage_page_posts_columns`
*
* @since 3.0.0
*
* @param string[] $post_columns An associative array of column headings.
*/
return apply_filters( "manage_{$post_type}_posts_columns", $posts_columns );
}
```
[apply\_filters( 'manage\_pages\_columns', string[] $post\_columns )](../../hooks/manage_pages_columns)
Filters the columns displayed in the Pages list table.
[apply\_filters( 'manage\_posts\_columns', string[] $post\_columns, string $post\_type )](../../hooks/manage_posts_columns)
Filters the columns displayed in the Posts list table.
[apply\_filters( "manage\_taxonomies\_for\_{$post\_type}\_columns", string[] $taxonomies, string $post\_type )](../../hooks/manage_taxonomies_for_post_type_columns)
Filters the taxonomy columns in the Posts list table.
[apply\_filters( "manage\_{$post\_type}\_posts\_columns", string[] $post\_columns )](../../hooks/manage_post_type_posts_columns)
Filters the columns displayed in the Posts list table for a specific post type.
| Uses | Description |
| --- | --- |
| [esc\_attr\_\_()](../../functions/esc_attr__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in an attribute. |
| [wp\_filter\_object\_list()](../../functions/wp_filter_object_list) wp-includes/functions.php | Filters a list of objects, based on a set of key => value arguments. |
| [get\_object\_taxonomies()](../../functions/get_object_taxonomies) wp-includes/taxonomy.php | Returns the names or objects of the taxonomies which are registered for the requested object or object type, such as a post object or post type name. |
| [post\_type\_supports()](../../functions/post_type_supports) wp-includes/post.php | Checks a post type’s support for a given feature. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_taxonomy()](../../functions/get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
wordpress WP_Posts_List_Table::get_bulk_actions(): array WP\_Posts\_List\_Table::get\_bulk\_actions(): array
===================================================
array
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
protected function get_bulk_actions() {
$actions = array();
$post_type_obj = get_post_type_object( $this->screen->post_type );
if ( current_user_can( $post_type_obj->cap->edit_posts ) ) {
if ( $this->is_trash ) {
$actions['untrash'] = __( 'Restore' );
} else {
$actions['edit'] = __( 'Edit' );
}
}
if ( current_user_can( $post_type_obj->cap->delete_posts ) ) {
if ( $this->is_trash || ! EMPTY_TRASH_DAYS ) {
$actions['delete'] = __( 'Delete permanently' );
} else {
$actions['trash'] = __( 'Move to Trash' );
}
}
return $actions;
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
wordpress WP_Posts_List_Table::column_date( WP_Post $post ) WP\_Posts\_List\_Table::column\_date( WP\_Post $post )
======================================================
Handles the post date column output.
`$post` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function column_date( $post ) {
global $mode;
if ( '0000-00-00 00:00:00' === $post->post_date ) {
$t_time = __( 'Unpublished' );
$time_diff = 0;
} else {
$t_time = sprintf(
/* translators: 1: Post date, 2: Post time. */
__( '%1$s at %2$s' ),
/* translators: Post date format. See https://www.php.net/manual/datetime.format.php */
get_the_time( __( 'Y/m/d' ), $post ),
/* translators: Post time format. See https://www.php.net/manual/datetime.format.php */
get_the_time( __( 'g:i a' ), $post )
);
$time = get_post_timestamp( $post );
$time_diff = time() - $time;
}
if ( 'publish' === $post->post_status ) {
$status = __( 'Published' );
} elseif ( 'future' === $post->post_status ) {
if ( $time_diff > 0 ) {
$status = '<strong class="error-message">' . __( 'Missed schedule' ) . '</strong>';
} else {
$status = __( 'Scheduled' );
}
} else {
$status = __( 'Last Modified' );
}
/**
* Filters the status text of the post.
*
* @since 4.8.0
*
* @param string $status The status text.
* @param WP_Post $post Post object.
* @param string $column_name The column name.
* @param string $mode The list display mode ('excerpt' or 'list').
*/
$status = apply_filters( 'post_date_column_status', $status, $post, 'date', $mode );
if ( $status ) {
echo $status . '<br />';
}
/**
* Filters the published time of the post.
*
* @since 2.5.1
* @since 5.5.0 Removed the difference between 'excerpt' and 'list' modes.
* The published time and date are both displayed now,
* which is equivalent to the previous 'excerpt' mode.
*
* @param string $t_time The published time.
* @param WP_Post $post Post object.
* @param string $column_name The column name.
* @param string $mode The list display mode ('excerpt' or 'list').
*/
echo apply_filters( 'post_date_column_time', $t_time, $post, 'date', $mode );
}
```
[apply\_filters( 'post\_date\_column\_status', string $status, WP\_Post $post, string $column\_name, string $mode )](../../hooks/post_date_column_status)
Filters the status text of the post.
[apply\_filters( 'post\_date\_column\_time', string $t\_time, WP\_Post $post, string $column\_name, string $mode )](../../hooks/post_date_column_time)
Filters the published time of the post.
| Uses | Description |
| --- | --- |
| [get\_post\_timestamp()](../../functions/get_post_timestamp) wp-includes/general-template.php | Retrieves post published or modified time as a Unix timestamp. |
| [get\_the\_time()](../../functions/get_the_time) wp-includes/general-template.php | Retrieves the time at which the post was written. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Posts_List_Table::_display_rows_hierarchical( array $pages, int $pagenum = 1, int $per_page = 20 ) WP\_Posts\_List\_Table::\_display\_rows\_hierarchical( array $pages, int $pagenum = 1, int $per\_page = 20 )
============================================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
`$pages` array Required `$pagenum` int Optional Default: `1`
`$per_page` int Optional Default: `20`
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
private function _display_rows_hierarchical( $pages, $pagenum = 1, $per_page = 20 ) {
global $wpdb;
$level = 0;
if ( ! $pages ) {
$pages = get_pages( array( 'sort_column' => 'menu_order' ) );
if ( ! $pages ) {
return;
}
}
/*
* Arrange pages into two parts: top level pages and children_pages.
* children_pages is two dimensional array. Example:
* children_pages[10][] contains all sub-pages whose parent is 10.
* It only takes O( N ) to arrange this and it takes O( 1 ) for subsequent lookup operations
* If searching, ignore hierarchy and treat everything as top level
*/
if ( empty( $_REQUEST['s'] ) ) {
$top_level_pages = array();
$children_pages = array();
foreach ( $pages as $page ) {
// Catch and repair bad pages.
if ( $page->post_parent === $page->ID ) {
$page->post_parent = 0;
$wpdb->update( $wpdb->posts, array( 'post_parent' => 0 ), array( 'ID' => $page->ID ) );
clean_post_cache( $page );
}
if ( $page->post_parent > 0 ) {
$children_pages[ $page->post_parent ][] = $page;
} else {
$top_level_pages[] = $page;
}
}
$pages = &$top_level_pages;
}
$count = 0;
$start = ( $pagenum - 1 ) * $per_page;
$end = $start + $per_page;
$to_display = array();
foreach ( $pages as $page ) {
if ( $count >= $end ) {
break;
}
if ( $count >= $start ) {
$to_display[ $page->ID ] = $level;
}
$count++;
if ( isset( $children_pages ) ) {
$this->_page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page, $to_display );
}
}
// If it is the last pagenum and there are orphaned pages, display them with paging as well.
if ( isset( $children_pages ) && $count < $end ) {
foreach ( $children_pages as $orphans ) {
foreach ( $orphans as $op ) {
if ( $count >= $end ) {
break;
}
if ( $count >= $start ) {
$to_display[ $op->ID ] = 0;
}
$count++;
}
}
}
$ids = array_keys( $to_display );
_prime_post_caches( $ids );
$_posts = array_map( 'get_post', $ids );
update_post_author_caches( $_posts );
if ( ! isset( $GLOBALS['post'] ) ) {
$GLOBALS['post'] = reset( $ids );
}
foreach ( $to_display as $page_id => $level ) {
echo "\t";
$this->single_row( $page_id, $level );
}
}
```
| Uses | Description |
| --- | --- |
| [update\_post\_author\_caches()](../../functions/update_post_author_caches) wp-includes/post.php | Updates post author user caches for a list of post objects. |
| [WP\_Posts\_List\_Table::single\_row()](single_row) wp-admin/includes/class-wp-posts-list-table.php | |
| [WP\_Posts\_List\_Table::\_page\_rows()](_page_rows) wp-admin/includes/class-wp-posts-list-table.php | Given a top level page ID, display the nested hierarchy of sub-pages together with paging support |
| [clean\_post\_cache()](../../functions/clean_post_cache) wp-includes/post.php | Will clean the post in the cache. |
| [\_prime\_post\_caches()](../../functions/_prime_post_caches) wp-includes/post.php | Adds any posts from the given IDs to the cache that do not already exist in cache. |
| [get\_pages()](../../functions/get_pages) wp-includes/post.php | Retrieves an array of pages (or hierarchical post type items). |
| [wpdb::update()](../wpdb/update) wp-includes/class-wpdb.php | Updates a row in the table. |
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::display\_rows()](display_rows) wp-admin/includes/class-wp-posts-list-table.php | |
| programming_docs |
wordpress WP_Posts_List_Table::__construct( array $args = array() ) WP\_Posts\_List\_Table::\_\_construct( array $args = array() )
==============================================================
Constructor.
* [WP\_List\_Table::\_\_construct()](../wp_list_table/__construct): for more information on default arguments.
`$args` array Optional An associative array of arguments. Default: `array()`
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function __construct( $args = array() ) {
global $post_type_object, $wpdb;
parent::__construct(
array(
'plural' => 'posts',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
$post_type = $this->screen->post_type;
$post_type_object = get_post_type_object( $post_type );
$exclude_states = get_post_stati(
array(
'show_in_admin_all_list' => false,
)
);
$this->user_posts_count = (int) $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT( 1 )
FROM $wpdb->posts
WHERE post_type = %s
AND post_status NOT IN ( '" . implode( "','", $exclude_states ) . "' )
AND post_author = %d",
$post_type,
get_current_user_id()
)
);
if ( $this->user_posts_count
&& ! current_user_can( $post_type_object->cap->edit_others_posts )
&& empty( $_REQUEST['post_status'] ) && empty( $_REQUEST['all_posts'] )
&& empty( $_REQUEST['author'] ) && empty( $_REQUEST['show_sticky'] )
) {
$_GET['author'] = get_current_user_id();
}
$sticky_posts = get_option( 'sticky_posts' );
if ( 'post' === $post_type && $sticky_posts ) {
$sticky_posts = implode( ', ', array_map( 'absint', (array) $sticky_posts ) );
$this->sticky_posts_count = (int) $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT( 1 )
FROM $wpdb->posts
WHERE post_type = %s
AND post_status NOT IN ('trash', 'auto-draft')
AND ID IN ($sticky_posts)",
$post_type
)
);
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::\_\_construct()](../wp_list_table/__construct) wp-admin/includes/class-wp-list-table.php | Constructor. |
| [get\_post\_stati()](../../functions/get_post_stati) wp-includes/post.php | Gets a list of post statuses. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [wpdb::get\_var()](../wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Posts_List_Table::formats_dropdown( string $post_type ) WP\_Posts\_List\_Table::formats\_dropdown( string $post\_type )
===============================================================
Displays a formats drop-down for filtering items.
`$post_type` string Required Post type slug. File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
protected function formats_dropdown( $post_type ) {
/**
* Filters whether to remove the 'Formats' drop-down from the post list table.
*
* @since 5.2.0
* @since 5.5.0 The `$post_type` parameter was added.
*
* @param bool $disable Whether to disable the drop-down. Default false.
* @param string $post_type Post type slug.
*/
if ( apply_filters( 'disable_formats_dropdown', false, $post_type ) ) {
return;
}
// Return if the post type doesn't have post formats or if we're in the Trash.
if ( ! is_object_in_taxonomy( $post_type, 'post_format' ) || $this->is_trash ) {
return;
}
// Make sure the dropdown shows only formats with a post count greater than 0.
$used_post_formats = get_terms(
array(
'taxonomy' => 'post_format',
'hide_empty' => true,
)
);
// Return if there are no posts using formats.
if ( ! $used_post_formats ) {
return;
}
$displayed_post_format = isset( $_GET['post_format'] ) ? $_GET['post_format'] : '';
?>
<label for="filter-by-format" class="screen-reader-text"><?php _e( 'Filter by post format' ); ?></label>
<select name="post_format" id="filter-by-format">
<option<?php selected( $displayed_post_format, '' ); ?> value=""><?php _e( 'All formats' ); ?></option>
<?php
foreach ( $used_post_formats as $used_post_format ) {
// Post format slug.
$slug = str_replace( 'post-format-', '', $used_post_format->slug );
// Pretty, translated version of the post format slug.
$pretty_name = get_post_format_string( $slug );
// Skip the standard post format.
if ( 'standard' === $slug ) {
continue;
}
?>
<option<?php selected( $displayed_post_format, $slug ); ?> value="<?php echo esc_attr( $slug ); ?>"><?php echo esc_html( $pretty_name ); ?></option>
<?php
}
?>
</select>
<?php
}
```
[apply\_filters( 'disable\_formats\_dropdown', bool $disable, string $post\_type )](../../hooks/disable_formats_dropdown)
Filters whether to remove the ‘Formats’ drop-down from the post list table.
| Uses | Description |
| --- | --- |
| [selected()](../../functions/selected) wp-includes/general-template.php | Outputs the HTML selected attribute. |
| [is\_object\_in\_taxonomy()](../../functions/is_object_in_taxonomy) wp-includes/taxonomy.php | Determines if the given object type is associated with the given taxonomy. |
| [get\_terms()](../../functions/get_terms) wp-includes/taxonomy.php | Retrieves the terms in a given taxonomy or list of taxonomies. |
| [get\_post\_format\_string()](../../functions/get_post_format_string) wp-includes/post-formats.php | Returns a pretty, translated version of a post format slug |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Posts\_List\_Table::extra\_tablenav()](extra_tablenav) wp-admin/includes/class-wp-posts-list-table.php | |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Posts_List_Table::column_comments( WP_Post $post ) WP\_Posts\_List\_Table::column\_comments( WP\_Post $post )
==========================================================
Handles the comments column output.
`$post` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function column_comments( $post ) {
?>
<div class="post-com-count-wrapper">
<?php
$pending_comments = isset( $this->comment_pending_count[ $post->ID ] ) ? $this->comment_pending_count[ $post->ID ] : 0;
$this->comments_bubble( $post->ID, $pending_comments );
?>
</div>
<?php
}
```
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Posts_List_Table::column_default( WP_Post $item, string $column_name ) WP\_Posts\_List\_Table::column\_default( WP\_Post $item, string $column\_name )
===============================================================================
Handles the default column output.
`$item` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. `$column_name` string Required The current column name. File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function column_default( $item, $column_name ) {
// Restores the more descriptive, specific name for use within this method.
$post = $item;
if ( 'categories' === $column_name ) {
$taxonomy = 'category';
} elseif ( 'tags' === $column_name ) {
$taxonomy = 'post_tag';
} elseif ( 0 === strpos( $column_name, 'taxonomy-' ) ) {
$taxonomy = substr( $column_name, 9 );
} else {
$taxonomy = false;
}
if ( $taxonomy ) {
$taxonomy_object = get_taxonomy( $taxonomy );
$terms = get_the_terms( $post->ID, $taxonomy );
if ( is_array( $terms ) ) {
$term_links = array();
foreach ( $terms as $t ) {
$posts_in_term_qv = array();
if ( 'post' !== $post->post_type ) {
$posts_in_term_qv['post_type'] = $post->post_type;
}
if ( $taxonomy_object->query_var ) {
$posts_in_term_qv[ $taxonomy_object->query_var ] = $t->slug;
} else {
$posts_in_term_qv['taxonomy'] = $taxonomy;
$posts_in_term_qv['term'] = $t->slug;
}
$label = esc_html( sanitize_term_field( 'name', $t->name, $t->term_id, $taxonomy, 'display' ) );
$term_links[] = $this->get_edit_link( $posts_in_term_qv, $label );
}
/**
* Filters the links in `$taxonomy` column of edit.php.
*
* @since 5.2.0
*
* @param string[] $term_links Array of term editing links.
* @param string $taxonomy Taxonomy name.
* @param WP_Term[] $terms Array of term objects appearing in the post row.
*/
$term_links = apply_filters( 'post_column_taxonomy_links', $term_links, $taxonomy, $terms );
echo implode( wp_get_list_item_separator(), $term_links );
} else {
echo '<span aria-hidden="true">—</span><span class="screen-reader-text">' . $taxonomy_object->labels->no_terms . '</span>';
}
return;
}
if ( is_post_type_hierarchical( $post->post_type ) ) {
/**
* Fires in each custom column on the Posts list table.
*
* This hook only fires if the current post type is hierarchical,
* such as pages.
*
* @since 2.5.0
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
do_action( 'manage_pages_custom_column', $column_name, $post->ID );
} else {
/**
* Fires in each custom column in the Posts list table.
*
* This hook only fires if the current post type is non-hierarchical,
* such as posts.
*
* @since 1.5.0
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
do_action( 'manage_posts_custom_column', $column_name, $post->ID );
}
/**
* Fires for each custom column of a specific post type in the Posts list table.
*
* The dynamic portion of the hook name, `$post->post_type`, refers to the post type.
*
* Possible hook names include:
*
* - `manage_post_posts_custom_column`
* - `manage_page_posts_custom_column`
*
* @since 3.1.0
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
do_action( "manage_{$post->post_type}_posts_custom_column", $column_name, $post->ID );
}
```
[do\_action( 'manage\_pages\_custom\_column', string $column\_name, int $post\_id )](../../hooks/manage_pages_custom_column)
Fires in each custom column on the Posts list table.
[do\_action( 'manage\_posts\_custom\_column', string $column\_name, int $post\_id )](../../hooks/manage_posts_custom_column)
Fires in each custom column in the Posts list table.
[do\_action( "manage\_{$post->post\_type}\_posts\_custom\_column", string $column\_name, int $post\_id )](../../hooks/manage_post-post_type_posts_custom_column)
Fires for each custom column of a specific post type in the Posts list table.
[apply\_filters( 'post\_column\_taxonomy\_links', string[] $term\_links, string $taxonomy, WP\_Term[] $terms )](../../hooks/post_column_taxonomy_links)
Filters the links in `$taxonomy` column of edit.php.
| Uses | Description |
| --- | --- |
| [wp\_get\_list\_item\_separator()](../../functions/wp_get_list_item_separator) wp-includes/l10n.php | Retrieves the list item separator based on the locale. |
| [WP\_Posts\_List\_Table::get\_edit\_link()](get_edit_link) wp-admin/includes/class-wp-posts-list-table.php | Helper to create links to edit.php with params. |
| [get\_the\_terms()](../../functions/get_the_terms) wp-includes/category-template.php | Retrieves the terms of the taxonomy that are attached to the post. |
| [sanitize\_term\_field()](../../functions/sanitize_term_field) wp-includes/taxonomy.php | Sanitizes the field value in the term based on the context. |
| [is\_post\_type\_hierarchical()](../../functions/is_post_type_hierarchical) wp-includes/post.php | Determines whether the post type is hierarchical. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [get\_taxonomy()](../../functions/get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Posts_List_Table::inline_edit() WP\_Posts\_List\_Table::inline\_edit()
======================================
Outputs the hidden row displayed when inline editing
File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/)
```
public function inline_edit() {
global $mode;
$screen = $this->screen;
$post = get_default_post_to_edit( $screen->post_type );
$post_type_object = get_post_type_object( $screen->post_type );
$taxonomy_names = get_object_taxonomies( $screen->post_type );
$hierarchical_taxonomies = array();
$flat_taxonomies = array();
foreach ( $taxonomy_names as $taxonomy_name ) {
$taxonomy = get_taxonomy( $taxonomy_name );
$show_in_quick_edit = $taxonomy->show_in_quick_edit;
/**
* Filters whether the current taxonomy should be shown in the Quick Edit panel.
*
* @since 4.2.0
*
* @param bool $show_in_quick_edit Whether to show the current taxonomy in Quick Edit.
* @param string $taxonomy_name Taxonomy name.
* @param string $post_type Post type of current Quick Edit post.
*/
if ( ! apply_filters( 'quick_edit_show_taxonomy', $show_in_quick_edit, $taxonomy_name, $screen->post_type ) ) {
continue;
}
if ( $taxonomy->hierarchical ) {
$hierarchical_taxonomies[] = $taxonomy;
} else {
$flat_taxonomies[] = $taxonomy;
}
}
$m = ( isset( $mode ) && 'excerpt' === $mode ) ? 'excerpt' : 'list';
$can_publish = current_user_can( $post_type_object->cap->publish_posts );
$core_columns = array(
'cb' => true,
'date' => true,
'title' => true,
'categories' => true,
'tags' => true,
'comments' => true,
'author' => true,
);
?>
<form method="get">
<table style="display: none"><tbody id="inlineedit">
<?php
$hclass = count( $hierarchical_taxonomies ) ? 'post' : 'page';
$inline_edit_classes = "inline-edit-row inline-edit-row-$hclass";
$bulk_edit_classes = "bulk-edit-row bulk-edit-row-$hclass bulk-edit-{$screen->post_type}";
$quick_edit_classes = "quick-edit-row quick-edit-row-$hclass inline-edit-{$screen->post_type}";
$bulk = 0;
while ( $bulk < 2 ) :
$classes = $inline_edit_classes . ' ';
$classes .= $bulk ? $bulk_edit_classes : $quick_edit_classes;
?>
<tr id="<?php echo $bulk ? 'bulk-edit' : 'inline-edit'; ?>" class="<?php echo $classes; ?>" style="display: none">
<td colspan="<?php echo $this->get_column_count(); ?>" class="colspanchange">
<div class="inline-edit-wrapper" role="region" aria-labelledby="<?php echo $bulk ? 'bulk' : 'quick'; ?>-edit-legend">
<fieldset class="inline-edit-col-left">
<legend class="inline-edit-legend" id="<?php echo $bulk ? 'bulk' : 'quick'; ?>-edit-legend"><?php echo $bulk ? __( 'Bulk Edit' ) : __( 'Quick Edit' ); ?></legend>
<div class="inline-edit-col">
<?php if ( post_type_supports( $screen->post_type, 'title' ) ) : ?>
<?php if ( $bulk ) : ?>
<div id="bulk-title-div">
<div id="bulk-titles"></div>
</div>
<?php else : // $bulk ?>
<label>
<span class="title"><?php _e( 'Title' ); ?></span>
<span class="input-text-wrap"><input type="text" name="post_title" class="ptitle" value="" /></span>
</label>
<?php if ( is_post_type_viewable( $screen->post_type ) ) : ?>
<label>
<span class="title"><?php _e( 'Slug' ); ?></span>
<span class="input-text-wrap"><input type="text" name="post_name" value="" autocomplete="off" spellcheck="false" /></span>
</label>
<?php endif; // is_post_type_viewable() ?>
<?php endif; // $bulk ?>
<?php endif; // post_type_supports( ... 'title' ) ?>
<?php if ( ! $bulk ) : ?>
<fieldset class="inline-edit-date">
<legend><span class="title"><?php _e( 'Date' ); ?></span></legend>
<?php touch_time( 1, 1, 0, 1 ); ?>
</fieldset>
<br class="clear" />
<?php endif; // $bulk ?>
<?php
if ( post_type_supports( $screen->post_type, 'author' ) ) {
$authors_dropdown = '';
if ( current_user_can( $post_type_object->cap->edit_others_posts ) ) {
$dropdown_name = 'post_author';
$dropdown_class = 'authors';
if ( wp_is_large_user_count() ) {
$authors_dropdown = sprintf( '<select name="%s" class="%s hidden"></select>', esc_attr( $dropdown_name ), esc_attr( $dropdown_class ) );
} else {
$users_opt = array(
'hide_if_only_one_author' => false,
'capability' => array( $post_type_object->cap->edit_posts ),
'name' => $dropdown_name,
'class' => $dropdown_class,
'multi' => 1,
'echo' => 0,
'show' => 'display_name_with_login',
);
if ( $bulk ) {
$users_opt['show_option_none'] = __( '— No Change —' );
}
/**
* Filters the arguments used to generate the Quick Edit authors drop-down.
*
* @since 5.6.0
*
* @see wp_dropdown_users()
*
* @param array $users_opt An array of arguments passed to wp_dropdown_users().
* @param bool $bulk A flag to denote if it's a bulk action.
*/
$users_opt = apply_filters( 'quick_edit_dropdown_authors_args', $users_opt, $bulk );
$authors = wp_dropdown_users( $users_opt );
if ( $authors ) {
$authors_dropdown = '<label class="inline-edit-author">';
$authors_dropdown .= '<span class="title">' . __( 'Author' ) . '</span>';
$authors_dropdown .= $authors;
$authors_dropdown .= '</label>';
}
}
} // current_user_can( 'edit_others_posts' )
if ( ! $bulk ) {
echo $authors_dropdown;
}
} // post_type_supports( ... 'author' )
?>
<?php if ( ! $bulk && $can_publish ) : ?>
<div class="inline-edit-group wp-clearfix">
<label class="alignleft">
<span class="title"><?php _e( 'Password' ); ?></span>
<span class="input-text-wrap"><input type="text" name="post_password" class="inline-edit-password-input" value="" /></span>
</label>
<span class="alignleft inline-edit-or">
<?php
/* translators: Between password field and private checkbox on post quick edit interface. */
_e( '–OR–' );
?>
</span>
<label class="alignleft inline-edit-private">
<input type="checkbox" name="keep_private" value="private" />
<span class="checkbox-title"><?php _e( 'Private' ); ?></span>
</label>
</div>
<?php endif; ?>
</div>
</fieldset>
<?php if ( count( $hierarchical_taxonomies ) && ! $bulk ) : ?>
<fieldset class="inline-edit-col-center inline-edit-categories">
<div class="inline-edit-col">
<?php foreach ( $hierarchical_taxonomies as $taxonomy ) : ?>
<span class="title inline-edit-categories-label"><?php echo esc_html( $taxonomy->labels->name ); ?></span>
<input type="hidden" name="<?php echo ( 'category' === $taxonomy->name ) ? 'post_category[]' : 'tax_input[' . esc_attr( $taxonomy->name ) . '][]'; ?>" value="0" />
<ul class="cat-checklist <?php echo esc_attr( $taxonomy->name ); ?>-checklist">
<?php wp_terms_checklist( 0, array( 'taxonomy' => $taxonomy->name ) ); ?>
</ul>
<?php endforeach; // $hierarchical_taxonomies as $taxonomy ?>
</div>
</fieldset>
<?php endif; // count( $hierarchical_taxonomies ) && ! $bulk ?>
<fieldset class="inline-edit-col-right">
<div class="inline-edit-col">
<?php
if ( post_type_supports( $screen->post_type, 'author' ) && $bulk ) {
echo $authors_dropdown;
}
?>
<?php if ( post_type_supports( $screen->post_type, 'page-attributes' ) ) : ?>
<?php if ( $post_type_object->hierarchical ) : ?>
<label>
<span class="title"><?php _e( 'Parent' ); ?></span>
<?php
$dropdown_args = array(
'post_type' => $post_type_object->name,
'selected' => $post->post_parent,
'name' => 'post_parent',
'show_option_none' => __( 'Main Page (no parent)' ),
'option_none_value' => 0,
'sort_column' => 'menu_order, post_title',
);
if ( $bulk ) {
$dropdown_args['show_option_no_change'] = __( '— No Change —' );
}
/**
* Filters the arguments used to generate the Quick Edit page-parent drop-down.
*
* @since 2.7.0
* @since 5.6.0 The `$bulk` parameter was added.
*
* @see wp_dropdown_pages()
*
* @param array $dropdown_args An array of arguments passed to wp_dropdown_pages().
* @param bool $bulk A flag to denote if it's a bulk action.
*/
$dropdown_args = apply_filters( 'quick_edit_dropdown_pages_args', $dropdown_args, $bulk );
wp_dropdown_pages( $dropdown_args );
?>
</label>
<?php endif; // hierarchical ?>
<?php if ( ! $bulk ) : ?>
<label>
<span class="title"><?php _e( 'Order' ); ?></span>
<span class="input-text-wrap"><input type="text" name="menu_order" class="inline-edit-menu-order-input" value="<?php echo $post->menu_order; ?>" /></span>
</label>
<?php endif; // ! $bulk ?>
<?php endif; // post_type_supports( ... 'page-attributes' ) ?>
<?php if ( 0 < count( get_page_templates( null, $screen->post_type ) ) ) : ?>
<label>
<span class="title"><?php _e( 'Template' ); ?></span>
<select name="page_template">
<?php if ( $bulk ) : ?>
<option value="-1"><?php _e( '— No Change —' ); ?></option>
<?php endif; // $bulk ?>
<?php
/** This filter is documented in wp-admin/includes/meta-boxes.php */
$default_title = apply_filters( 'default_page_template_title', __( 'Default template' ), 'quick-edit' );
?>
<option value="default"><?php echo esc_html( $default_title ); ?></option>
<?php page_template_dropdown( '', $screen->post_type ); ?>
</select>
</label>
<?php endif; ?>
<?php if ( count( $flat_taxonomies ) && ! $bulk ) : ?>
<?php foreach ( $flat_taxonomies as $taxonomy ) : ?>
<?php if ( current_user_can( $taxonomy->cap->assign_terms ) ) : ?>
<?php $taxonomy_name = esc_attr( $taxonomy->name ); ?>
<div class="inline-edit-tags-wrap">
<label class="inline-edit-tags">
<span class="title"><?php echo esc_html( $taxonomy->labels->name ); ?></span>
<textarea data-wp-taxonomy="<?php echo $taxonomy_name; ?>" cols="22" rows="1" name="tax_input[<?php echo esc_attr( $taxonomy->name ); ?>]" class="tax_input_<?php echo esc_attr( $taxonomy->name ); ?>" aria-describedby="inline-edit-<?php echo esc_attr( $taxonomy->name ); ?>-desc"></textarea>
</label>
<p class="howto" id="inline-edit-<?php echo esc_attr( $taxonomy->name ); ?>-desc"><?php echo esc_html( $taxonomy->labels->separate_items_with_commas ); ?></p>
</div>
<?php endif; // current_user_can( 'assign_terms' ) ?>
<?php endforeach; // $flat_taxonomies as $taxonomy ?>
<?php endif; // count( $flat_taxonomies ) && ! $bulk ?>
<?php if ( post_type_supports( $screen->post_type, 'comments' ) || post_type_supports( $screen->post_type, 'trackbacks' ) ) : ?>
<?php if ( $bulk ) : ?>
<div class="inline-edit-group wp-clearfix">
<?php if ( post_type_supports( $screen->post_type, 'comments' ) ) : ?>
<label class="alignleft">
<span class="title"><?php _e( 'Comments' ); ?></span>
<select name="comment_status">
<option value=""><?php _e( '— No Change —' ); ?></option>
<option value="open"><?php _e( 'Allow' ); ?></option>
<option value="closed"><?php _e( 'Do not allow' ); ?></option>
</select>
</label>
<?php endif; ?>
<?php if ( post_type_supports( $screen->post_type, 'trackbacks' ) ) : ?>
<label class="alignright">
<span class="title"><?php _e( 'Pings' ); ?></span>
<select name="ping_status">
<option value=""><?php _e( '— No Change —' ); ?></option>
<option value="open"><?php _e( 'Allow' ); ?></option>
<option value="closed"><?php _e( 'Do not allow' ); ?></option>
</select>
</label>
<?php endif; ?>
</div>
<?php else : // $bulk ?>
<div class="inline-edit-group wp-clearfix">
<?php if ( post_type_supports( $screen->post_type, 'comments' ) ) : ?>
<label class="alignleft">
<input type="checkbox" name="comment_status" value="open" />
<span class="checkbox-title"><?php _e( 'Allow Comments' ); ?></span>
</label>
<?php endif; ?>
<?php if ( post_type_supports( $screen->post_type, 'trackbacks' ) ) : ?>
<label class="alignleft">
<input type="checkbox" name="ping_status" value="open" />
<span class="checkbox-title"><?php _e( 'Allow Pings' ); ?></span>
</label>
<?php endif; ?>
</div>
<?php endif; // $bulk ?>
<?php endif; // post_type_supports( ... comments or pings ) ?>
<div class="inline-edit-group wp-clearfix">
<label class="inline-edit-status alignleft">
<span class="title"><?php _e( 'Status' ); ?></span>
<select name="_status">
<?php if ( $bulk ) : ?>
<option value="-1"><?php _e( '— No Change —' ); ?></option>
<?php endif; // $bulk ?>
<?php if ( $can_publish ) : // Contributors only get "Unpublished" and "Pending Review". ?>
<option value="publish"><?php _e( 'Published' ); ?></option>
<option value="future"><?php _e( 'Scheduled' ); ?></option>
<?php if ( $bulk ) : ?>
<option value="private"><?php _e( 'Private' ); ?></option>
<?php endif; // $bulk ?>
<?php endif; ?>
<option value="pending"><?php _e( 'Pending Review' ); ?></option>
<option value="draft"><?php _e( 'Draft' ); ?></option>
</select>
</label>
<?php if ( 'post' === $screen->post_type && $can_publish && current_user_can( $post_type_object->cap->edit_others_posts ) ) : ?>
<?php if ( $bulk ) : ?>
<label class="alignright">
<span class="title"><?php _e( 'Sticky' ); ?></span>
<select name="sticky">
<option value="-1"><?php _e( '— No Change —' ); ?></option>
<option value="sticky"><?php _e( 'Sticky' ); ?></option>
<option value="unsticky"><?php _e( 'Not Sticky' ); ?></option>
</select>
</label>
<?php else : // $bulk ?>
<label class="alignleft">
<input type="checkbox" name="sticky" value="sticky" />
<span class="checkbox-title"><?php _e( 'Make this post sticky' ); ?></span>
</label>
<?php endif; // $bulk ?>
<?php endif; // 'post' && $can_publish && current_user_can( 'edit_others_posts' ) ?>
</div>
<?php if ( $bulk && current_theme_supports( 'post-formats' ) && post_type_supports( $screen->post_type, 'post-formats' ) ) : ?>
<?php $post_formats = get_theme_support( 'post-formats' ); ?>
<label class="alignleft">
<span class="title"><?php _ex( 'Format', 'post format' ); ?></span>
<select name="post_format">
<option value="-1"><?php _e( '— No Change —' ); ?></option>
<option value="0"><?php echo get_post_format_string( 'standard' ); ?></option>
<?php if ( is_array( $post_formats[0] ) ) : ?>
<?php foreach ( $post_formats[0] as $format ) : ?>
<option value="<?php echo esc_attr( $format ); ?>"><?php echo esc_html( get_post_format_string( $format ) ); ?></option>
<?php endforeach; ?>
<?php endif; ?>
</select>
</label>
<?php endif; ?>
</div>
</fieldset>
<?php
list( $columns ) = $this->get_column_info();
foreach ( $columns as $column_name => $column_display_name ) {
if ( isset( $core_columns[ $column_name ] ) ) {
continue;
}
if ( $bulk ) {
/**
* Fires once for each column in Bulk Edit mode.
*
* @since 2.7.0
*
* @param string $column_name Name of the column to edit.
* @param string $post_type The post type slug.
*/
do_action( 'bulk_edit_custom_box', $column_name, $screen->post_type );
} else {
/**
* Fires once for each column in Quick Edit mode.
*
* @since 2.7.0
*
* @param string $column_name Name of the column to edit.
* @param string $post_type The post type slug, or current screen name if this is a taxonomy list table.
* @param string $taxonomy The taxonomy name, if any.
*/
do_action( 'quick_edit_custom_box', $column_name, $screen->post_type, '' );
}
}
?>
<div class="submit inline-edit-save">
<?php if ( ! $bulk ) : ?>
<?php wp_nonce_field( 'inlineeditnonce', '_inline_edit', false ); ?>
<button type="button" class="button button-primary save"><?php _e( 'Update' ); ?></button>
<?php else : ?>
<?php submit_button( __( 'Update' ), 'primary', 'bulk_edit', false ); ?>
<?php endif; ?>
<button type="button" class="button cancel"><?php _e( 'Cancel' ); ?></button>
<?php if ( ! $bulk ) : ?>
<span class="spinner"></span>
<?php endif; ?>
<input type="hidden" name="post_view" value="<?php echo esc_attr( $m ); ?>" />
<input type="hidden" name="screen" value="<?php echo esc_attr( $screen->id ); ?>" />
<?php if ( ! $bulk && ! post_type_supports( $screen->post_type, 'author' ) ) : ?>
<input type="hidden" name="post_author" value="<?php echo esc_attr( $post->post_author ); ?>" />
<?php endif; ?>
<div class="notice notice-error notice-alt inline hidden">
<p class="error"></p>
</div>
</div>
</div> <!-- end of .inline-edit-wrapper -->
</td></tr>
<?php
$bulk++;
endwhile;
?>
</tbody></table>
</form>
<?php
}
```
[do\_action( 'bulk\_edit\_custom\_box', string $column\_name, string $post\_type )](../../hooks/bulk_edit_custom_box)
Fires once for each column in Bulk Edit mode.
[apply\_filters( 'default\_page\_template\_title', string $label, string $context )](../../hooks/default_page_template_title)
Filters the title of the default page template displayed in the drop-down.
[do\_action( 'quick\_edit\_custom\_box', string $column\_name, string $post\_type, string $taxonomy )](../../hooks/quick_edit_custom_box)
Fires once for each column in Quick Edit mode.
[apply\_filters( 'quick\_edit\_dropdown\_authors\_args', array $users\_opt, bool $bulk )](../../hooks/quick_edit_dropdown_authors_args)
Filters the arguments used to generate the Quick Edit authors drop-down.
[apply\_filters( 'quick\_edit\_dropdown\_pages\_args', array $dropdown\_args, bool $bulk )](../../hooks/quick_edit_dropdown_pages_args)
Filters the arguments used to generate the Quick Edit page-parent drop-down.
[apply\_filters( 'quick\_edit\_show\_taxonomy', bool $show\_in\_quick\_edit, string $taxonomy\_name, string $post\_type )](../../hooks/quick_edit_show_taxonomy)
Filters whether the current taxonomy should be shown in the Quick Edit panel.
| Uses | Description |
| --- | --- |
| [wp\_is\_large\_user\_count()](../../functions/wp_is_large_user_count) wp-includes/user.php | Determines whether the site has a large number of users. |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [post\_type\_supports()](../../functions/post_type_supports) wp-includes/post.php | Checks a post type’s support for a given feature. |
| [wp\_dropdown\_pages()](../../functions/wp_dropdown_pages) wp-includes/post-template.php | Retrieves or displays a list of pages as a dropdown (select list). |
| [wp\_dropdown\_users()](../../functions/wp_dropdown_users) wp-includes/user.php | Creates dropdown HTML content of users. |
| [get\_object\_taxonomies()](../../functions/get_object_taxonomies) wp-includes/taxonomy.php | Returns the names or objects of the taxonomies which are registered for the requested object or object type, such as a post object or post type name. |
| [wp\_nonce\_field()](../../functions/wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [is\_post\_type\_viewable()](../../functions/is_post_type_viewable) wp-includes/post.php | Determines whether a post type is considered “viewable”. |
| [\_ex()](../../functions/_ex) wp-includes/l10n.php | Displays translated string with gettext context. |
| [get\_post\_format\_string()](../../functions/get_post_format_string) wp-includes/post-formats.php | Returns a pretty, translated version of a post format slug |
| [wp\_terms\_checklist()](../../functions/wp_terms_checklist) wp-admin/includes/template.php | Outputs an unordered list of checkbox input elements labelled with term names. |
| [get\_page\_templates()](../../functions/get_page_templates) wp-admin/includes/theme.php | Gets the page templates available in this theme. |
| [submit\_button()](../../functions/submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [touch\_time()](../../functions/touch_time) wp-admin/includes/template.php | Prints out HTML form date elements for editing post or comment publish date. |
| [page\_template\_dropdown()](../../functions/page_template_dropdown) wp-admin/includes/template.php | Prints out option HTML elements for the page templates drop-down. |
| [get\_default\_post\_to\_edit()](../../functions/get_default_post_to_edit) wp-admin/includes/post.php | Returns default post information to use when populating the “Write Post” form. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_taxonomy()](../../functions/get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
| programming_docs |
wordpress Requests_Exception_Transport_cURL::getReason() Requests\_Exception\_Transport\_cURL::getReason()
=================================================
Get the error message
File: `wp-includes/Requests/Exception/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/transport/curl.php/)
```
public function getReason() {
return $this->reason;
}
```
wordpress Requests_Exception_Transport_cURL::__construct( $message, $type, $data = null, $code ) Requests\_Exception\_Transport\_cURL::\_\_construct( $message, $type, $data = null, $code )
===========================================================================================
File: `wp-includes/Requests/Exception/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/transport/curl.php/)
```
public function __construct($message, $type, $data = null, $code = 0) {
if ($type !== null) {
$this->type = $type;
}
if ($code !== null) {
$this->code = $code;
}
if ($message !== null) {
$this->reason = $message;
}
$message = sprintf('%d %s', $this->code, $this->reason);
parent::__construct($message, $this->type, $data, $this->code);
}
```
| Used By | Description |
| --- | --- |
| [Requests\_Transport\_cURL::request\_multiple()](../requests_transport_curl/request_multiple) wp-includes/Requests/Transport/cURL.php | Send multiple requests simultaneously |
wordpress WP_Customize_Date_Time_Control::content_template() WP\_Customize\_Date\_Time\_Control::content\_template()
=======================================================
Renders a JS template for the content of date time control.
File: `wp-includes/customize/class-wp-customize-date-time-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-date-time-control.php/)
```
public function content_template() {
$data = array_merge( $this->json(), $this->get_month_choices() );
$timezone_info = $this->get_timezone_info();
$date_format = get_option( 'date_format' );
$date_format = preg_replace( '/(?<!\\\\)[Yyo]/', '%1$s', $date_format );
$date_format = preg_replace( '/(?<!\\\\)[FmMn]/', '%2$s', $date_format );
$date_format = preg_replace( '/(?<!\\\\)[jd]/', '%3$s', $date_format );
// Fallback to ISO date format if year, month, or day are missing from the date format.
if ( 1 !== substr_count( $date_format, '%1$s' ) || 1 !== substr_count( $date_format, '%2$s' ) || 1 !== substr_count( $date_format, '%3$s' ) ) {
$date_format = '%1$s-%2$s-%3$s';
}
?>
<# _.defaults( data, <?php echo wp_json_encode( $data ); ?> ); #>
<# var idPrefix = _.uniqueId( 'el' ) + '-'; #>
<# if ( data.label ) { #>
<span class="customize-control-title">
{{ data.label }}
</span>
<# } #>
<div class="customize-control-notifications-container"></div>
<# if ( data.description ) { #>
<span class="description customize-control-description">{{ data.description }}</span>
<# } #>
<div class="date-time-fields {{ data.includeTime ? 'includes-time' : '' }}">
<fieldset class="day-row">
<legend class="title-day {{ ! data.includeTime ? 'screen-reader-text' : '' }}"><?php esc_html_e( 'Date' ); ?></legend>
<div class="day-fields clear">
<?php ob_start(); ?>
<label for="{{ idPrefix }}date-time-month" class="screen-reader-text"><?php esc_html_e( 'Month' ); ?></label>
<select id="{{ idPrefix }}date-time-month" class="date-input month" data-component="month">
<# _.each( data.month_choices, function( choice ) {
if ( _.isObject( choice ) && ! _.isUndefined( choice.text ) && ! _.isUndefined( choice.value ) ) {
text = choice.text;
value = choice.value;
}
#>
<option value="{{ value }}" >
{{ text }}
</option>
<# } ); #>
</select>
<?php $month_field = trim( ob_get_clean() ); ?>
<?php ob_start(); ?>
<label for="{{ idPrefix }}date-time-day" class="screen-reader-text"><?php esc_html_e( 'Day' ); ?></label>
<input id="{{ idPrefix }}date-time-day" type="number" size="2" autocomplete="off" class="date-input day" data-component="day" min="1" max="31" />
<?php $day_field = trim( ob_get_clean() ); ?>
<?php ob_start(); ?>
<label for="{{ idPrefix }}date-time-year" class="screen-reader-text"><?php esc_html_e( 'Year' ); ?></label>
<input id="{{ idPrefix }}date-time-year" type="number" size="4" autocomplete="off" class="date-input year" data-component="year" min="{{ data.minYear }}" max="{{ data.maxYear }}">
<?php $year_field = trim( ob_get_clean() ); ?>
<?php printf( $date_format, $year_field, $month_field, $day_field ); ?>
</div>
</fieldset>
<# if ( data.includeTime ) { #>
<fieldset class="time-row clear">
<legend class="title-time"><?php esc_html_e( 'Time' ); ?></legend>
<div class="time-fields clear">
<label for="{{ idPrefix }}date-time-hour" class="screen-reader-text"><?php esc_html_e( 'Hour' ); ?></label>
<# var maxHour = data.twelveHourFormat ? 12 : 23; #>
<# var minHour = data.twelveHourFormat ? 1 : 0; #>
<input id="{{ idPrefix }}date-time-hour" type="number" size="2" autocomplete="off" class="date-input hour" data-component="hour" min="{{ minHour }}" max="{{ maxHour }}">
:
<label for="{{ idPrefix }}date-time-minute" class="screen-reader-text"><?php esc_html_e( 'Minute' ); ?></label>
<input id="{{ idPrefix }}date-time-minute" type="number" size="2" autocomplete="off" class="date-input minute" data-component="minute" min="0" max="59">
<# if ( data.twelveHourFormat ) { #>
<label for="{{ idPrefix }}date-time-meridian" class="screen-reader-text"><?php esc_html_e( 'Meridian' ); ?></label>
<select id="{{ idPrefix }}date-time-meridian" class="date-input meridian" data-component="meridian">
<option value="am"><?php esc_html_e( 'AM' ); ?></option>
<option value="pm"><?php esc_html_e( 'PM' ); ?></option>
</select>
<# } #>
<p><?php echo $timezone_info['description']; ?></p>
</div>
</fieldset>
<# } #>
</div>
<?php
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Date\_Time\_Control::json()](json) wp-includes/customize/class-wp-customize-date-time-control.php | Export data to JS. |
| [WP\_Customize\_Date\_Time\_Control::get\_month\_choices()](get_month_choices) wp-includes/customize/class-wp-customize-date-time-control.php | Generate options for the month Select. |
| [WP\_Customize\_Date\_Time\_Control::get\_timezone\_info()](get_timezone_info) wp-includes/customize/class-wp-customize-date-time-control.php | Get timezone info. |
| [esc\_html\_e()](../../functions/esc_html_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in HTML output. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Date_Time_Control::json(): array WP\_Customize\_Date\_Time\_Control::json(): array
=================================================
Export data to JS.
array
File: `wp-includes/customize/class-wp-customize-date-time-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-date-time-control.php/)
```
public function json() {
$data = parent::json();
$data['maxYear'] = (int) $this->max_year;
$data['minYear'] = (int) $this->min_year;
$data['allowPastDate'] = (bool) $this->allow_past_date;
$data['twelveHourFormat'] = (bool) $this->twelve_hour_format;
$data['includeTime'] = (bool) $this->include_time;
return $data;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::json()](../wp_customize_control/json) wp-includes/class-wp-customize-control.php | Get the data to export to the client via JSON. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Date\_Time\_Control::content\_template()](content_template) wp-includes/customize/class-wp-customize-date-time-control.php | Renders a JS template for the content of date time control. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Date_Time_Control::get_timezone_info(): array WP\_Customize\_Date\_Time\_Control::get\_timezone\_info(): array
================================================================
Get timezone info.
array Timezone info. All properties are optional.
* `abbr`stringTimezone abbreviation. Examples: PST or CEST.
* `description`stringHuman-readable timezone description as HTML.
File: `wp-includes/customize/class-wp-customize-date-time-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-date-time-control.php/)
```
public function get_timezone_info() {
$tz_string = get_option( 'timezone_string' );
$timezone_info = array();
if ( $tz_string ) {
try {
$tz = new DateTimeZone( $tz_string );
} catch ( Exception $e ) {
$tz = '';
}
if ( $tz ) {
$now = new DateTime( 'now', $tz );
$formatted_gmt_offset = $this->format_gmt_offset( $tz->getOffset( $now ) / 3600 );
$tz_name = str_replace( '_', ' ', $tz->getName() );
$timezone_info['abbr'] = $now->format( 'T' );
$timezone_info['description'] = sprintf(
/* translators: 1: Timezone name, 2: Timezone abbreviation, 3: UTC abbreviation and offset, 4: UTC offset. */
__( 'Your timezone is set to %1$s (%2$s), currently %3$s (Coordinated Universal Time %4$s).' ),
$tz_name,
'<abbr>' . $timezone_info['abbr'] . '</abbr>',
'<abbr>UTC</abbr>' . $formatted_gmt_offset,
$formatted_gmt_offset
);
} else {
$timezone_info['description'] = '';
}
} else {
$formatted_gmt_offset = $this->format_gmt_offset( (int) get_option( 'gmt_offset', 0 ) );
$timezone_info['description'] = sprintf(
/* translators: 1: UTC abbreviation and offset, 2: UTC offset. */
__( 'Your timezone is set to %1$s (Coordinated Universal Time %2$s).' ),
'<abbr>UTC</abbr>' . $formatted_gmt_offset,
$formatted_gmt_offset
);
}
return $timezone_info;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Date\_Time\_Control::format\_gmt\_offset()](format_gmt_offset) wp-includes/customize/class-wp-customize-date-time-control.php | Format GMT Offset. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Date\_Time\_Control::content\_template()](content_template) wp-includes/customize/class-wp-customize-date-time-control.php | Renders a JS template for the content of date time control. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Date_Time_Control::format_gmt_offset( float $offset ): string WP\_Customize\_Date\_Time\_Control::format\_gmt\_offset( float $offset ): string
================================================================================
Format GMT Offset.
* [wp\_timezone\_choice()](../../functions/wp_timezone_choice)
`$offset` float Required Offset in hours. string Formatted offset.
File: `wp-includes/customize/class-wp-customize-date-time-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-date-time-control.php/)
```
public function format_gmt_offset( $offset ) {
if ( 0 <= $offset ) {
$formatted_offset = '+' . (string) $offset;
} else {
$formatted_offset = (string) $offset;
}
$formatted_offset = str_replace(
array( '.25', '.5', '.75' ),
array( ':15', ':30', ':45' ),
$formatted_offset
);
return $formatted_offset;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Date\_Time\_Control::get\_timezone\_info()](get_timezone_info) wp-includes/customize/class-wp-customize-date-time-control.php | Get timezone info. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Date_Time_Control::get_month_choices(): array WP\_Customize\_Date\_Time\_Control::get\_month\_choices(): array
================================================================
Generate options for the month Select.
Based on [touch\_time()](../../functions/touch_time) .
* [touch\_time()](../../functions/touch_time)
array
File: `wp-includes/customize/class-wp-customize-date-time-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-date-time-control.php/)
```
public function get_month_choices() {
global $wp_locale;
$months = array();
for ( $i = 1; $i < 13; $i++ ) {
$month_text = $wp_locale->get_month_abbrev( $wp_locale->get_month( $i ) );
/* translators: 1: Month number (01, 02, etc.), 2: Month abbreviation. */
$months[ $i ]['text'] = sprintf( __( '%1$s-%2$s' ), $i, $month_text );
$months[ $i ]['value'] = $i;
}
return array(
'month_choices' => $months,
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Locale::get\_month()](../wp_locale/get_month) wp-includes/class-wp-locale.php | Retrieves the full translated month by month number. |
| [WP\_Locale::get\_month\_abbrev()](../wp_locale/get_month_abbrev) wp-includes/class-wp-locale.php | Retrieves translated version of month abbreviation string. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Date\_Time\_Control::content\_template()](content_template) wp-includes/customize/class-wp-customize-date-time-control.php | Renders a JS template for the content of date time control. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Date_Time_Control::render_content() WP\_Customize\_Date\_Time\_Control::render\_content()
=====================================================
Don’t render the control’s content – it’s rendered with a JS template.
File: `wp-includes/customize/class-wp-customize-date-time-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-date-time-control.php/)
```
public function render_content() {}
```
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Partial::render_callback( WP_Customize_Partial $partial, array $context = array() ): string|array|false WP\_Customize\_Partial::render\_callback( WP\_Customize\_Partial $partial, array $context = array() ): string|array|false
=========================================================================================================================
Default callback used when invoking [WP\_Customize\_Control::render()](../wp_customize_control/render).
Note that this method may echo the partial *or* return the partial as a string or array, but not both. Output buffering is performed when this is called. Subclasses can override this with their specific logic, or they may provide an ‘render\_callback’ argument to the constructor.
This method may return an HTML string for straight DOM injection, or it may return an array for supporting Partial JS subclasses to render by applying to client-side templating.
`$partial` [WP\_Customize\_Partial](../wp_customize_partial) Required Partial. `$context` array Optional Context. Default: `array()`
string|array|false
File: `wp-includes/customize/class-wp-customize-partial.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-partial.php/)
```
public function render_callback( WP_Customize_Partial $partial, $context = array() ) {
unset( $partial, $context );
return false;
}
```
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Partial::json(): array WP\_Customize\_Partial::json(): array
=====================================
Retrieves the data to export to the client via JSON.
array Array of parameters passed to the JavaScript.
File: `wp-includes/customize/class-wp-customize-partial.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-partial.php/)
```
public function json() {
$exports = array(
'settings' => $this->settings,
'primarySetting' => $this->primary_setting,
'selector' => $this->selector,
'type' => $this->type,
'fallbackRefresh' => $this->fallback_refresh,
'containerInclusive' => $this->container_inclusive,
);
return $exports;
}
```
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Partial::__construct( WP_Customize_Selective_Refresh $component, string $id, array $args = array() ) WP\_Customize\_Partial::\_\_construct( WP\_Customize\_Selective\_Refresh $component, string $id, array $args = array() )
========================================================================================================================
Constructor.
Supplied `$args` override class property defaults.
If `$args['settings']` is not defined, use the $id as the setting ID.
`$component` [WP\_Customize\_Selective\_Refresh](../wp_customize_selective_refresh) Required Customize Partial Refresh plugin instance. `$id` string Required Control ID. `$args` array Optional Array of properties for the new Partials object.
* `type`stringType of the partial to be created.
* `selector`stringThe jQuery selector to find the container element for the partial, that is, a partial's placement.
* `settings`string[]IDs for settings tied to the partial. If undefined, `$id` will be used.
* `primary_setting`stringThe ID for the setting that this partial is primarily responsible for rendering. If not supplied, it will default to the ID of the first setting.
* `capability`stringCapability required to edit this partial.
Normally this is empty and the capability is derived from the capabilities of the associated `$settings`.
* `render_callback`callableRender callback.
Callback is called with one argument, the instance of [WP\_Customize\_Partial](../wp_customize_partial).
The callback can either echo the partial or return the partial as a string, or return false if error.
* `container_inclusive`boolWhether the container element is included in the partial, or if only the contents are rendered.
* `fallback_refresh`boolWhether to refresh the entire preview in case a partial cannot be refreshed.
A partial render is considered a failure if the render\_callback returns false.
Default: `array()`
File: `wp-includes/customize/class-wp-customize-partial.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-partial.php/)
```
public function __construct( WP_Customize_Selective_Refresh $component, $id, $args = array() ) {
$keys = array_keys( get_object_vars( $this ) );
foreach ( $keys as $key ) {
if ( isset( $args[ $key ] ) ) {
$this->$key = $args[ $key ];
}
}
$this->component = $component;
$this->id = $id;
$this->id_data['keys'] = preg_split( '/\[/', str_replace( ']', '', $this->id ) );
$this->id_data['base'] = array_shift( $this->id_data['keys'] );
if ( empty( $this->render_callback ) ) {
$this->render_callback = array( $this, 'render_callback' );
}
// Process settings.
if ( ! isset( $this->settings ) ) {
$this->settings = array( $id );
} elseif ( is_string( $this->settings ) ) {
$this->settings = array( $this->settings );
}
if ( empty( $this->primary_setting ) ) {
$this->primary_setting = current( $this->settings );
}
}
```
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Partial::render( array $container_context = array() ): string|array|false WP\_Customize\_Partial::render( array $container\_context = array() ): string|array|false
=========================================================================================
Renders the template partial involving the associated settings.
`$container_context` array Optional Array of context data associated with the target container (placement).
Default: `array()`
string|array|false The rendered partial as a string, raw data array (for client-side JS template), or false if no render applied.
File: `wp-includes/customize/class-wp-customize-partial.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-partial.php/)
```
final public function render( $container_context = array() ) {
$partial = $this;
$rendered = false;
if ( ! empty( $this->render_callback ) ) {
ob_start();
$return_render = call_user_func( $this->render_callback, $this, $container_context );
$ob_render = ob_get_clean();
if ( null !== $return_render && '' !== $ob_render ) {
_doing_it_wrong( __FUNCTION__, __( 'Partial render must echo the content or return the content string (or array), but not both.' ), '4.5.0' );
}
/*
* Note that the string return takes precedence because the $ob_render may just\
* include PHP warnings or notices.
*/
$rendered = null !== $return_render ? $return_render : $ob_render;
}
/**
* Filters partial rendering.
*
* @since 4.5.0
*
* @param string|array|false $rendered The partial value. Default false.
* @param WP_Customize_Partial $partial WP_Customize_Setting instance.
* @param array $container_context Optional array of context data associated with
* the target container.
*/
$rendered = apply_filters( 'customize_partial_render', $rendered, $partial, $container_context );
/**
* Filters partial rendering for a specific partial.
*
* The dynamic portion of the hook name, `$partial->ID` refers to the partial ID.
*
* @since 4.5.0
*
* @param string|array|false $rendered The partial value. Default false.
* @param WP_Customize_Partial $partial WP_Customize_Setting instance.
* @param array $container_context Optional array of context data associated with
* the target container.
*/
$rendered = apply_filters( "customize_partial_render_{$partial->id}", $rendered, $partial, $container_context );
return $rendered;
}
```
[apply\_filters( 'customize\_partial\_render', string|array|false $rendered, WP\_Customize\_Partial $partial, array $container\_context )](../../hooks/customize_partial_render)
Filters partial rendering.
[apply\_filters( "customize\_partial\_render\_{$partial->id}", string|array|false $rendered, WP\_Customize\_Partial $partial, array $container\_context )](../../hooks/customize_partial_render_partial-id)
Filters partial rendering for a specific partial.
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](../../functions/_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Partial::id_data(): array WP\_Customize\_Partial::id\_data(): array
=========================================
Retrieves parsed ID data for multidimensional setting.
array ID data for multidimensional partial.
* `base`stringID base.
* `keys`arrayKeys for multidimensional array.
File: `wp-includes/customize/class-wp-customize-partial.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-partial.php/)
```
final public function id_data() {
return $this->id_data;
}
```
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Partial::check_capabilities(): bool WP\_Customize\_Partial::check\_capabilities(): bool
===================================================
Checks if the user can refresh this partial.
Returns false if the user cannot manipulate one of the associated settings, or if one of the associated settings does not exist.
bool False if user can't edit one of the related settings, or if one of the associated settings does not exist.
File: `wp-includes/customize/class-wp-customize-partial.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-partial.php/)
```
final public function check_capabilities() {
if ( ! empty( $this->capability ) && ! current_user_can( $this->capability ) ) {
return false;
}
foreach ( $this->settings as $setting_id ) {
$setting = $this->component->manager->get_setting( $setting_id );
if ( ! $setting || ! $setting->check_capabilities() ) {
return false;
}
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::get_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Plugins\_Controller::get\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
====================================================================================================
Retrieves one plugin from the site.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function get_item( $request ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
$data = $this->get_plugin_data( $request['plugin'] );
if ( is_wp_error( $data ) ) {
return $data;
}
return $this->prepare_item_for_response( $data, $request );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::get\_plugin\_data()](get_plugin_data) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Gets the plugin header data for a plugin. |
| [WP\_REST\_Plugins\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Prepares the plugin for the REST response. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::validate_plugin_param( string $file ): bool WP\_REST\_Plugins\_Controller::validate\_plugin\_param( string $file ): bool
============================================================================
Checks that the “plugin” parameter is a valid path.
`$file` string Required The plugin file parameter. bool
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function validate_plugin_param( $file ) {
if ( ! is_string( $file ) || ! preg_match( '/' . self::PATTERN . '/u', $file ) ) {
return false;
}
$validated = validate_file( plugin_basename( $file ) );
return 0 === $validated;
}
```
| Uses | Description |
| --- | --- |
| [validate\_file()](../../functions/validate_file) wp-includes/functions.php | Validates a file name and path against an allowed set of rules. |
| [plugin\_basename()](../../functions/plugin_basename) wp-includes/plugin.php | Gets the basename of a plugin. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::prepare_item_for_response( array $item, WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Plugins\_Controller::prepare\_item\_for\_response( array $item, WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
====================================================================================================================================
Prepares the plugin for the REST response.
`$item` array Required Unmarked up and untranslated plugin data from [get\_plugin\_data()](../../functions/get_plugin_data) . `$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function prepare_item_for_response( $item, $request ) {
$fields = $this->get_fields_for_response( $request );
$item = _get_plugin_data_markup_translate( $item['_file'], $item, false );
$marked = _get_plugin_data_markup_translate( $item['_file'], $item, true );
$data = array(
'plugin' => substr( $item['_file'], 0, - 4 ),
'status' => $this->get_plugin_status( $item['_file'] ),
'name' => $item['Name'],
'plugin_uri' => $item['PluginURI'],
'author' => $item['Author'],
'author_uri' => $item['AuthorURI'],
'description' => array(
'raw' => $item['Description'],
'rendered' => $marked['Description'],
),
'version' => $item['Version'],
'network_only' => $item['Network'],
'requires_wp' => $item['RequiresWP'],
'requires_php' => $item['RequiresPHP'],
'textdomain' => $item['TextDomain'],
);
$data = $this->add_additional_fields_to_object( $data, $request );
$response = new WP_REST_Response( $data );
if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
$response->add_links( $this->prepare_links( $item ) );
}
/**
* Filters plugin data for a REST API response.
*
* @since 5.5.0
*
* @param WP_REST_Response $response The response object.
* @param array $item The plugin item from {@see get_plugin_data()}.
* @param WP_REST_Request $request The request object.
*/
return apply_filters( 'rest_prepare_plugin', $response, $item, $request );
}
```
[apply\_filters( 'rest\_prepare\_plugin', WP\_REST\_Response $response, array $item, WP\_REST\_Request $request )](../../hooks/rest_prepare_plugin)
Filters plugin data for a REST API response.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::get\_plugin\_status()](get_plugin_status) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Get’s the activation status for a plugin. |
| [WP\_REST\_Plugins\_Controller::prepare\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Prepares links for the request. |
| [rest\_is\_field\_included()](../../functions/rest_is_field_included) wp-includes/rest-api.php | Given an array of fields to include in a response, some of which may be `nested.fields`, determine whether the provided field should be included in the response body. |
| [\_get\_plugin\_data\_markup\_translate()](../../functions/_get_plugin_data_markup_translate) wp-admin/includes/plugin.php | Sanitizes plugin data, optionally adds markup, optionally translates. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Retrieves a collection of plugins. |
| [WP\_REST\_Plugins\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Retrieves one plugin from the site. |
| [WP\_REST\_Plugins\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Uploads a plugin and optionally activates it. |
| [WP\_REST\_Plugins\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Updates one plugin. |
| [WP\_REST\_Plugins\_Controller::delete\_item()](delete_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Deletes one plugin from the site. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::prepare_links( array $item ): array[] WP\_REST\_Plugins\_Controller::prepare\_links( array $item ): array[]
=====================================================================
Prepares links for the request.
`$item` array Required The plugin item. array[]
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
protected function prepare_links( $item ) {
return array(
'self' => array(
'href' => rest_url(
sprintf(
'%s/%s/%s',
$this->namespace,
$this->rest_base,
substr( $item['_file'], 0, - 4 )
)
),
),
);
}
```
| Uses | Description |
| --- | --- |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Prepares the plugin for the REST response. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::get_items( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Plugins\_Controller::get\_items( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=====================================================================================================
Retrieves a collection of plugins.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function get_items( $request ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
$plugins = array();
foreach ( get_plugins() as $file => $data ) {
if ( is_wp_error( $this->check_read_permission( $file ) ) ) {
continue;
}
$data['_file'] = $file;
if ( ! $this->does_plugin_match_request( $request, $data ) ) {
continue;
}
$plugins[] = $this->prepare_response_for_collection( $this->prepare_item_for_response( $data, $request ) );
}
return new WP_REST_Response( $plugins );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::does\_plugin\_match\_request()](does_plugin_match_request) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if the plugin matches the requested parameters. |
| [WP\_REST\_Plugins\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if the given plugin can be viewed by the current user. |
| [WP\_REST\_Plugins\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Prepares the plugin for the REST response. |
| [get\_plugins()](../../functions/get_plugins) wp-admin/includes/plugin.php | Checks the plugins directory and retrieve all plugin files with plugin data. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::get_plugin_data( string $plugin ): array|WP_Error WP\_REST\_Plugins\_Controller::get\_plugin\_data( string $plugin ): array|WP\_Error
===================================================================================
Gets the plugin header data for a plugin.
`$plugin` string Required The plugin file to get data for. array|[WP\_Error](../wp_error) The plugin data, or a [WP\_Error](../wp_error) if the plugin is not installed.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
protected function get_plugin_data( $plugin ) {
$plugins = get_plugins();
if ( ! isset( $plugins[ $plugin ] ) ) {
return new WP_Error( 'rest_plugin_not_found', __( 'Plugin not found.' ), array( 'status' => 404 ) );
}
$data = $plugins[ $plugin ];
$data['_file'] = $plugin;
return $data;
}
```
| Uses | Description |
| --- | --- |
| [get\_plugins()](../../functions/get_plugins) wp-admin/includes/plugin.php | Checks the plugins directory and retrieve all plugin files with plugin data. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Retrieves one plugin from the site. |
| [WP\_REST\_Plugins\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Updates one plugin. |
| [WP\_REST\_Plugins\_Controller::delete\_item()](delete_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Deletes one plugin from the site. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::create_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Plugins\_Controller::create\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=======================================================================================================
Uploads a plugin and optionally activates it.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function create_item( $request ) {
global $wp_filesystem;
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/plugin.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
$slug = $request['slug'];
// Verify filesystem is accessible first.
$filesystem_available = $this->is_filesystem_available();
if ( is_wp_error( $filesystem_available ) ) {
return $filesystem_available;
}
$api = plugins_api(
'plugin_information',
array(
'slug' => $slug,
'fields' => array(
'sections' => false,
'language_packs' => true,
),
)
);
if ( is_wp_error( $api ) ) {
if ( false !== strpos( $api->get_error_message(), 'Plugin not found.' ) ) {
$api->add_data( array( 'status' => 404 ) );
} else {
$api->add_data( array( 'status' => 500 ) );
}
return $api;
}
$skin = new WP_Ajax_Upgrader_Skin();
$upgrader = new Plugin_Upgrader( $skin );
$result = $upgrader->install( $api->download_link );
if ( is_wp_error( $result ) ) {
$result->add_data( array( 'status' => 500 ) );
return $result;
}
// This should be the same as $result above.
if ( is_wp_error( $skin->result ) ) {
$skin->result->add_data( array( 'status' => 500 ) );
return $skin->result;
}
if ( $skin->get_errors()->has_errors() ) {
$error = $skin->get_errors();
$error->add_data( array( 'status' => 500 ) );
return $error;
}
if ( is_null( $result ) ) {
// Pass through the error from WP_Filesystem if one was raised.
if ( $wp_filesystem instanceof WP_Filesystem_Base
&& is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors()
) {
return new WP_Error(
'unable_to_connect_to_filesystem',
$wp_filesystem->errors->get_error_message(),
array( 'status' => 500 )
);
}
return new WP_Error(
'unable_to_connect_to_filesystem',
__( 'Unable to connect to the filesystem. Please confirm your credentials.' ),
array( 'status' => 500 )
);
}
$file = $upgrader->plugin_info();
if ( ! $file ) {
return new WP_Error(
'unable_to_determine_installed_plugin',
__( 'Unable to determine what plugin was installed.' ),
array( 'status' => 500 )
);
}
if ( 'inactive' !== $request['status'] ) {
$can_change_status = $this->plugin_status_permission_check( $file, $request['status'], 'inactive' );
if ( is_wp_error( $can_change_status ) ) {
return $can_change_status;
}
$changed_status = $this->handle_plugin_status( $file, $request['status'], 'inactive' );
if ( is_wp_error( $changed_status ) ) {
return $changed_status;
}
}
// Install translations.
$installed_locales = array_values( get_available_languages() );
/** This filter is documented in wp-includes/update.php */
$installed_locales = apply_filters( 'plugins_update_check_locales', $installed_locales );
$language_packs = array_map(
static function( $item ) {
return (object) $item;
},
$api->language_packs
);
$language_packs = array_filter(
$language_packs,
static function( $pack ) use ( $installed_locales ) {
return in_array( $pack->language, $installed_locales, true );
}
);
if ( $language_packs ) {
$lp_upgrader = new Language_Pack_Upgrader( $skin );
// Install all applicable language packs for the plugin.
$lp_upgrader->bulk_upgrade( $language_packs );
}
$path = WP_PLUGIN_DIR . '/' . $file;
$data = get_plugin_data( $path, false, false );
$data['_file'] = $file;
$response = $this->prepare_item_for_response( $data, $request );
$response->set_status( 201 );
$response->header( 'Location', rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, substr( $file, 0, - 4 ) ) ) );
return $response;
}
```
[apply\_filters( 'plugins\_update\_check\_locales', string[] $locales )](../../hooks/plugins_update_check_locales)
Filters the locales requested for plugin translations.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::is\_filesystem\_available()](is_filesystem_available) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Determine if the endpoints are available. |
| [WP\_REST\_Plugins\_Controller::plugin\_status\_permission\_check()](plugin_status_permission_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Handle updating a plugin’s status. |
| [WP\_REST\_Plugins\_Controller::handle\_plugin\_status()](handle_plugin_status) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Handle updating a plugin’s status. |
| [WP\_REST\_Plugins\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Prepares the plugin for the REST response. |
| [WP\_Ajax\_Upgrader\_Skin::\_\_construct()](../wp_ajax_upgrader_skin/__construct) wp-admin/includes/class-wp-ajax-upgrader-skin.php | Constructor. |
| [plugins\_api()](../../functions/plugins_api) wp-admin/includes/plugin-install.php | Retrieves plugin installer pages from the WordPress.org Plugins API. |
| [get\_plugin\_data()](../../functions/get_plugin_data) wp-admin/includes/plugin.php | Parses the plugin contents to retrieve plugin’s metadata. |
| [get\_available\_languages()](../../functions/get_available_languages) wp-includes/l10n.php | Gets all available languages based on the presence of \*.mo files in a given directory. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Plugins_Controller::sanitize_plugin_param( string $file ): string WP\_REST\_Plugins\_Controller::sanitize\_plugin\_param( string $file ): string
==============================================================================
Sanitizes the “plugin” parameter to be a proper plugin file with “.php” appended.
`$file` string Required The plugin file parameter. string
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function sanitize_plugin_param( $file ) {
return plugin_basename( sanitize_text_field( $file . '.php' ) );
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [plugin\_basename()](../../functions/plugin_basename) wp-includes/plugin.php | Gets the basename of a plugin. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::update_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Plugins\_Controller::update\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=======================================================================================================
Updates one plugin.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function update_item( $request ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
$data = $this->get_plugin_data( $request['plugin'] );
if ( is_wp_error( $data ) ) {
return $data;
}
$status = $this->get_plugin_status( $request['plugin'] );
if ( $request['status'] && $status !== $request['status'] ) {
$handled = $this->handle_plugin_status( $request['plugin'], $request['status'], $status );
if ( is_wp_error( $handled ) ) {
return $handled;
}
}
$this->update_additional_fields_for_object( $data, $request );
$request['context'] = 'edit';
return $this->prepare_item_for_response( $data, $request );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::get\_plugin\_data()](get_plugin_data) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Gets the plugin header data for a plugin. |
| [WP\_REST\_Plugins\_Controller::get\_plugin\_status()](get_plugin_status) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Get’s the activation status for a plugin. |
| [WP\_REST\_Plugins\_Controller::handle\_plugin\_status()](handle_plugin_status) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Handle updating a plugin’s status. |
| [WP\_REST\_Plugins\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Prepares the plugin for the REST response. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::handle_plugin_status( string $plugin, string $new_status, string $current_status ): true|WP_Error WP\_REST\_Plugins\_Controller::handle\_plugin\_status( string $plugin, string $new\_status, string $current\_status ): true|WP\_Error
=====================================================================================================================================
Handle updating a plugin’s status.
`$plugin` string Required The plugin file to update. `$new_status` string Required The plugin's new status. `$current_status` string Required The plugin's current status. true|[WP\_Error](../wp_error)
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
protected function handle_plugin_status( $plugin, $new_status, $current_status ) {
if ( 'inactive' === $new_status ) {
deactivate_plugins( $plugin, false, 'network-active' === $current_status );
return true;
}
if ( 'active' === $new_status && 'network-active' === $current_status ) {
return true;
}
$network_activate = 'network-active' === $new_status;
if ( is_multisite() && ! $network_activate && is_network_only_plugin( $plugin ) ) {
return new WP_Error(
'rest_network_only_plugin',
__( 'Network only plugin must be network activated.' ),
array( 'status' => 400 )
);
}
$activated = activate_plugin( $plugin, '', $network_activate );
if ( is_wp_error( $activated ) ) {
$activated->add_data( array( 'status' => 500 ) );
return $activated;
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [deactivate\_plugins()](../../functions/deactivate_plugins) wp-admin/includes/plugin.php | Deactivates a single plugin or multiple plugins. |
| [is\_network\_only\_plugin()](../../functions/is_network_only_plugin) wp-admin/includes/plugin.php | Checks for “Network: true” in the plugin header to see if this should be activated only as a network wide plugin. The plugin would also work when Multisite is not enabled. |
| [activate\_plugin()](../../functions/activate_plugin) wp-admin/includes/plugin.php | Attempts activation of plugin in a “sandbox” and redirects on success. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Uploads a plugin and optionally activates it. |
| [WP\_REST\_Plugins\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Updates one plugin. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::delete_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Plugins\_Controller::delete\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=============================================================================================================
Checks if a given request has access to delete a specific plugin.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has access to delete the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function delete_item_permissions_check( $request ) {
if ( ! current_user_can( 'activate_plugins' ) ) {
return new WP_Error(
'rest_cannot_manage_plugins',
__( 'Sorry, you are not allowed to manage plugins for this site.' ),
array( 'status' => rest_authorization_required_code() )
);
}
if ( ! current_user_can( 'delete_plugins' ) ) {
return new WP_Error(
'rest_cannot_manage_plugins',
__( 'Sorry, you are not allowed to delete plugins for this site.' ),
array( 'status' => rest_authorization_required_code() )
);
}
$can_read = $this->check_read_permission( $request['plugin'] );
if ( is_wp_error( $can_read ) ) {
return $can_read;
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if the given plugin can be viewed by the current user. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::is_filesystem_available(): true|WP_Error WP\_REST\_Plugins\_Controller::is\_filesystem\_available(): true|WP\_Error
==========================================================================
Determine if the endpoints are available.
Only the ‘Direct’ filesystem transport, and SSH/FTP when credentials are stored are supported at present.
true|[WP\_Error](../wp_error) True if filesystem is available, [WP\_Error](../wp_error) otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
protected function is_filesystem_available() {
$filesystem_method = get_filesystem_method();
if ( 'direct' === $filesystem_method ) {
return true;
}
ob_start();
$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
ob_end_clean();
if ( $filesystem_credentials_are_stored ) {
return true;
}
return new WP_Error( 'fs_unavailable', __( 'The filesystem is currently unavailable for managing plugins.' ), array( 'status' => 500 ) );
}
```
| Uses | Description |
| --- | --- |
| [get\_filesystem\_method()](../../functions/get_filesystem_method) wp-admin/includes/file.php | Determines which method to use for reading, writing, modifying, or deleting files on the filesystem. |
| [request\_filesystem\_credentials()](../../functions/request_filesystem_credentials) wp-admin/includes/file.php | Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem. |
| [self\_admin\_url()](../../functions/self_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for either the current site or the network depending on context. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Uploads a plugin and optionally activates it. |
| [WP\_REST\_Plugins\_Controller::delete\_item()](delete_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Deletes one plugin from the site. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Plugins\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
===========================================================================================================
Checks if a given request has access to get plugins.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function get_items_permissions_check( $request ) {
if ( ! current_user_can( 'activate_plugins' ) ) {
return new WP_Error(
'rest_cannot_view_plugins',
__( 'Sorry, you are not allowed to manage plugins for this site.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::update_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Plugins\_Controller::update\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=============================================================================================================
Checks if a given request has access to update a specific plugin.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has access to update the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function update_item_permissions_check( $request ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
if ( ! current_user_can( 'activate_plugins' ) ) {
return new WP_Error(
'rest_cannot_manage_plugins',
__( 'Sorry, you are not allowed to manage plugins for this site.' ),
array( 'status' => rest_authorization_required_code() )
);
}
$can_read = $this->check_read_permission( $request['plugin'] );
if ( is_wp_error( $can_read ) ) {
return $can_read;
}
$status = $this->get_plugin_status( $request['plugin'] );
if ( $request['status'] && $status !== $request['status'] ) {
$can_change_status = $this->plugin_status_permission_check( $request['plugin'], $request['status'], $status );
if ( is_wp_error( $can_change_status ) ) {
return $can_change_status;
}
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::get\_plugin\_status()](get_plugin_status) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Get’s the activation status for a plugin. |
| [WP\_REST\_Plugins\_Controller::plugin\_status\_permission\_check()](plugin_status_permission_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Handle updating a plugin’s status. |
| [WP\_REST\_Plugins\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if the given plugin can be viewed by the current user. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::plugin_status_permission_check( string $plugin, string $new_status, string $current_status ): true|WP_Error WP\_REST\_Plugins\_Controller::plugin\_status\_permission\_check( string $plugin, string $new\_status, string $current\_status ): true|WP\_Error
================================================================================================================================================
Handle updating a plugin’s status.
`$plugin` string Required The plugin file to update. `$new_status` string Required The plugin's new status. `$current_status` string Required The plugin's current status. true|[WP\_Error](../wp_error)
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
protected function plugin_status_permission_check( $plugin, $new_status, $current_status ) {
if ( is_multisite() && ( 'network-active' === $current_status || 'network-active' === $new_status ) && ! current_user_can( 'manage_network_plugins' ) ) {
return new WP_Error(
'rest_cannot_manage_network_plugins',
__( 'Sorry, you are not allowed to manage network plugins.' ),
array( 'status' => rest_authorization_required_code() )
);
}
if ( ( 'active' === $new_status || 'network-active' === $new_status ) && ! current_user_can( 'activate_plugin', $plugin ) ) {
return new WP_Error(
'rest_cannot_activate_plugin',
__( 'Sorry, you are not allowed to activate this plugin.' ),
array( 'status' => rest_authorization_required_code() )
);
}
if ( 'inactive' === $new_status && ! current_user_can( 'deactivate_plugin', $plugin ) ) {
return new WP_Error(
'rest_cannot_deactivate_plugin',
__( 'Sorry, you are not allowed to deactivate this plugin.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Uploads a plugin and optionally activates it. |
| [WP\_REST\_Plugins\_Controller::update\_item\_permissions\_check()](update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if a given request has access to update a specific plugin. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Plugins_Controller::register_routes() WP\_REST\_Plugins\_Controller::register\_routes()
=================================================
Registers the routes for the plugins controller.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base,
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => $this->get_collection_params(),
),
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'create_item' ),
'permission_callback' => array( $this, 'create_item_permissions_check' ),
'args' => array(
'slug' => array(
'type' => 'string',
'required' => true,
'description' => __( 'WordPress.org plugin directory slug.' ),
'pattern' => '[\w\-]+',
),
'status' => array(
'description' => __( 'The plugin activation status.' ),
'type' => 'string',
'enum' => is_multisite() ? array( 'inactive', 'active', 'network-active' ) : array( 'inactive', 'active' ),
'default' => 'inactive',
),
),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/(?P<plugin>' . self::PATTERN . ')',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this, 'get_item_permissions_check' ),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'update_item' ),
'permission_callback' => array( $this, 'update_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => array( $this, 'delete_item' ),
'permission_callback' => array( $this, 'delete_item_permissions_check' ),
),
'args' => array(
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
'plugin' => array(
'type' => 'string',
'pattern' => self::PATTERN,
'validate_callback' => array( $this, 'validate_plugin_param' ),
'sanitize_callback' => array( $this, 'sanitize_plugin_param' ),
),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Retrieves the query params for the collections. |
| [register\_rest\_route()](../../functions/register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::get_collection_params(): array WP\_REST\_Plugins\_Controller::get\_collection\_params(): array
===============================================================
Retrieves the query params for the collections.
array Query parameters for the collection.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function get_collection_params() {
$query_params = parent::get_collection_params();
$query_params['context']['default'] = 'view';
$query_params['status'] = array(
'description' => __( 'Limits results to plugins with the given status.' ),
'type' => 'array',
'items' => array(
'type' => 'string',
'enum' => is_multisite() ? array( 'inactive', 'active', 'network-active' ) : array( 'inactive', 'active' ),
),
);
unset( $query_params['page'], $query_params['per_page'] );
return $query_params;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Controller::get\_collection\_params()](../wp_rest_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves the query params for the collections. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::register\_routes()](register_routes) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Registers the routes for the plugins controller. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::check_read_permission( string $plugin ): true|WP_Error WP\_REST\_Plugins\_Controller::check\_read\_permission( string $plugin ): true|WP\_Error
========================================================================================
Checks if the given plugin can be viewed by the current user.
On multisite, this hides non-active network only plugins if the user does not have permission to manage network plugins.
`$plugin` string Required The plugin file to check. true|[WP\_Error](../wp_error) True if can read, a [WP\_Error](../wp_error) instance otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
protected function check_read_permission( $plugin ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
if ( ! $this->is_plugin_installed( $plugin ) ) {
return new WP_Error( 'rest_plugin_not_found', __( 'Plugin not found.' ), array( 'status' => 404 ) );
}
if ( ! is_multisite() ) {
return true;
}
if ( ! is_network_only_plugin( $plugin ) || is_plugin_active( $plugin ) || current_user_can( 'manage_network_plugins' ) ) {
return true;
}
return new WP_Error(
'rest_cannot_view_plugin',
__( 'Sorry, you are not allowed to manage this plugin.' ),
array( 'status' => rest_authorization_required_code() )
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::is\_plugin\_installed()](is_plugin_installed) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if the plugin is installed. |
| [is\_network\_only\_plugin()](../../functions/is_network_only_plugin) wp-admin/includes/plugin.php | Checks for “Network: true” in the plugin header to see if this should be activated only as a network wide plugin. The plugin would also work when Multisite is not enabled. |
| [is\_plugin\_active()](../../functions/is_plugin_active) wp-admin/includes/plugin.php | Determines whether a plugin is active. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Retrieves a collection of plugins. |
| [WP\_REST\_Plugins\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if a given request has access to get a specific plugin. |
| [WP\_REST\_Plugins\_Controller::update\_item\_permissions\_check()](update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if a given request has access to update a specific plugin. |
| [WP\_REST\_Plugins\_Controller::delete\_item\_permissions\_check()](delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if a given request has access to delete a specific plugin. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::__construct() WP\_REST\_Plugins\_Controller::\_\_construct()
==============================================
Plugins controller constructor.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'plugins';
}
```
| Used By | Description |
| --- | --- |
| [create\_initial\_rest\_routes()](../../functions/create_initial_rest_routes) wp-includes/rest-api.php | Registers default REST API routes. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::get_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Plugins\_Controller::get\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
==========================================================================================================
Checks if a given request has access to get a specific plugin.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access for the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function get_item_permissions_check( $request ) {
if ( ! current_user_can( 'activate_plugins' ) ) {
return new WP_Error(
'rest_cannot_view_plugin',
__( 'Sorry, you are not allowed to manage plugins for this site.' ),
array( 'status' => rest_authorization_required_code() )
);
}
$can_read = $this->check_read_permission( $request['plugin'] );
if ( is_wp_error( $can_read ) ) {
return $can_read;
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if the given plugin can be viewed by the current user. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::create_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Plugins\_Controller::create\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=============================================================================================================
Checks if a given request has access to upload plugins.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has access to create items, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function create_item_permissions_check( $request ) {
if ( ! current_user_can( 'install_plugins' ) ) {
return new WP_Error(
'rest_cannot_install_plugin',
__( 'Sorry, you are not allowed to install plugins on this site.' ),
array( 'status' => rest_authorization_required_code() )
);
}
if ( 'inactive' !== $request['status'] && ! current_user_can( 'activate_plugins' ) ) {
return new WP_Error(
'rest_cannot_activate_plugin',
__( 'Sorry, you are not allowed to activate plugins.' ),
array(
'status' => rest_authorization_required_code(),
)
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::delete_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Plugins\_Controller::delete\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=======================================================================================================
Deletes one plugin from the site.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function delete_item( $request ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/plugin.php';
$data = $this->get_plugin_data( $request['plugin'] );
if ( is_wp_error( $data ) ) {
return $data;
}
if ( is_plugin_active( $request['plugin'] ) ) {
return new WP_Error(
'rest_cannot_delete_active_plugin',
__( 'Cannot delete an active plugin. Please deactivate it first.' ),
array( 'status' => 400 )
);
}
$filesystem_available = $this->is_filesystem_available();
if ( is_wp_error( $filesystem_available ) ) {
return $filesystem_available;
}
$prepared = $this->prepare_item_for_response( $data, $request );
$deleted = delete_plugins( array( $request['plugin'] ) );
if ( is_wp_error( $deleted ) ) {
$deleted->add_data( array( 'status' => 500 ) );
return $deleted;
}
return new WP_REST_Response(
array(
'deleted' => true,
'previous' => $prepared->get_data(),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::get\_plugin\_data()](get_plugin_data) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Gets the plugin header data for a plugin. |
| [WP\_REST\_Plugins\_Controller::is\_filesystem\_available()](is_filesystem_available) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Determine if the endpoints are available. |
| [WP\_REST\_Plugins\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Prepares the plugin for the REST response. |
| [is\_plugin\_active()](../../functions/is_plugin_active) wp-admin/includes/plugin.php | Determines whether a plugin is active. |
| [delete\_plugins()](../../functions/delete_plugins) wp-admin/includes/plugin.php | Removes directory and files of a plugin for a list of plugins. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::get_item_schema(): array WP\_REST\_Plugins\_Controller::get\_item\_schema(): array
=========================================================
Retrieves the plugin’s schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
public function get_item_schema() {
if ( $this->schema ) {
return $this->add_additional_fields_schema( $this->schema );
}
$this->schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'plugin',
'type' => 'object',
'properties' => array(
'plugin' => array(
'description' => __( 'The plugin file.' ),
'type' => 'string',
'pattern' => self::PATTERN,
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'status' => array(
'description' => __( 'The plugin activation status.' ),
'type' => 'string',
'enum' => is_multisite() ? array( 'inactive', 'active', 'network-active' ) : array( 'inactive', 'active' ),
'context' => array( 'view', 'edit', 'embed' ),
),
'name' => array(
'description' => __( 'The plugin name.' ),
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'plugin_uri' => array(
'description' => __( 'The plugin\'s website address.' ),
'type' => 'string',
'format' => 'uri',
'readonly' => true,
'context' => array( 'view', 'edit' ),
),
'author' => array(
'description' => __( 'The plugin author.' ),
'type' => 'object',
'readonly' => true,
'context' => array( 'view', 'edit' ),
),
'author_uri' => array(
'description' => __( 'Plugin author\'s website address.' ),
'type' => 'string',
'format' => 'uri',
'readonly' => true,
'context' => array( 'view', 'edit' ),
),
'description' => array(
'description' => __( 'The plugin description.' ),
'type' => 'object',
'readonly' => true,
'context' => array( 'view', 'edit' ),
'properties' => array(
'raw' => array(
'description' => __( 'The raw plugin description.' ),
'type' => 'string',
),
'rendered' => array(
'description' => __( 'The plugin description formatted for display.' ),
'type' => 'string',
),
),
),
'version' => array(
'description' => __( 'The plugin version number.' ),
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit' ),
),
'network_only' => array(
'description' => __( 'Whether the plugin can only be activated network-wide.' ),
'type' => 'boolean',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'requires_wp' => array(
'description' => __( 'Minimum required version of WordPress.' ),
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'requires_php' => array(
'description' => __( 'Minimum required version of PHP.' ),
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'textdomain' => array(
'description' => __( 'The plugin\'s text domain.' ),
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit' ),
),
),
);
return $this->add_additional_fields_schema( $this->schema );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Plugins_Controller::get_plugin_status( string $plugin ): string WP\_REST\_Plugins\_Controller::get\_plugin\_status( string $plugin ): string
============================================================================
Get’s the activation status for a plugin.
`$plugin` string Required The plugin file to check. string Either `'network-active'`, `'active'` or `'inactive'`.
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
protected function get_plugin_status( $plugin ) {
if ( is_plugin_active_for_network( $plugin ) ) {
return 'network-active';
}
if ( is_plugin_active( $plugin ) ) {
return 'active';
}
return 'inactive';
}
```
| Uses | Description |
| --- | --- |
| [is\_plugin\_active\_for\_network()](../../functions/is_plugin_active_for_network) wp-admin/includes/plugin.php | Determines whether the plugin is active for the entire network. |
| [is\_plugin\_active()](../../functions/is_plugin_active) wp-admin/includes/plugin.php | Determines whether a plugin is active. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::does\_plugin\_match\_request()](does_plugin_match_request) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if the plugin matches the requested parameters. |
| [WP\_REST\_Plugins\_Controller::update\_item\_permissions\_check()](update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if a given request has access to update a specific plugin. |
| [WP\_REST\_Plugins\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Updates one plugin. |
| [WP\_REST\_Plugins\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Prepares the plugin for the REST response. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::does_plugin_match_request( WP_REST_Request $request, array $item ): bool WP\_REST\_Plugins\_Controller::does\_plugin\_match\_request( WP\_REST\_Request $request, array $item ): bool
============================================================================================================
Checks if the plugin matches the requested parameters.
`$request` [WP\_REST\_Request](../wp_rest_request) Required The request to require the plugin matches against. `$item` array Required The plugin item. bool
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
protected function does_plugin_match_request( $request, $item ) {
$search = $request['search'];
if ( $search ) {
$matched_search = false;
foreach ( $item as $field ) {
if ( is_string( $field ) && false !== strpos( strip_tags( $field ), $search ) ) {
$matched_search = true;
break;
}
}
if ( ! $matched_search ) {
return false;
}
}
$status = $request['status'];
if ( $status && ! in_array( $this->get_plugin_status( $item['_file'] ), $status, true ) ) {
return false;
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::get\_plugin\_status()](get_plugin_status) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Get’s the activation status for a plugin. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Retrieves a collection of plugins. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Plugins_Controller::is_plugin_installed( string $plugin ): bool WP\_REST\_Plugins\_Controller::is\_plugin\_installed( string $plugin ): bool
============================================================================
Checks if the plugin is installed.
`$plugin` string Required The plugin file. bool
File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/)
```
protected function is_plugin_installed( $plugin ) {
return file_exists( WP_PLUGIN_DIR . '/' . $plugin );
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Plugins\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if the given plugin can be viewed by the current user. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Fatal_Error_Handler::detect_error(): array|null WP\_Fatal\_Error\_Handler::detect\_error(): array|null
======================================================
Detects the error causing the crash if it should be handled.
array|null Error information returned by `error_get_last()`, or null if none was recorded or the error should not be handled.
File: `wp-includes/class-wp-fatal-error-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-fatal-error-handler.php/)
```
protected function detect_error() {
$error = error_get_last();
// No error, just skip the error handling code.
if ( null === $error ) {
return null;
}
// Bail if this error should not be handled.
if ( ! $this->should_handle_error( $error ) ) {
return null;
}
return $error;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Fatal\_Error\_Handler::should\_handle\_error()](should_handle_error) wp-includes/class-wp-fatal-error-handler.php | Determines whether we are dealing with an error that WordPress should handle in order to protect the admin backend against WSODs. |
| Used By | Description |
| --- | --- |
| [WP\_Fatal\_Error\_Handler::handle()](handle) wp-includes/class-wp-fatal-error-handler.php | Runs the shutdown handler. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Fatal_Error_Handler::should_handle_error( array $error ): bool WP\_Fatal\_Error\_Handler::should\_handle\_error( array $error ): bool
======================================================================
Determines whether we are dealing with an error that WordPress should handle in order to protect the admin backend against WSODs.
`$error` array Required Error information retrieved from `error_get_last()`. bool Whether WordPress should handle this error.
File: `wp-includes/class-wp-fatal-error-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-fatal-error-handler.php/)
```
protected function should_handle_error( $error ) {
$error_types_to_handle = array(
E_ERROR,
E_PARSE,
E_USER_ERROR,
E_COMPILE_ERROR,
E_RECOVERABLE_ERROR,
);
if ( isset( $error['type'] ) && in_array( $error['type'], $error_types_to_handle, true ) ) {
return true;
}
/**
* Filters whether a given thrown error should be handled by the fatal error handler.
*
* This filter is only fired if the error is not already configured to be handled by WordPress core. As such,
* it exclusively allows adding further rules for which errors should be handled, but not removing existing
* ones.
*
* @since 5.2.0
*
* @param bool $should_handle_error Whether the error should be handled by the fatal error handler.
* @param array $error Error information retrieved from `error_get_last()`.
*/
return (bool) apply_filters( 'wp_should_handle_php_error', false, $error );
}
```
[apply\_filters( 'wp\_should\_handle\_php\_error', bool $should\_handle\_error, array $error )](../../hooks/wp_should_handle_php_error)
Filters whether a given thrown error should be handled by the fatal error handler.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Fatal\_Error\_Handler::detect\_error()](detect_error) wp-includes/class-wp-fatal-error-handler.php | Detects the error causing the crash if it should be handled. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Fatal_Error_Handler::display_error_template( array $error, true|WP_Error $handled ) WP\_Fatal\_Error\_Handler::display\_error\_template( array $error, true|WP\_Error $handled )
============================================================================================
Displays the PHP error template and sends the HTTP status code, typically 500.
A drop-in ‘php-error.php’ can be used as a custom template. This drop-in should control the HTTP status code and print the HTML markup indicating that a PHP error occurred. Note that this drop-in may potentially be executed very early in the WordPress bootstrap process, so any core functions used that are not part of `wp-includes/load.php` should be checked for before being called.
If no such drop-in is available, this will call [WP\_Fatal\_Error\_Handler::display\_default\_error\_template()](../wp_fatal_error_handler/display_default_error_template).
`$error` array Required Error information retrieved from `error_get_last()`. `$handled` true|[WP\_Error](../wp_error) Required Whether Recovery Mode handled the fatal error. File: `wp-includes/class-wp-fatal-error-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-fatal-error-handler.php/)
```
protected function display_error_template( $error, $handled ) {
if ( defined( 'WP_CONTENT_DIR' ) ) {
// Load custom PHP error template, if present.
$php_error_pluggable = WP_CONTENT_DIR . '/php-error.php';
if ( is_readable( $php_error_pluggable ) ) {
require_once $php_error_pluggable;
return;
}
}
// Otherwise, display the default error template.
$this->display_default_error_template( $error, $handled );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Fatal\_Error\_Handler::display\_default\_error\_template()](display_default_error_template) wp-includes/class-wp-fatal-error-handler.php | Displays the default PHP error template. |
| Used By | Description |
| --- | --- |
| [WP\_Fatal\_Error\_Handler::handle()](handle) wp-includes/class-wp-fatal-error-handler.php | Runs the shutdown handler. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | The `$handled` parameter was added. |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Fatal_Error_Handler::display_default_error_template( array $error, true|WP_Error $handled ) WP\_Fatal\_Error\_Handler::display\_default\_error\_template( array $error, true|WP\_Error $handled )
=====================================================================================================
Displays the default PHP error template.
This method is called conditionally if no ‘php-error.php’ drop-in is available.
It calls [wp\_die()](../../functions/wp_die) with a message indicating that the site is experiencing technical difficulties and a login link to the admin backend. The [‘wp\_php\_error\_message’](../../hooks/wp_php_error_message) and [‘wp\_php\_error\_args’](../../hooks/wp_php_error_args) filters can be used to modify these parameters.
`$error` array Required Error information retrieved from `error_get_last()`. `$handled` true|[WP\_Error](../wp_error) Required Whether Recovery Mode handled the fatal error. File: `wp-includes/class-wp-fatal-error-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-fatal-error-handler.php/)
```
protected function display_default_error_template( $error, $handled ) {
if ( ! function_exists( '__' ) ) {
wp_load_translations_early();
}
if ( ! function_exists( 'wp_die' ) ) {
require_once ABSPATH . WPINC . '/functions.php';
}
if ( ! class_exists( 'WP_Error' ) ) {
require_once ABSPATH . WPINC . '/class-wp-error.php';
}
if ( true === $handled && wp_is_recovery_mode() ) {
$message = __( 'There has been a critical error on this website, putting it in recovery mode. Please check the Themes and Plugins screens for more details. If you just installed or updated a theme or plugin, check the relevant page for that first.' );
} elseif ( is_protected_endpoint() && wp_recovery_mode()->is_initialized() ) {
if ( is_multisite() ) {
$message = __( 'There has been a critical error on this website. Please reach out to your site administrator, and inform them of this error for further assistance.' );
} else {
$message = __( 'There has been a critical error on this website. Please check your site admin email inbox for instructions.' );
}
} else {
$message = __( 'There has been a critical error on this website.' );
}
$message = sprintf(
'<p>%s</p><p><a href="%s">%s</a></p>',
$message,
/* translators: Documentation about troubleshooting. */
__( 'https://wordpress.org/support/article/faq-troubleshooting/' ),
__( 'Learn more about troubleshooting WordPress.' )
);
$args = array(
'response' => 500,
'exit' => false,
);
/**
* Filters the message that the default PHP error template displays.
*
* @since 5.2.0
*
* @param string $message HTML error message to display.
* @param array $error Error information retrieved from `error_get_last()`.
*/
$message = apply_filters( 'wp_php_error_message', $message, $error );
/**
* Filters the arguments passed to {@see wp_die()} for the default PHP error template.
*
* @since 5.2.0
*
* @param array $args Associative array of arguments passed to `wp_die()`. By default these contain a
* 'response' key, and optionally 'link_url' and 'link_text' keys.
* @param array $error Error information retrieved from `error_get_last()`.
*/
$args = apply_filters( 'wp_php_error_args', $args, $error );
$wp_error = new WP_Error(
'internal_server_error',
$message,
array(
'error' => $error,
)
);
wp_die( $wp_error, '', $args );
}
```
[apply\_filters( 'wp\_php\_error\_args', array $args, array $error )](../../hooks/wp_php_error_args)
Filters the arguments passed to {@see [wp\_die()](../../functions/wp_die) } for the default PHP error template.
[apply\_filters( 'wp\_php\_error\_message', string $message, array $error )](../../hooks/wp_php_error_message)
Filters the message that the default PHP error template displays.
| Uses | Description |
| --- | --- |
| [WP\_Recovery\_Mode::is\_initialized()](../wp_recovery_mode/is_initialized) wp-includes/class-wp-recovery-mode.php | Checks whether recovery mode has been initialized. |
| [wp\_is\_recovery\_mode()](../../functions/wp_is_recovery_mode) wp-includes/load.php | Is WordPress in Recovery Mode. |
| [is\_protected\_endpoint()](../../functions/is_protected_endpoint) wp-includes/load.php | Determines whether we are currently on an endpoint that should be protected against WSODs. |
| [wp\_recovery\_mode()](../../functions/wp_recovery_mode) wp-includes/error-protection.php | Access the WordPress Recovery Mode instance. |
| [wp\_load\_translations\_early()](../../functions/wp_load_translations_early) wp-includes/load.php | Attempt an early load of translations. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Fatal\_Error\_Handler::display\_error\_template()](display_error_template) wp-includes/class-wp-fatal-error-handler.php | Displays the PHP error template and sends the HTTP status code, typically 500. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | The `$handled` parameter was added. |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Fatal_Error_Handler::handle() WP\_Fatal\_Error\_Handler::handle()
===================================
Runs the shutdown handler.
This method is registered via `register_shutdown_function()`.
File: `wp-includes/class-wp-fatal-error-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-fatal-error-handler.php/)
```
public function handle() {
if ( defined( 'WP_SANDBOX_SCRAPING' ) && WP_SANDBOX_SCRAPING ) {
return;
}
// Do not trigger the fatal error handler while updates are being installed.
if ( wp_is_maintenance_mode() ) {
return;
}
try {
// Bail if no error found.
$error = $this->detect_error();
if ( ! $error ) {
return;
}
if ( ! isset( $GLOBALS['wp_locale'] ) && function_exists( 'load_default_textdomain' ) ) {
load_default_textdomain();
}
$handled = false;
if ( ! is_multisite() && wp_recovery_mode()->is_initialized() ) {
$handled = wp_recovery_mode()->handle_error( $error );
}
// Display the PHP error template if headers not sent.
if ( is_admin() || ! headers_sent() ) {
$this->display_error_template( $error, $handled );
}
} catch ( Exception $e ) {
// Catch exceptions and remain silent.
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_maintenance\_mode()](../../functions/wp_is_maintenance_mode) wp-includes/load.php | Check if maintenance mode is enabled. |
| [WP\_Recovery\_Mode::is\_initialized()](../wp_recovery_mode/is_initialized) wp-includes/class-wp-recovery-mode.php | Checks whether recovery mode has been initialized. |
| [WP\_Recovery\_Mode::handle\_error()](../wp_recovery_mode/handle_error) wp-includes/class-wp-recovery-mode.php | Handles a fatal error occurring. |
| [wp\_recovery\_mode()](../../functions/wp_recovery_mode) wp-includes/error-protection.php | Access the WordPress Recovery Mode instance. |
| [WP\_Fatal\_Error\_Handler::detect\_error()](detect_error) wp-includes/class-wp-fatal-error-handler.php | Detects the error causing the crash if it should be handled. |
| [WP\_Fatal\_Error\_Handler::display\_error\_template()](display_error_template) wp-includes/class-wp-fatal-error-handler.php | Displays the PHP error template and sends the HTTP status code, typically 500. |
| [load\_default\_textdomain()](../../functions/load_default_textdomain) wp-includes/l10n.php | Loads default translated strings based on locale. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress IXR_IntrospectionServer::methodSignature( $method ) IXR\_IntrospectionServer::methodSignature( $method )
====================================================
File: `wp-includes/IXR/class-IXR-introspectionserver.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-introspectionserver.php/)
```
function methodSignature($method)
{
if (!$this->hasMethod($method)) {
return new IXR_Error(-32601, 'server error. requested method "'.$method.'" not specified.');
}
// We should be returning an array of types
$types = $this->signatures[$method];
$return = array();
foreach ($types as $type) {
switch ($type) {
case 'string':
$return[] = 'string';
break;
case 'int':
case 'i4':
$return[] = 42;
break;
case 'double':
$return[] = 3.1415;
break;
case 'dateTime.iso8601':
$return[] = new IXR_Date(time());
break;
case 'boolean':
$return[] = true;
break;
case 'base64':
$return[] = new IXR_Base64('base64');
break;
case 'array':
$return[] = array('array');
break;
case 'struct':
$return[] = array('struct' => 'struct');
break;
}
}
return $return;
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Base64::\_\_construct()](../ixr_base64/__construct) wp-includes/IXR/class-IXR-base64.php | PHP5 constructor. |
| [IXR\_Date::\_\_construct()](../ixr_date/__construct) wp-includes/IXR/class-IXR-date.php | PHP5 constructor. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
wordpress IXR_IntrospectionServer::methodHelp( $method ) IXR\_IntrospectionServer::methodHelp( $method )
===============================================
File: `wp-includes/IXR/class-IXR-introspectionserver.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-introspectionserver.php/)
```
function methodHelp($method)
{
return $this->help[$method];
}
```
wordpress IXR_IntrospectionServer::addCallback( $method, $callback, $args, $help ) IXR\_IntrospectionServer::addCallback( $method, $callback, $args, $help )
=========================================================================
File: `wp-includes/IXR/class-IXR-introspectionserver.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-introspectionserver.php/)
```
function addCallback($method, $callback, $args, $help)
{
$this->callbacks[$method] = $callback;
$this->signatures[$method] = $args;
$this->help[$method] = $help;
}
```
| Used By | Description |
| --- | --- |
| [IXR\_IntrospectionServer::\_\_construct()](__construct) wp-includes/IXR/class-IXR-introspectionserver.php | PHP5 constructor. |
wordpress IXR_IntrospectionServer::call( $methodname, $args ) IXR\_IntrospectionServer::call( $methodname, $args )
====================================================
File: `wp-includes/IXR/class-IXR-introspectionserver.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-introspectionserver.php/)
```
function call($methodname, $args)
{
// Make sure it's in an array
if ($args && !is_array($args)) {
$args = array($args);
}
// Over-rides default call method, adds signature check
if (!$this->hasMethod($methodname)) {
return new IXR_Error(-32601, 'server error. requested method "'.$this->message->methodName.'" not specified.');
}
$method = $this->callbacks[$methodname];
$signature = $this->signatures[$methodname];
$returnType = array_shift($signature);
// Check the number of arguments
if (count($args) != count($signature)) {
return new IXR_Error(-32602, 'server error. wrong number of method parameters');
}
// Check the argument types
$ok = true;
$argsbackup = $args;
for ($i = 0, $j = count($args); $i < $j; $i++) {
$arg = array_shift($args);
$type = array_shift($signature);
switch ($type) {
case 'int':
case 'i4':
if (is_array($arg) || !is_int($arg)) {
$ok = false;
}
break;
case 'base64':
case 'string':
if (!is_string($arg)) {
$ok = false;
}
break;
case 'boolean':
if ($arg !== false && $arg !== true) {
$ok = false;
}
break;
case 'float':
case 'double':
if (!is_float($arg)) {
$ok = false;
}
break;
case 'date':
case 'dateTime.iso8601':
if (!is_a($arg, 'IXR_Date')) {
$ok = false;
}
break;
}
if (!$ok) {
return new IXR_Error(-32602, 'server error. invalid method parameters');
}
}
// It passed the test - run the "real" method call
return parent::call($methodname, $argsbackup);
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Server::call()](../ixr_server/call) wp-includes/IXR/class-IXR-server.php | |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
wordpress IXR_IntrospectionServer::IXR_IntrospectionServer() IXR\_IntrospectionServer::IXR\_IntrospectionServer()
====================================================
PHP4 constructor.
File: `wp-includes/IXR/class-IXR-introspectionserver.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-introspectionserver.php/)
```
public function IXR_IntrospectionServer() {
self::__construct();
}
```
| Uses | Description |
| --- | --- |
| [IXR\_IntrospectionServer::\_\_construct()](__construct) wp-includes/IXR/class-IXR-introspectionserver.php | PHP5 constructor. |
wordpress IXR_IntrospectionServer::__construct() IXR\_IntrospectionServer::\_\_construct()
=========================================
PHP5 constructor.
File: `wp-includes/IXR/class-IXR-introspectionserver.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-introspectionserver.php/)
```
function __construct()
{
$this->setCallbacks();
$this->setCapabilities();
$this->capabilities['introspection'] = array(
'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html',
'specVersion' => 1
);
$this->addCallback(
'system.methodSignature',
'this:methodSignature',
array('array', 'string'),
'Returns an array describing the return type and required parameters of a method'
);
$this->addCallback(
'system.getCapabilities',
'this:getCapabilities',
array('struct'),
'Returns a struct describing the XML-RPC specifications supported by this server'
);
$this->addCallback(
'system.listMethods',
'this:listMethods',
array('array'),
'Returns an array of available methods on this server'
);
$this->addCallback(
'system.methodHelp',
'this:methodHelp',
array('string', 'string'),
'Returns a documentation string for the specified method'
);
}
```
| Uses | Description |
| --- | --- |
| [IXR\_IntrospectionServer::addCallback()](addcallback) wp-includes/IXR/class-IXR-introspectionserver.php | |
| Used By | Description |
| --- | --- |
| [IXR\_IntrospectionServer::IXR\_IntrospectionServer()](ixr_introspectionserver) wp-includes/IXR/class-IXR-introspectionserver.php | PHP4 constructor. |
wordpress WP_REST_Term_Meta_Fields::get_meta_subtype(): string WP\_REST\_Term\_Meta\_Fields::get\_meta\_subtype(): string
==========================================================
Retrieves the term meta subtype.
string Subtype for the meta type, or empty string if no specific subtype.
File: `wp-includes/rest-api/fields/class-wp-rest-term-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-term-meta-fields.php/)
```
protected function get_meta_subtype() {
return $this->taxonomy;
}
```
| Version | Description |
| --- | --- |
| [4.9.8](https://developer.wordpress.org/reference/since/4.9.8/) | Introduced. |
wordpress WP_REST_Term_Meta_Fields::get_rest_field_type(): string WP\_REST\_Term\_Meta\_Fields::get\_rest\_field\_type(): string
==============================================================
Retrieves the type for [register\_rest\_field()](../../functions/register_rest_field) .
string The REST field type.
File: `wp-includes/rest-api/fields/class-wp-rest-term-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-term-meta-fields.php/)
```
public function get_rest_field_type() {
return 'post_tag' === $this->taxonomy ? 'tag' : $this->taxonomy;
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Term_Meta_Fields::__construct( string $taxonomy ) WP\_REST\_Term\_Meta\_Fields::\_\_construct( string $taxonomy )
===============================================================
Constructor.
`$taxonomy` string Required Taxonomy to register fields for. File: `wp-includes/rest-api/fields/class-wp-rest-term-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-term-meta-fields.php/)
```
public function __construct( $taxonomy ) {
$this->taxonomy = $taxonomy;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Terms\_Controller::\_\_construct()](../wp_rest_terms_controller/__construct) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Term_Meta_Fields::get_meta_type(): string WP\_REST\_Term\_Meta\_Fields::get\_meta\_type(): string
=======================================================
Retrieves the term meta type.
string The meta type.
File: `wp-includes/rest-api/fields/class-wp-rest-term-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-term-meta-fields.php/)
```
protected function get_meta_type() {
return 'term';
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Upgrader_Skin::feedback( string $feedback, mixed $args ) WP\_Upgrader\_Skin::feedback( string $feedback, mixed $args )
=============================================================
`$feedback` string Required Message data. `$args` mixed Optional text replacements. File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function feedback( $feedback, ...$args ) {
if ( isset( $this->upgrader->strings[ $feedback ] ) ) {
$feedback = $this->upgrader->strings[ $feedback ];
}
if ( strpos( $feedback, '%' ) !== false ) {
if ( $args ) {
$args = array_map( 'strip_tags', $args );
$args = array_map( 'esc_html', $args );
$feedback = vsprintf( $feedback, $args );
}
}
if ( empty( $feedback ) ) {
return;
}
show_message( $feedback );
}
```
| Uses | Description |
| --- | --- |
| [show\_message()](../../functions/show_message) wp-admin/includes/misc.php | Displays the given administration message. |
| Used By | Description |
| --- | --- |
| [WP\_Upgrader\_Skin::error()](error) wp-admin/includes/class-wp-upgrader-skin.php | |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$string` (a PHP reserved keyword) to `$feedback` for PHP 8 named parameter support. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader_Skin::decrement_update_count( string $type ) WP\_Upgrader\_Skin::decrement\_update\_count( string $type )
============================================================
Output JavaScript that calls function to decrement the update counts.
`$type` string Required Type of update count to decrement. Likely values include `'plugin'`, `'theme'`, `'translation'`, etc. File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
protected function decrement_update_count( $type ) {
if ( ! $this->result || is_wp_error( $this->result ) || 'up_to_date' === $this->result ) {
return;
}
if ( defined( 'IFRAME_REQUEST' ) ) {
echo '<script type="text/javascript">
if ( window.postMessage && JSON ) {
window.parent.postMessage( JSON.stringify( { action: "decrementUpdateCount", upgradeType: "' . $type . '" } ), window.location.protocol + "//" + window.location.hostname );
}
</script>';
} else {
echo '<script type="text/javascript">
(function( wp ) {
if ( wp && wp.updates && wp.updates.decrementCount ) {
wp.updates.decrementCount( "' . $type . '" );
}
})( window.wp );
</script>';
}
}
```
| Uses | Description |
| --- | --- |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Upgrader_Skin::set_upgrader( WP_Upgrader $upgrader ) WP\_Upgrader\_Skin::set\_upgrader( WP\_Upgrader $upgrader )
===========================================================
`$upgrader` [WP\_Upgrader](../wp_upgrader) Required File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function set_upgrader( &$upgrader ) {
if ( is_object( $upgrader ) ) {
$this->upgrader =& $upgrader;
}
$this->add_strings();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Upgrader\_Skin::add\_strings()](add_strings) wp-admin/includes/class-wp-upgrader-skin.php | |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader_Skin::request_filesystem_credentials( bool|WP_Error $error = false, string $context = '', bool $allow_relaxed_file_ownership = false ): bool WP\_Upgrader\_Skin::request\_filesystem\_credentials( bool|WP\_Error $error = false, string $context = '', bool $allow\_relaxed\_file\_ownership = false ): bool
================================================================================================================================================================
Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem.
* [request\_filesystem\_credentials()](../../functions/request_filesystem_credentials)
`$error` bool|[WP\_Error](../wp_error) Optional Whether the current request has failed to connect, or an error object. Default: `false`
`$context` string Optional Full path to the directory that is tested for being writable. Default: `''`
`$allow_relaxed_file_ownership` bool Optional Whether to allow Group/World writable. Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function request_filesystem_credentials( $error = false, $context = '', $allow_relaxed_file_ownership = false ) {
$url = $this->options['url'];
if ( ! $context ) {
$context = $this->options['context'];
}
if ( ! empty( $this->options['nonce'] ) ) {
$url = wp_nonce_url( $url, $this->options['nonce'] );
}
$extra_fields = array();
return request_filesystem_credentials( $url, '', $error, $context, $extra_fields, $allow_relaxed_file_ownership );
}
```
| Uses | Description |
| --- | --- |
| [request\_filesystem\_credentials()](../../functions/request_filesystem_credentials) wp-admin/includes/file.php | Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem. |
| [wp\_nonce\_url()](../../functions/wp_nonce_url) wp-includes/functions.php | Retrieves URL with nonce added to URL query. |
| Used By | Description |
| --- | --- |
| [Automatic\_Upgrader\_Skin::request\_filesystem\_credentials()](../automatic_upgrader_skin/request_filesystem_credentials) wp-admin/includes/class-automatic-upgrader-skin.php | Determines whether the upgrader needs FTP/SSH details in order to connect to the filesystem. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | The `$context` parameter default changed from `false` to an empty string. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader_Skin::after() WP\_Upgrader\_Skin::after()
===========================
Action to perform following an update.
File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function after() {}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader_Skin::hide_process_failed( WP_Error $wp_error ): bool WP\_Upgrader\_Skin::hide\_process\_failed( WP\_Error $wp\_error ): bool
=======================================================================
Hides the `process_failed` error message when updating by uploading a zip file.
`$wp_error` [WP\_Error](../wp_error) Required [WP\_Error](../wp_error) object. bool
File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function hide_process_failed( $wp_error ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Upgrader_Skin::set_result( string|bool|WP_Error $result ) WP\_Upgrader\_Skin::set\_result( string|bool|WP\_Error $result )
================================================================
Sets the result of an upgrade.
`$result` string|bool|[WP\_Error](../wp_error) Required The result of an upgrade. File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function set_result( $result ) {
$this->result = $result;
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader_Skin::__construct( array $args = array() ) WP\_Upgrader\_Skin::\_\_construct( array $args = array() )
==========================================================
Constructor.
Sets up the generic skin for the WordPress Upgrader classes.
`$args` array Optional The WordPress upgrader skin arguments to override default options. Default: `array()`
File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function __construct( $args = array() ) {
$defaults = array(
'url' => '',
'nonce' => '',
'title' => '',
'context' => false,
);
$this->options = wp_parse_args( $args, $defaults );
}
```
| Uses | Description |
| --- | --- |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Used By | Description |
| --- | --- |
| [WP\_Upgrader::\_\_construct()](../wp_upgrader/__construct) wp-admin/includes/class-wp-upgrader.php | Construct the upgrader with a skin. |
| [Language\_Pack\_Upgrader\_Skin::\_\_construct()](../language_pack_upgrader_skin/__construct) wp-admin/includes/class-language-pack-upgrader-skin.php | |
| [Theme\_Upgrader\_Skin::\_\_construct()](../theme_upgrader_skin/__construct) wp-admin/includes/class-theme-upgrader-skin.php | Constructor. |
| [Plugin\_Installer\_Skin::\_\_construct()](../plugin_installer_skin/__construct) wp-admin/includes/class-plugin-installer-skin.php | |
| [Theme\_Installer\_Skin::\_\_construct()](../theme_installer_skin/__construct) wp-admin/includes/class-theme-installer-skin.php | |
| [Plugin\_Upgrader\_Skin::\_\_construct()](../plugin_upgrader_skin/__construct) wp-admin/includes/class-plugin-upgrader-skin.php | Constructor. |
| [Bulk\_Upgrader\_Skin::\_\_construct()](../bulk_upgrader_skin/__construct) wp-admin/includes/class-bulk-upgrader-skin.php | |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Upgrader_Skin::footer() WP\_Upgrader\_Skin::footer()
============================
File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function footer() {
if ( $this->done_footer ) {
return;
}
$this->done_footer = true;
echo '</div>';
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader_Skin::bulk_header() WP\_Upgrader\_Skin::bulk\_header()
==================================
File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function bulk_header() {}
```
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress WP_Upgrader_Skin::header() WP\_Upgrader\_Skin::header()
============================
File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function header() {
if ( $this->done_header ) {
return;
}
$this->done_header = true;
echo '<div class="wrap">';
echo '<h1>' . $this->options['title'] . '</h1>';
}
```
| Used By | Description |
| --- | --- |
| [WP\_Upgrader\_Skin::error()](error) wp-admin/includes/class-wp-upgrader-skin.php | |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader_Skin::error( string|WP_Error $errors ) WP\_Upgrader\_Skin::error( string|WP\_Error $errors )
=====================================================
`$errors` string|[WP\_Error](../wp_error) Required Errors. File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function error( $errors ) {
if ( ! $this->done_header ) {
$this->header();
}
if ( is_string( $errors ) ) {
$this->feedback( $errors );
} elseif ( is_wp_error( $errors ) && $errors->has_errors() ) {
foreach ( $errors->get_error_messages() as $message ) {
if ( $errors->get_error_data() && is_string( $errors->get_error_data() ) ) {
$this->feedback( $message . ' ' . esc_html( strip_tags( $errors->get_error_data() ) ) );
} else {
$this->feedback( $message );
}
}
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Upgrader\_Skin::feedback()](feedback) wp-admin/includes/class-wp-upgrader-skin.php | |
| [WP\_Upgrader\_Skin::header()](header) wp-admin/includes/class-wp-upgrader-skin.php | |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [Language\_Pack\_Upgrader\_Skin::error()](../language_pack_upgrader_skin/error) wp-admin/includes/class-language-pack-upgrader-skin.php | |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader_Skin::add_strings() WP\_Upgrader\_Skin::add\_strings()
==================================
File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function add_strings() {
}
```
| Used By | Description |
| --- | --- |
| [WP\_Upgrader\_Skin::set\_upgrader()](set_upgrader) wp-admin/includes/class-wp-upgrader-skin.php | |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress WP_Upgrader_Skin::bulk_footer() WP\_Upgrader\_Skin::bulk\_footer()
==================================
File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function bulk_footer() {}
```
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress WP_Upgrader_Skin::before() WP\_Upgrader\_Skin::before()
============================
Action to perform before an update.
File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
public function before() {}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Media_Image::get_instance_schema(): array WP\_Widget\_Media\_Image::get\_instance\_schema(): array
========================================================
Get schema for properties of a widget instance (item).
* [WP\_REST\_Controller::get\_item\_schema()](../wp_rest_controller/get_item_schema)
* [WP\_REST\_Controller::get\_additional\_fields()](../wp_rest_controller/get_additional_fields)
array Schema for properties.
File: `wp-includes/widgets/class-wp-widget-media-image.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-image.php/)
```
public function get_instance_schema() {
return array_merge(
array(
'size' => array(
'type' => 'string',
'enum' => array_merge( get_intermediate_image_sizes(), array( 'full', 'custom' ) ),
'default' => 'medium',
'description' => __( 'Size' ),
),
'width' => array( // Via 'customWidth', only when size=custom; otherwise via 'width'.
'type' => 'integer',
'minimum' => 0,
'default' => 0,
'description' => __( 'Width' ),
),
'height' => array( // Via 'customHeight', only when size=custom; otherwise via 'height'.
'type' => 'integer',
'minimum' => 0,
'default' => 0,
'description' => __( 'Height' ),
),
'caption' => array(
'type' => 'string',
'default' => '',
'sanitize_callback' => 'wp_kses_post',
'description' => __( 'Caption' ),
'should_preview_update' => false,
),
'alt' => array(
'type' => 'string',
'default' => '',
'sanitize_callback' => 'sanitize_text_field',
'description' => __( 'Alternative Text' ),
),
'link_type' => array(
'type' => 'string',
'enum' => array( 'none', 'file', 'post', 'custom' ),
'default' => 'custom',
'media_prop' => 'link',
'description' => __( 'Link To' ),
'should_preview_update' => true,
),
'link_url' => array(
'type' => 'string',
'default' => '',
'format' => 'uri',
'media_prop' => 'linkUrl',
'description' => __( 'URL' ),
'should_preview_update' => true,
),
'image_classes' => array(
'type' => 'string',
'default' => '',
'sanitize_callback' => array( $this, 'sanitize_token_list' ),
'media_prop' => 'extraClasses',
'description' => __( 'Image CSS Class' ),
'should_preview_update' => false,
),
'link_classes' => array(
'type' => 'string',
'default' => '',
'sanitize_callback' => array( $this, 'sanitize_token_list' ),
'media_prop' => 'linkClassName',
'should_preview_update' => false,
'description' => __( 'Link CSS Class' ),
),
'link_rel' => array(
'type' => 'string',
'default' => '',
'sanitize_callback' => array( $this, 'sanitize_token_list' ),
'media_prop' => 'linkRel',
'description' => __( 'Link Rel' ),
'should_preview_update' => false,
),
'link_target_blank' => array(
'type' => 'boolean',
'default' => false,
'media_prop' => 'linkTargetBlank',
'description' => __( 'Open link in a new tab' ),
'should_preview_update' => false,
),
'image_title' => array(
'type' => 'string',
'default' => '',
'sanitize_callback' => 'sanitize_text_field',
'media_prop' => 'title',
'description' => __( 'Image Title Attribute' ),
'should_preview_update' => false,
),
/*
* There are two additional properties exposed by the PostImage modal
* that don't seem to be relevant, as they may only be derived read-only
* values:
* - originalUrl
* - aspectRatio
* - height (redundant when size is not custom)
* - width (redundant when size is not custom)
*/
),
parent::get_instance_schema()
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Media::get\_instance\_schema()](../wp_widget_media/get_instance_schema) wp-includes/widgets/class-wp-widget-media.php | Get schema for properties of a widget instance (item). |
| [get\_intermediate\_image\_sizes()](../../functions/get_intermediate_image_sizes) wp-includes/media.php | Gets the available intermediate image size names. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Media\_Image::render\_media()](render_media) wp-includes/widgets/class-wp-widget-media-image.php | Render the media on the frontend. |
| [WP\_Widget\_Media\_Image::enqueue\_admin\_scripts()](enqueue_admin_scripts) wp-includes/widgets/class-wp-widget-media-image.php | Loads the required media files for the media manager and scripts for media widgets. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media_Image::enqueue_admin_scripts() WP\_Widget\_Media\_Image::enqueue\_admin\_scripts()
===================================================
Loads the required media files for the media manager and scripts for media widgets.
File: `wp-includes/widgets/class-wp-widget-media-image.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-image.php/)
```
public function enqueue_admin_scripts() {
parent::enqueue_admin_scripts();
$handle = 'media-image-widget';
wp_enqueue_script( $handle );
$exported_schema = array();
foreach ( $this->get_instance_schema() as $field => $field_schema ) {
$exported_schema[ $field ] = wp_array_slice_assoc( $field_schema, array( 'type', 'default', 'enum', 'minimum', 'format', 'media_prop', 'should_preview_update' ) );
}
wp_add_inline_script(
$handle,
sprintf(
'wp.mediaWidgets.modelConstructors[ %s ].prototype.schema = %s;',
wp_json_encode( $this->id_base ),
wp_json_encode( $exported_schema )
)
);
wp_add_inline_script(
$handle,
sprintf(
'
wp.mediaWidgets.controlConstructors[ %1$s ].prototype.mime_type = %2$s;
wp.mediaWidgets.controlConstructors[ %1$s ].prototype.l10n = _.extend( {}, wp.mediaWidgets.controlConstructors[ %1$s ].prototype.l10n, %3$s );
',
wp_json_encode( $this->id_base ),
wp_json_encode( $this->widget_options['mime_type'] ),
wp_json_encode( $this->l10n )
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Media::enqueue\_admin\_scripts()](../wp_widget_media/enqueue_admin_scripts) wp-includes/widgets/class-wp-widget-media.php | Loads the required scripts and styles for the widget control. |
| [WP\_Widget\_Media\_Image::get\_instance\_schema()](get_instance_schema) wp-includes/widgets/class-wp-widget-media-image.php | Get schema for properties of a widget instance (item). |
| [wp\_add\_inline\_script()](../../functions/wp_add_inline_script) wp-includes/functions.wp-scripts.php | Adds extra code to a registered script. |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media_Image::render_media( array $instance ) WP\_Widget\_Media\_Image::render\_media( array $instance )
==========================================================
Render the media on the frontend.
`$instance` array Required Widget instance props. File: `wp-includes/widgets/class-wp-widget-media-image.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-image.php/)
```
public function render_media( $instance ) {
$instance = array_merge( wp_list_pluck( $this->get_instance_schema(), 'default' ), $instance );
$instance = wp_parse_args(
$instance,
array(
'size' => 'thumbnail',
)
);
$attachment = null;
if ( $this->is_attachment_with_mime_type( $instance['attachment_id'], $this->widget_options['mime_type'] ) ) {
$attachment = get_post( $instance['attachment_id'] );
}
if ( $attachment ) {
$caption = '';
if ( ! isset( $instance['caption'] ) ) {
$caption = $attachment->post_excerpt;
} elseif ( trim( $instance['caption'] ) ) {
$caption = $instance['caption'];
}
$image_attributes = array(
'class' => sprintf( 'image wp-image-%d %s', $attachment->ID, $instance['image_classes'] ),
'style' => 'max-width: 100%; height: auto;',
);
if ( ! empty( $instance['image_title'] ) ) {
$image_attributes['title'] = $instance['image_title'];
}
if ( $instance['alt'] ) {
$image_attributes['alt'] = $instance['alt'];
}
$size = $instance['size'];
if ( 'custom' === $size || ! in_array( $size, array_merge( get_intermediate_image_sizes(), array( 'full' ) ), true ) ) {
$size = array( $instance['width'], $instance['height'] );
$width = $instance['width'];
} else {
$caption_size = _wp_get_image_size_from_meta( $instance['size'], wp_get_attachment_metadata( $attachment->ID ) );
$width = empty( $caption_size[0] ) ? 0 : $caption_size[0];
}
$image_attributes['class'] .= sprintf( ' attachment-%1$s size-%1$s', is_array( $size ) ? implode( 'x', $size ) : $size );
$image = wp_get_attachment_image( $attachment->ID, $size, false, $image_attributes );
} else {
if ( empty( $instance['url'] ) ) {
return;
}
$instance['size'] = 'custom';
$caption = $instance['caption'];
$width = $instance['width'];
$classes = 'image ' . $instance['image_classes'];
if ( 0 === $instance['width'] ) {
$instance['width'] = '';
}
if ( 0 === $instance['height'] ) {
$instance['height'] = '';
}
$image = sprintf(
'<img class="%1$s" src="%2$s" alt="%3$s" width="%4$s" height="%5$s" />',
esc_attr( $classes ),
esc_url( $instance['url'] ),
esc_attr( $instance['alt'] ),
esc_attr( $instance['width'] ),
esc_attr( $instance['height'] )
);
} // End if().
$url = '';
if ( 'file' === $instance['link_type'] ) {
$url = $attachment ? wp_get_attachment_url( $attachment->ID ) : $instance['url'];
} elseif ( $attachment && 'post' === $instance['link_type'] ) {
$url = get_attachment_link( $attachment->ID );
} elseif ( 'custom' === $instance['link_type'] && ! empty( $instance['link_url'] ) ) {
$url = $instance['link_url'];
}
if ( $url ) {
$link = sprintf( '<a href="%s"', esc_url( $url ) );
if ( ! empty( $instance['link_classes'] ) ) {
$link .= sprintf( ' class="%s"', esc_attr( $instance['link_classes'] ) );
}
if ( ! empty( $instance['link_rel'] ) ) {
$link .= sprintf( ' rel="%s"', esc_attr( $instance['link_rel'] ) );
}
if ( ! empty( $instance['link_target_blank'] ) ) {
$link .= ' target="_blank"';
}
$link .= '>';
$link .= $image;
$link .= '</a>';
$image = wp_targeted_link_rel( $link );
}
if ( $caption ) {
$image = img_caption_shortcode(
array(
'width' => $width,
'caption' => $caption,
),
$image
);
}
echo $image;
}
```
| Uses | Description |
| --- | --- |
| [wp\_targeted\_link\_rel()](../../functions/wp_targeted_link_rel) wp-includes/formatting.php | Adds `rel="noopener"` to all HTML A elements that have a target. |
| [WP\_Widget\_Media\_Image::get\_instance\_schema()](get_instance_schema) wp-includes/widgets/class-wp-widget-media-image.php | Get schema for properties of a widget instance (item). |
| [\_wp\_get\_image\_size\_from\_meta()](../../functions/_wp_get_image_size_from_meta) wp-includes/media.php | Gets the image size as array from its meta data. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [get\_attachment\_link()](../../functions/get_attachment_link) wp-includes/link-template.php | Retrieves the permalink for an attachment. |
| [get\_intermediate\_image\_sizes()](../../functions/get_intermediate_image_sizes) wp-includes/media.php | Gets the available intermediate image size names. |
| [wp\_get\_attachment\_image()](../../functions/wp_get_attachment_image) wp-includes/media.php | Gets an HTML img element representing an image attachment. |
| [img\_caption\_shortcode()](../../functions/img_caption_shortcode) wp-includes/media.php | Builds the Caption shortcode output. |
| [wp\_get\_attachment\_metadata()](../../functions/wp_get_attachment_metadata) wp-includes/post.php | Retrieves attachment metadata for attachment ID. |
| [wp\_get\_attachment\_url()](../../functions/wp_get_attachment_url) wp-includes/post.php | Retrieves the URL for an attachment. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media_Image::render_control_template_scripts() WP\_Widget\_Media\_Image::render\_control\_template\_scripts()
==============================================================
Render form template scripts.
File: `wp-includes/widgets/class-wp-widget-media-image.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-image.php/)
```
public function render_control_template_scripts() {
parent::render_control_template_scripts();
?>
<script type="text/html" id="tmpl-wp-media-widget-image-fields">
<# var elementIdPrefix = 'el' + String( Math.random() ) + '_'; #>
<# if ( data.url ) { #>
<p class="media-widget-image-link">
<label for="{{ elementIdPrefix }}linkUrl"><?php esc_html_e( 'Link to:' ); ?></label>
<input id="{{ elementIdPrefix }}linkUrl" type="text" class="widefat link" value="{{ data.link_url }}" placeholder="https://" pattern="((\w+:)?\/\/\w.*|\w+:(?!\/\/$)|\/|\?|#).*">
</p>
<# } #>
</script>
<script type="text/html" id="tmpl-wp-media-widget-image-preview">
<# if ( data.error && 'missing_attachment' === data.error ) { #>
<div class="notice notice-error notice-alt notice-missing-attachment">
<p><?php echo $this->l10n['missing_attachment']; ?></p>
</div>
<# } else if ( data.error ) { #>
<div class="notice notice-error notice-alt">
<p><?php _e( 'Unable to preview media due to an unknown error.' ); ?></p>
</div>
<# } else if ( data.url ) { #>
<img class="attachment-thumb" src="{{ data.url }}" draggable="false" alt="{{ data.alt }}"
<# if ( ! data.alt && data.currentFilename ) { #>
aria-label="
<?php
echo esc_attr(
sprintf(
/* translators: %s: The image file name. */
__( 'The current image has no alternative text. The file name is: %s' ),
'{{ data.currentFilename }}'
)
);
?>
"
<# } #>
/>
<# } #>
</script>
<?php
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Media::render\_control\_template\_scripts()](../wp_widget_media/render_control_template_scripts) wp-includes/widgets/class-wp-widget-media.php | Render form template scripts. |
| [esc\_html\_e()](../../functions/esc_html_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in HTML output. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Widget_Media_Image::__construct() WP\_Widget\_Media\_Image::\_\_construct()
=========================================
Constructor.
File: `wp-includes/widgets/class-wp-widget-media-image.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-image.php/)
```
public function __construct() {
parent::__construct(
'media_image',
__( 'Image' ),
array(
'description' => __( 'Displays an image.' ),
'mime_type' => 'image',
)
);
$this->l10n = array_merge(
$this->l10n,
array(
'no_media_selected' => __( 'No image selected' ),
'add_media' => _x( 'Add Image', 'label for button in the image widget' ),
'replace_media' => _x( 'Replace Image', 'label for button in the image widget; should preferably not be longer than ~13 characters long' ),
'edit_media' => _x( 'Edit Image', 'label for button in the image widget; should preferably not be longer than ~13 characters long' ),
'missing_attachment' => sprintf(
/* translators: %s: URL to media library. */
__( 'That image cannot be found. Check your <a href="%s">media library</a> and make sure it was not deleted.' ),
esc_url( admin_url( 'upload.php' ) )
),
/* translators: %d: Widget count. */
'media_library_state_multi' => _n_noop( 'Image Widget (%d)', 'Image Widget (%d)' ),
'media_library_state_single' => __( 'Image Widget' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Media::\_\_construct()](../wp_widget_media/__construct) wp-includes/widgets/class-wp-widget-media.php | Constructor. |
| [\_n\_noop()](../../functions/_n_noop) wp-includes/l10n.php | Registers plural strings in POT file, but does not translate them. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_REST_Post_Types_Controller::get_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Post\_Types\_Controller::get\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
========================================================================================================
Retrieves a specific post type.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php/)
```
public function get_item( $request ) {
$obj = get_post_type_object( $request['type'] );
if ( empty( $obj ) ) {
return new WP_Error(
'rest_type_invalid',
__( 'Invalid post type.' ),
array( 'status' => 404 )
);
}
if ( empty( $obj->show_in_rest ) ) {
return new WP_Error(
'rest_cannot_read_type',
__( 'Cannot view post type.' ),
array( 'status' => rest_authorization_required_code() )
);
}
if ( 'edit' === $request['context'] && ! current_user_can( $obj->cap->edit_posts ) ) {
return new WP_Error(
'rest_forbidden_context',
__( 'Sorry, you are not allowed to edit posts in this post type.' ),
array( 'status' => rest_authorization_required_code() )
);
}
$data = $this->prepare_item_for_response( $obj, $request );
return rest_ensure_response( $data );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Post\_Types\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php | Prepares a post type object for serialization. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Post_Types_Controller::prepare_item_for_response( WP_Post_Type $item, WP_REST_Request $request ): WP_REST_Response WP\_REST\_Post\_Types\_Controller::prepare\_item\_for\_response( WP\_Post\_Type $item, WP\_REST\_Request $request ): WP\_REST\_Response
=======================================================================================================================================
Prepares a post type object for serialization.
`$item` [WP\_Post\_Type](../wp_post_type) Required Post type object. `$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response) Response object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php/)
```
public function prepare_item_for_response( $item, $request ) {
// Restores the more descriptive, specific name for use within this method.
$post_type = $item;
$taxonomies = wp_list_filter( get_object_taxonomies( $post_type->name, 'objects' ), array( 'show_in_rest' => true ) );
$taxonomies = wp_list_pluck( $taxonomies, 'name' );
$base = ! empty( $post_type->rest_base ) ? $post_type->rest_base : $post_type->name;
$namespace = ! empty( $post_type->rest_namespace ) ? $post_type->rest_namespace : 'wp/v2';
$supports = get_all_post_type_supports( $post_type->name );
$fields = $this->get_fields_for_response( $request );
$data = array();
if ( rest_is_field_included( 'capabilities', $fields ) ) {
$data['capabilities'] = $post_type->cap;
}
if ( rest_is_field_included( 'description', $fields ) ) {
$data['description'] = $post_type->description;
}
if ( rest_is_field_included( 'hierarchical', $fields ) ) {
$data['hierarchical'] = $post_type->hierarchical;
}
if ( rest_is_field_included( 'has_archive', $fields ) ) {
$data['has_archive'] = $post_type->has_archive;
}
if ( rest_is_field_included( 'visibility', $fields ) ) {
$data['visibility'] = array(
'show_in_nav_menus' => (bool) $post_type->show_in_nav_menus,
'show_ui' => (bool) $post_type->show_ui,
);
}
if ( rest_is_field_included( 'viewable', $fields ) ) {
$data['viewable'] = is_post_type_viewable( $post_type );
}
if ( rest_is_field_included( 'labels', $fields ) ) {
$data['labels'] = $post_type->labels;
}
if ( rest_is_field_included( 'name', $fields ) ) {
$data['name'] = $post_type->label;
}
if ( rest_is_field_included( 'slug', $fields ) ) {
$data['slug'] = $post_type->name;
}
if ( rest_is_field_included( 'icon', $fields ) ) {
$data['icon'] = $post_type->menu_icon;
}
if ( rest_is_field_included( 'supports', $fields ) ) {
$data['supports'] = $supports;
}
if ( rest_is_field_included( 'taxonomies', $fields ) ) {
$data['taxonomies'] = array_values( $taxonomies );
}
if ( rest_is_field_included( 'rest_base', $fields ) ) {
$data['rest_base'] = $base;
}
if ( rest_is_field_included( 'rest_namespace', $fields ) ) {
$data['rest_namespace'] = $namespace;
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
// Wrap the data in a response object.
$response = rest_ensure_response( $data );
if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
$response->add_links( $this->prepare_links( $post_type ) );
}
/**
* Filters a post type returned from the REST API.
*
* Allows modification of the post type data right before it is returned.
*
* @since 4.7.0
*
* @param WP_REST_Response $response The response object.
* @param WP_Post_Type $post_type The original post type object.
* @param WP_REST_Request $request Request used to generate the response.
*/
return apply_filters( 'rest_prepare_post_type', $response, $post_type, $request );
}
```
[apply\_filters( 'rest\_prepare\_post\_type', WP\_REST\_Response $response, WP\_Post\_Type $post\_type, WP\_REST\_Request $request )](../../hooks/rest_prepare_post_type)
Filters a post type returned from the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Post\_Types\_Controller::prepare\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php | Prepares links for the request. |
| [rest\_is\_field\_included()](../../functions/rest_is_field_included) wp-includes/rest-api.php | Given an array of fields to include in a response, some of which may be `nested.fields`, determine whether the provided field should be included in the response body. |
| [is\_post\_type\_viewable()](../../functions/is_post_type_viewable) wp-includes/post.php | Determines whether a post type is considered “viewable”. |
| [wp\_list\_filter()](../../functions/wp_list_filter) wp-includes/functions.php | Filters a list of objects, based on a set of key => value arguments. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [get\_object\_taxonomies()](../../functions/get_object_taxonomies) wp-includes/taxonomy.php | Returns the names or objects of the taxonomies which are registered for the requested object or object type, such as a post object or post type name. |
| [get\_all\_post\_type\_supports()](../../functions/get_all_post_type_supports) wp-includes/post.php | Gets all the post type features |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Post\_Types\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php | Retrieves all public post types. |
| [WP\_REST\_Post\_Types\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php | Retrieves a specific post type. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$post_type` to `$item` to match parent class for PHP 8 named parameter support. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Post_Types_Controller::prepare_links( WP_Post_Type $post_type ): array WP\_REST\_Post\_Types\_Controller::prepare\_links( WP\_Post\_Type $post\_type ): array
======================================================================================
Prepares links for the request.
`$post_type` [WP\_Post\_Type](../wp_post_type) Required The post type. array Links for the given post type.
File: `wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php/)
```
protected function prepare_links( $post_type ) {
return array(
'collection' => array(
'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
),
'https://api.w.org/items' => array(
'href' => rest_url( rest_get_route_for_post_type_items( $post_type->name ) ),
),
);
}
```
| Uses | Description |
| --- | --- |
| [rest\_get\_route\_for\_post\_type\_items()](../../functions/rest_get_route_for_post_type_items) wp-includes/rest-api.php | Gets the REST API route for a post type. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Post\_Types\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php | Prepares a post type object for serialization. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_REST_Post_Types_Controller::get_items( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Post\_Types\_Controller::get\_items( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=========================================================================================================
Retrieves all public post types.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php/)
```
public function get_items( $request ) {
$data = array();
$types = get_post_types( array( 'show_in_rest' => true ), 'objects' );
foreach ( $types as $type ) {
if ( 'edit' === $request['context'] && ! current_user_can( $type->cap->edit_posts ) ) {
continue;
}
$post_type = $this->prepare_item_for_response( $type, $request );
$data[ $type->name ] = $this->prepare_response_for_collection( $post_type );
}
return rest_ensure_response( $data );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Post\_Types\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php | Prepares a post type object for serialization. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Post_Types_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Post\_Types\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
===============================================================================================================
Checks whether a given request has permission to read types.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php/)
```
public function get_items_permissions_check( $request ) {
if ( 'edit' === $request['context'] ) {
$types = get_post_types( array( 'show_in_rest' => true ), 'objects' );
foreach ( $types as $type ) {
if ( current_user_can( $type->cap->edit_posts ) ) {
return true;
}
}
return new WP_Error(
'rest_cannot_view',
__( 'Sorry, you are not allowed to edit posts in this post type.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Post_Types_Controller::register_routes() WP\_REST\_Post\_Types\_Controller::register\_routes()
=====================================================
Registers the routes for post types.
* [register\_rest\_route()](../../functions/register_rest_route)
File: `wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php/)
```
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base,
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => $this->get_collection_params(),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/(?P<type>[\w-]+)',
array(
'args' => array(
'type' => array(
'description' => __( 'An alphanumeric identifier for the post type.' ),
'type' => 'string',
),
),
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => '__return_true',
'args' => array(
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Post\_Types\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php | Retrieves the query params for collections. |
| [register\_rest\_route()](../../functions/register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Post_Types_Controller::get_collection_params(): array WP\_REST\_Post\_Types\_Controller::get\_collection\_params(): array
===================================================================
Retrieves the query params for collections.
array Collection parameters.
File: `wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php/)
```
public function get_collection_params() {
return array(
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
);
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Post\_Types\_Controller::register\_routes()](register_routes) wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php | Registers the routes for post types. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Post_Types_Controller::__construct() WP\_REST\_Post\_Types\_Controller::\_\_construct()
==================================================
Constructor.
File: `wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php/)
```
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'types';
}
```
| Used By | Description |
| --- | --- |
| [create\_initial\_rest\_routes()](../../functions/create_initial_rest_routes) wp-includes/rest-api.php | Registers default REST API routes. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Post_Types_Controller::get_item_schema(): array WP\_REST\_Post\_Types\_Controller::get\_item\_schema(): array
=============================================================
Retrieves the post type’s schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php/)
```
public function get_item_schema() {
if ( $this->schema ) {
return $this->add_additional_fields_schema( $this->schema );
}
$schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'type',
'type' => 'object',
'properties' => array(
'capabilities' => array(
'description' => __( 'All capabilities used by the post type.' ),
'type' => 'object',
'context' => array( 'edit' ),
'readonly' => true,
),
'description' => array(
'description' => __( 'A human-readable description of the post type.' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'hierarchical' => array(
'description' => __( 'Whether or not the post type should have children.' ),
'type' => 'boolean',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'viewable' => array(
'description' => __( 'Whether or not the post type can be viewed.' ),
'type' => 'boolean',
'context' => array( 'edit' ),
'readonly' => true,
),
'labels' => array(
'description' => __( 'Human-readable labels for the post type for various contexts.' ),
'type' => 'object',
'context' => array( 'edit' ),
'readonly' => true,
),
'name' => array(
'description' => __( 'The title for the post type.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
),
'slug' => array(
'description' => __( 'An alphanumeric identifier for the post type.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
),
'supports' => array(
'description' => __( 'All features, supported by the post type.' ),
'type' => 'object',
'context' => array( 'edit' ),
'readonly' => true,
),
'has_archive' => array(
'description' => __( 'If the value is a string, the value will be used as the archive slug. If the value is false the post type has no archive.' ),
'type' => array( 'string', 'boolean' ),
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'taxonomies' => array(
'description' => __( 'Taxonomies associated with post type.' ),
'type' => 'array',
'items' => array(
'type' => 'string',
),
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'rest_base' => array(
'description' => __( 'REST base route for the post type.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
),
'rest_namespace' => array(
'description' => __( 'REST route\'s namespace for the post type.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
),
'visibility' => array(
'description' => __( 'The visibility settings for the post type.' ),
'type' => 'object',
'context' => array( 'edit' ),
'readonly' => true,
'properties' => array(
'show_ui' => array(
'description' => __( 'Whether to generate a default UI for managing this post type.' ),
'type' => 'boolean',
),
'show_in_nav_menus' => array(
'description' => __( 'Whether to make the post type available for selection in navigation menus.' ),
'type' => 'boolean',
),
),
),
'icon' => array(
'description' => __( 'The icon for the post type.' ),
'type' => array( 'string', 'null' ),
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
),
),
);
$this->schema = $schema;
return $this->add_additional_fields_schema( $this->schema );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | The `icon` property was added. |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | The `visibility` and `rest_namespace` properties were added. |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | The `supports` property was added. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Object_Cache::reset() WP\_Object\_Cache::reset()
==========================
This method has been deprecated. Use [switch\_to\_blog()](../../functions/switch_to_blog) instead.
Resets cache keys.
* [switch\_to\_blog()](../../functions/switch_to_blog)
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function reset() {
_deprecated_function( __FUNCTION__, '3.5.0', 'WP_Object_Cache::switch_to_blog()' );
// Clear out non-global caches since the blog ID has changed.
foreach ( array_keys( $this->cache ) as $group ) {
if ( ! isset( $this->global_groups[ $group ] ) ) {
unset( $this->cache[ $group ] );
}
}
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Used By | Description |
| --- | --- |
| [wp\_cache\_reset()](../../functions/wp_cache_reset) wp-includes/cache.php | Resets internal cache keys and structures. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Use [WP\_Object\_Cache::switch\_to\_blog()](switch_to_blog) |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress WP_Object_Cache::_exists( int|string $key, string $group ): bool WP\_Object\_Cache::\_exists( int|string $key, string $group ): bool
===================================================================
Serves as a utility function to determine whether a key exists in the cache.
`$key` int|string Required Cache key to check for existence. `$group` string Required Cache group for the key existence check. bool Whether the key exists in the cache for the given group.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
protected function _exists( $key, $group ) {
return isset( $this->cache[ $group ] ) && ( isset( $this->cache[ $group ][ $key ] ) || array_key_exists( $key, $this->cache[ $group ] ) );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Object\_Cache::replace()](replace) wp-includes/class-wp-object-cache.php | Replaces the contents in the cache, if contents already exist. |
| [WP\_Object\_Cache::get()](get) wp-includes/class-wp-object-cache.php | Retrieves the cache contents, if it exists. |
| [WP\_Object\_Cache::delete()](delete) wp-includes/class-wp-object-cache.php | Removes the contents of the cache key in the group. |
| [WP\_Object\_Cache::incr()](incr) wp-includes/class-wp-object-cache.php | Increments numeric cache item’s value. |
| [WP\_Object\_Cache::decr()](decr) wp-includes/class-wp-object-cache.php | Decrements numeric cache item’s value. |
| [WP\_Object\_Cache::add()](add) wp-includes/class-wp-object-cache.php | Adds data to the cache if it doesn’t already exist. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Object_Cache::stats() WP\_Object\_Cache::stats()
==========================
Echoes the stats of the caching.
Gives the cache hits, and cache misses. Also prints every cached group, key and the data.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function stats() {
echo '<p>';
echo "<strong>Cache Hits:</strong> {$this->cache_hits}<br />";
echo "<strong>Cache Misses:</strong> {$this->cache_misses}<br />";
echo '</p>';
echo '<ul>';
foreach ( $this->cache as $group => $cache ) {
echo '<li><strong>Group:</strong> ' . esc_html( $group ) . ' - ( ' . number_format( strlen( serialize( $cache ) ) / KB_IN_BYTES, 2 ) . 'k )</li>';
}
echo '</ul>';
}
```
| Uses | Description |
| --- | --- |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_Object_Cache::__unset( string $name ) WP\_Object\_Cache::\_\_unset( string $name )
============================================
Makes private properties un-settable for backward compatibility.
`$name` string Required Property to unset. File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function __unset( $name ) {
unset( $this->$name );
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Object_Cache::is_valid_key( int|string $key ): bool WP\_Object\_Cache::is\_valid\_key( int|string $key ): bool
==========================================================
Serves as a utility function to determine whether a key is valid.
`$key` int|string Required Cache key to check for validity. bool Whether the key is valid.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
protected function is_valid_key( $key ) {
if ( is_int( $key ) ) {
return true;
}
if ( is_string( $key ) && trim( $key ) !== '' ) {
return true;
}
$type = gettype( $key );
if ( ! function_exists( '__' ) ) {
wp_load_translations_early();
}
$message = is_string( $key )
? __( 'Cache key must not be an empty string.' )
/* translators: %s: The type of the given cache key. */
: sprintf( __( 'Cache key must be integer or non-empty string, %s given.' ), $type );
_doing_it_wrong(
sprintf( '%s::%s', __CLASS__, debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 )[1]['function'] ),
$message,
'6.1.0'
);
return false;
}
```
| Uses | Description |
| --- | --- |
| [wp\_load\_translations\_early()](../../functions/wp_load_translations_early) wp-includes/load.php | Attempt an early load of translations. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](../../functions/_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Used By | Description |
| --- | --- |
| [WP\_Object\_Cache::replace()](replace) wp-includes/class-wp-object-cache.php | Replaces the contents in the cache, if contents already exist. |
| [WP\_Object\_Cache::set()](set) wp-includes/class-wp-object-cache.php | Sets the data contents into the cache. |
| [WP\_Object\_Cache::get()](get) wp-includes/class-wp-object-cache.php | Retrieves the cache contents, if it exists. |
| [WP\_Object\_Cache::delete()](delete) wp-includes/class-wp-object-cache.php | Removes the contents of the cache key in the group. |
| [WP\_Object\_Cache::incr()](incr) wp-includes/class-wp-object-cache.php | Increments numeric cache item’s value. |
| [WP\_Object\_Cache::decr()](decr) wp-includes/class-wp-object-cache.php | Decrements numeric cache item’s value. |
| [WP\_Object\_Cache::add()](add) wp-includes/class-wp-object-cache.php | Adds data to the cache if it doesn’t already exist. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Object_Cache::add_multiple( array $data, string $group = '', int $expire ): bool[] WP\_Object\_Cache::add\_multiple( array $data, string $group = '', int $expire ): bool[]
========================================================================================
Adds multiple values to the cache in one call.
`$data` array Required Array of keys and values to be added. `$group` string Optional Where the cache contents are grouped. Default: `''`
`$expire` int Optional When to expire the cache contents, in seconds.
Default 0 (no expiration). bool[] Array of return values, grouped by key. Each value is either true on success, or false if cache key and group already exist.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function add_multiple( array $data, $group = '', $expire = 0 ) {
$values = array();
foreach ( $data as $key => $value ) {
$values[ $key ] = $this->add( $key, $value, $group, $expire );
}
return $values;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Object\_Cache::add()](add) wp-includes/class-wp-object-cache.php | Adds data to the cache if it doesn’t already exist. |
| Used By | Description |
| --- | --- |
| [wp\_cache\_add\_multiple()](../../functions/wp_cache_add_multiple) wp-includes/cache.php | Adds multiple values to the cache in one call. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_Object_Cache::add( int|string $key, mixed $data, string $group = 'default', int $expire ): bool WP\_Object\_Cache::add( int|string $key, mixed $data, string $group = 'default', int $expire ): bool
====================================================================================================
Adds data to the cache if it doesn’t already exist.
`$key` int|string Required What to call the contents in the cache. `$data` mixed Required The contents to store in the cache. `$group` string Optional Where to group the cache contents. Default `'default'`. Default: `'default'`
`$expire` int Optional When to expire the cache contents, in seconds.
Default 0 (no expiration). bool True on success, false if cache key and group already exist.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function add( $key, $data, $group = 'default', $expire = 0 ) {
if ( wp_suspend_cache_addition() ) {
return false;
}
if ( ! $this->is_valid_key( $key ) ) {
return false;
}
if ( empty( $group ) ) {
$group = 'default';
}
$id = $key;
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$id = $this->blog_prefix . $key;
}
if ( $this->_exists( $id, $group ) ) {
return false;
}
return $this->set( $key, $data, $group, (int) $expire );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Object\_Cache::is\_valid\_key()](is_valid_key) wp-includes/class-wp-object-cache.php | Serves as a utility function to determine whether a key is valid. |
| [WP\_Object\_Cache::\_exists()](_exists) wp-includes/class-wp-object-cache.php | Serves as a utility function to determine whether a key exists in the cache. |
| [WP\_Object\_Cache::set()](set) wp-includes/class-wp-object-cache.php | Sets the data contents into the cache. |
| [wp\_suspend\_cache\_addition()](../../functions/wp_suspend_cache_addition) wp-includes/functions.php | Temporarily suspends cache additions. |
| Used By | Description |
| --- | --- |
| [WP\_Object\_Cache::add\_multiple()](add_multiple) wp-includes/class-wp-object-cache.php | Adds multiple values to the cache in one call. |
| [wp\_cache\_add()](../../functions/wp_cache_add) wp-includes/cache.php | Adds data to the cache, if the cache key doesn’t already exist. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_Object_Cache::add_global_groups( string|string[] $groups ) WP\_Object\_Cache::add\_global\_groups( string|string[] $groups )
=================================================================
Sets the list of global cache groups.
`$groups` string|string[] Required List of groups that are global. File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function add_global_groups( $groups ) {
$groups = (array) $groups;
$groups = array_fill_keys( $groups, true );
$this->global_groups = array_merge( $this->global_groups, $groups );
}
```
| Used By | Description |
| --- | --- |
| [wp\_cache\_add\_global\_groups()](../../functions/wp_cache_add_global_groups) wp-includes/cache.php | Adds a group or set of groups to the list of global groups. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress WP_Object_Cache::replace( int|string $key, mixed $data, string $group = 'default', int $expire ): bool WP\_Object\_Cache::replace( int|string $key, mixed $data, string $group = 'default', int $expire ): bool
========================================================================================================
Replaces the contents in the cache, if contents already exist.
* [WP\_Object\_Cache::set()](../wp_object_cache/set)
`$key` int|string Required What to call the contents in the cache. `$data` mixed Required The contents to store in the cache. `$group` string Optional Where to group the cache contents. Default `'default'`. Default: `'default'`
`$expire` int Optional When to expire the cache contents, in seconds.
Default 0 (no expiration). bool True if contents were replaced, false if original value does not exist.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function replace( $key, $data, $group = 'default', $expire = 0 ) {
if ( ! $this->is_valid_key( $key ) ) {
return false;
}
if ( empty( $group ) ) {
$group = 'default';
}
$id = $key;
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$id = $this->blog_prefix . $key;
}
if ( ! $this->_exists( $id, $group ) ) {
return false;
}
return $this->set( $key, $data, $group, (int) $expire );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Object\_Cache::is\_valid\_key()](is_valid_key) wp-includes/class-wp-object-cache.php | Serves as a utility function to determine whether a key is valid. |
| [WP\_Object\_Cache::\_exists()](_exists) wp-includes/class-wp-object-cache.php | Serves as a utility function to determine whether a key exists in the cache. |
| [WP\_Object\_Cache::set()](set) wp-includes/class-wp-object-cache.php | Sets the data contents into the cache. |
| Used By | Description |
| --- | --- |
| [wp\_cache\_replace()](../../functions/wp_cache_replace) wp-includes/cache.php | Replaces the contents of the cache with new data. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
| programming_docs |
wordpress WP_Object_Cache::__set( string $name, mixed $value ): mixed WP\_Object\_Cache::\_\_set( string $name, mixed $value ): mixed
===============================================================
Makes private properties settable for backward compatibility.
`$name` string Required Property to set. `$value` mixed Required Property value. mixed Newly-set property.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function __set( $name, $value ) {
return $this->$name = $value;
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Object_Cache::delete_multiple( array $keys, string $group = '' ): bool[] WP\_Object\_Cache::delete\_multiple( array $keys, string $group = '' ): bool[]
==============================================================================
Deletes multiple values from the cache in one call.
`$keys` array Required Array of keys to be deleted. `$group` string Optional Where the cache contents are grouped. Default: `''`
bool[] Array of return values, grouped by key. Each value is either true on success, or false if the contents were not deleted.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function delete_multiple( array $keys, $group = '' ) {
$values = array();
foreach ( $keys as $key ) {
$values[ $key ] = $this->delete( $key, $group );
}
return $values;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Object\_Cache::delete()](delete) wp-includes/class-wp-object-cache.php | Removes the contents of the cache key in the group. |
| Used By | Description |
| --- | --- |
| [wp\_cache\_delete\_multiple()](../../functions/wp_cache_delete_multiple) wp-includes/cache.php | Deletes multiple values from the cache in one call. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_Object_Cache::switch_to_blog( int $blog_id ) WP\_Object\_Cache::switch\_to\_blog( int $blog\_id )
====================================================
Switches the internal blog ID.
This changes the blog ID used to create keys in blog specific groups.
`$blog_id` int Required Blog ID. File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function switch_to_blog( $blog_id ) {
$blog_id = (int) $blog_id;
$this->blog_prefix = $this->multisite ? $blog_id . ':' : '';
}
```
| Used By | Description |
| --- | --- |
| [wp\_cache\_switch\_to\_blog()](../../functions/wp_cache_switch_to_blog) wp-includes/cache.php | Switches the internal blog ID. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Object_Cache::__get( string $name ): mixed WP\_Object\_Cache::\_\_get( string $name ): mixed
=================================================
Makes private properties readable for backward compatibility.
`$name` string Required Property to get. mixed Property.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function __get( $name ) {
return $this->$name;
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Object_Cache::flush(): true WP\_Object\_Cache::flush(): true
================================
Clears the object cache of all data.
true Always returns true.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function flush() {
$this->cache = array();
return true;
}
```
| Used By | Description |
| --- | --- |
| [wp\_cache\_flush()](../../functions/wp_cache_flush) wp-includes/cache.php | Removes all cache items. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_Object_Cache::__isset( string $name ): bool WP\_Object\_Cache::\_\_isset( string $name ): bool
==================================================
Makes private properties checkable for backward compatibility.
`$name` string Required Property to check if set. bool Whether the property is set.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function __isset( $name ) {
return isset( $this->$name );
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Object_Cache::incr( int|string $key, int $offset = 1, string $group = 'default' ): int|false WP\_Object\_Cache::incr( int|string $key, int $offset = 1, string $group = 'default' ): int|false
=================================================================================================
Increments numeric cache item’s value.
`$key` int|string Required The cache key to increment. `$offset` int Optional The amount by which to increment the item's value.
Default: `1`
`$group` string Optional The group the key is in. Default `'default'`. Default: `'default'`
int|false The item's new value on success, false on failure.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function incr( $key, $offset = 1, $group = 'default' ) {
if ( ! $this->is_valid_key( $key ) ) {
return false;
}
if ( empty( $group ) ) {
$group = 'default';
}
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$key = $this->blog_prefix . $key;
}
if ( ! $this->_exists( $key, $group ) ) {
return false;
}
if ( ! is_numeric( $this->cache[ $group ][ $key ] ) ) {
$this->cache[ $group ][ $key ] = 0;
}
$offset = (int) $offset;
$this->cache[ $group ][ $key ] += $offset;
if ( $this->cache[ $group ][ $key ] < 0 ) {
$this->cache[ $group ][ $key ] = 0;
}
return $this->cache[ $group ][ $key ];
}
```
| Uses | Description |
| --- | --- |
| [WP\_Object\_Cache::is\_valid\_key()](is_valid_key) wp-includes/class-wp-object-cache.php | Serves as a utility function to determine whether a key is valid. |
| [WP\_Object\_Cache::\_exists()](_exists) wp-includes/class-wp-object-cache.php | Serves as a utility function to determine whether a key exists in the cache. |
| Used By | Description |
| --- | --- |
| [wp\_cache\_incr()](../../functions/wp_cache_incr) wp-includes/cache.php | Increments numeric cache item’s value. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Object_Cache::decr( int|string $key, int $offset = 1, string $group = 'default' ): int|false WP\_Object\_Cache::decr( int|string $key, int $offset = 1, string $group = 'default' ): int|false
=================================================================================================
Decrements numeric cache item’s value.
`$key` int|string Required The cache key to decrement. `$offset` int Optional The amount by which to decrement the item's value.
Default: `1`
`$group` string Optional The group the key is in. Default `'default'`. Default: `'default'`
int|false The item's new value on success, false on failure.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function decr( $key, $offset = 1, $group = 'default' ) {
if ( ! $this->is_valid_key( $key ) ) {
return false;
}
if ( empty( $group ) ) {
$group = 'default';
}
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$key = $this->blog_prefix . $key;
}
if ( ! $this->_exists( $key, $group ) ) {
return false;
}
if ( ! is_numeric( $this->cache[ $group ][ $key ] ) ) {
$this->cache[ $group ][ $key ] = 0;
}
$offset = (int) $offset;
$this->cache[ $group ][ $key ] -= $offset;
if ( $this->cache[ $group ][ $key ] < 0 ) {
$this->cache[ $group ][ $key ] = 0;
}
return $this->cache[ $group ][ $key ];
}
```
| Uses | Description |
| --- | --- |
| [WP\_Object\_Cache::is\_valid\_key()](is_valid_key) wp-includes/class-wp-object-cache.php | Serves as a utility function to determine whether a key is valid. |
| [WP\_Object\_Cache::\_exists()](_exists) wp-includes/class-wp-object-cache.php | Serves as a utility function to determine whether a key exists in the cache. |
| Used By | Description |
| --- | --- |
| [wp\_cache\_decr()](../../functions/wp_cache_decr) wp-includes/cache.php | Decrements numeric cache item’s value. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Object_Cache::set_multiple( array $data, string $group = '', int $expire ): bool[] WP\_Object\_Cache::set\_multiple( array $data, string $group = '', int $expire ): bool[]
========================================================================================
Sets multiple values to the cache in one call.
`$data` array Required Array of key and value to be set. `$group` string Optional Where the cache contents are grouped. Default: `''`
`$expire` int Optional When to expire the cache contents, in seconds.
Default 0 (no expiration). bool[] Array of return values, grouped by key. Each value is always true.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function set_multiple( array $data, $group = '', $expire = 0 ) {
$values = array();
foreach ( $data as $key => $value ) {
$values[ $key ] = $this->set( $key, $value, $group, $expire );
}
return $values;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Object\_Cache::set()](set) wp-includes/class-wp-object-cache.php | Sets the data contents into the cache. |
| Used By | Description |
| --- | --- |
| [wp\_cache\_set\_multiple()](../../functions/wp_cache_set_multiple) wp-includes/cache.php | Sets multiple values to the cache in one call. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_Object_Cache::__construct() WP\_Object\_Cache::\_\_construct()
==================================
Sets up object properties; PHP 5 style constructor.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function __construct() {
$this->multisite = is_multisite();
$this->blog_prefix = $this->multisite ? get_current_blog_id() . ':' : '';
}
```
| Uses | Description |
| --- | --- |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [get\_current\_blog\_id()](../../functions/get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| Used By | Description |
| --- | --- |
| [wp\_cache\_init()](../../functions/wp_cache_init) wp-includes/cache.php | Sets up Object Cache Global and assigns it. |
| Version | Description |
| --- | --- |
| [2.0.8](https://developer.wordpress.org/reference/since/2.0.8/) | Introduced. |
wordpress WP_Object_Cache::get_multiple( array $keys, string $group = 'default', bool $force = false ): array WP\_Object\_Cache::get\_multiple( array $keys, string $group = 'default', bool $force = false ): array
======================================================================================================
Retrieves multiple values from the cache in one call.
`$keys` array Required Array of keys under which the cache contents are stored. `$group` string Optional Where the cache contents are grouped. Default `'default'`. Default: `'default'`
`$force` bool Optional Whether to force an update of the local cache from the persistent cache. Default: `false`
array Array of return values, grouped by key. Each value is either the cache contents on success, or false on failure.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function get_multiple( $keys, $group = 'default', $force = false ) {
$values = array();
foreach ( $keys as $key ) {
$values[ $key ] = $this->get( $key, $group, $force );
}
return $values;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Object\_Cache::get()](get) wp-includes/class-wp-object-cache.php | Retrieves the cache contents, if it exists. |
| Used By | Description |
| --- | --- |
| [wp\_cache\_get\_multiple()](../../functions/wp_cache_get_multiple) wp-includes/cache.php | Retrieves multiple values from the cache in one call. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Object_Cache::set( int|string $key, mixed $data, string $group = 'default', int $expire ): bool WP\_Object\_Cache::set( int|string $key, mixed $data, string $group = 'default', int $expire ): bool
====================================================================================================
Sets the data contents into the cache.
The cache contents are grouped by the $group parameter followed by the $key. This allows for duplicate IDs in unique groups. Therefore, naming of the group should be used with care and should follow normal function naming guidelines outside of core WordPress usage.
The $expire parameter is not used, because the cache will automatically expire for each time a page is accessed and PHP finishes. The method is more for cache plugins which use files.
`$key` int|string Required What to call the contents in the cache. `$data` mixed Required The contents to store in the cache. `$group` string Optional Where to group the cache contents. Default `'default'`. Default: `'default'`
`$expire` int Optional Not used. bool True if contents were set, false if key is invalid.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function set( $key, $data, $group = 'default', $expire = 0 ) {
if ( ! $this->is_valid_key( $key ) ) {
return false;
}
if ( empty( $group ) ) {
$group = 'default';
}
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$key = $this->blog_prefix . $key;
}
if ( is_object( $data ) ) {
$data = clone $data;
}
$this->cache[ $group ][ $key ] = $data;
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Object\_Cache::is\_valid\_key()](is_valid_key) wp-includes/class-wp-object-cache.php | Serves as a utility function to determine whether a key is valid. |
| Used By | Description |
| --- | --- |
| [WP\_Object\_Cache::set\_multiple()](set_multiple) wp-includes/class-wp-object-cache.php | Sets multiple values to the cache in one call. |
| [WP\_Object\_Cache::replace()](replace) wp-includes/class-wp-object-cache.php | Replaces the contents in the cache, if contents already exist. |
| [WP\_Object\_Cache::add()](add) wp-includes/class-wp-object-cache.php | Adds data to the cache if it doesn’t already exist. |
| [wp\_cache\_set()](../../functions/wp_cache_set) wp-includes/cache.php | Saves the data to the cache. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Returns false if cache key is invalid. |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_Object_Cache::delete( int|string $key, string $group = 'default', bool $deprecated = false ): bool WP\_Object\_Cache::delete( int|string $key, string $group = 'default', bool $deprecated = false ): bool
=======================================================================================================
Removes the contents of the cache key in the group.
If the cache key does not exist in the group, then nothing will happen.
`$key` int|string Required What the contents in the cache are called. `$group` string Optional Where the cache contents are grouped. Default `'default'`. Default: `'default'`
`$deprecated` bool Optional Unused. Default: `false`
bool True on success, false if the contents were not deleted.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function delete( $key, $group = 'default', $deprecated = false ) {
if ( ! $this->is_valid_key( $key ) ) {
return false;
}
if ( empty( $group ) ) {
$group = 'default';
}
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$key = $this->blog_prefix . $key;
}
if ( ! $this->_exists( $key, $group ) ) {
return false;
}
unset( $this->cache[ $group ][ $key ] );
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Object\_Cache::is\_valid\_key()](is_valid_key) wp-includes/class-wp-object-cache.php | Serves as a utility function to determine whether a key is valid. |
| [WP\_Object\_Cache::\_exists()](_exists) wp-includes/class-wp-object-cache.php | Serves as a utility function to determine whether a key exists in the cache. |
| Used By | Description |
| --- | --- |
| [WP\_Object\_Cache::delete\_multiple()](delete_multiple) wp-includes/class-wp-object-cache.php | Deletes multiple values from the cache in one call. |
| [wp\_cache\_delete()](../../functions/wp_cache_delete) wp-includes/cache.php | Removes the cache contents matching key and group. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_Object_Cache::get( int|string $key, string $group = 'default', bool $force = false, bool $found = null ): mixed|false WP\_Object\_Cache::get( int|string $key, string $group = 'default', bool $force = false, bool $found = null ): mixed|false
==========================================================================================================================
Retrieves the cache contents, if it exists.
The contents will be first attempted to be retrieved by searching by the key in the cache group. If the cache is hit (success) then the contents are returned.
On failure, the number of cache misses will be incremented.
`$key` int|string Required The key under which the cache contents are stored. `$group` string Optional Where the cache contents are grouped. Default `'default'`. Default: `'default'`
`$force` bool Optional Unused. Whether to force an update of the local cache from the persistent cache. Default: `false`
`$found` bool Optional Whether the key was found in the cache (passed by reference).
Disambiguates a return of false, a storable value. Default: `null`
mixed|false The cache contents on success, false on failure to retrieve contents.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function get( $key, $group = 'default', $force = false, &$found = null ) {
if ( ! $this->is_valid_key( $key ) ) {
return false;
}
if ( empty( $group ) ) {
$group = 'default';
}
if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) {
$key = $this->blog_prefix . $key;
}
if ( $this->_exists( $key, $group ) ) {
$found = true;
$this->cache_hits += 1;
if ( is_object( $this->cache[ $group ][ $key ] ) ) {
return clone $this->cache[ $group ][ $key ];
} else {
return $this->cache[ $group ][ $key ];
}
}
$found = false;
$this->cache_misses += 1;
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Object\_Cache::is\_valid\_key()](is_valid_key) wp-includes/class-wp-object-cache.php | Serves as a utility function to determine whether a key is valid. |
| [WP\_Object\_Cache::\_exists()](_exists) wp-includes/class-wp-object-cache.php | Serves as a utility function to determine whether a key exists in the cache. |
| Used By | Description |
| --- | --- |
| [WP\_Object\_Cache::get\_multiple()](get_multiple) wp-includes/class-wp-object-cache.php | Retrieves multiple values from the cache in one call. |
| [wp\_cache\_get()](../../functions/wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
| programming_docs |
wordpress WP_Object_Cache::flush_group( string $group ): true WP\_Object\_Cache::flush\_group( string $group ): true
======================================================
Removes all cache items in a group.
`$group` string Required Name of group to remove from cache. true Always returns true.
File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/)
```
public function flush_group( $group ) {
unset( $this->cache[ $group ] );
return true;
}
```
| Used By | Description |
| --- | --- |
| [wp\_cache\_flush\_group()](../../functions/wp_cache_flush_group) wp-includes/cache-compat.php | Removes all cache items in a group, if the object cache implementation supports it. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress Requests_Proxy_HTTP::curl_before_send( resource $handle ) Requests\_Proxy\_HTTP::curl\_before\_send( resource $handle )
=============================================================
Set cURL parameters before the data is sent
`$handle` resource Required cURL resource File: `wp-includes/Requests/Proxy/HTTP.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/proxy/http.php/)
```
public function curl_before_send(&$handle) {
curl_setopt($handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt($handle, CURLOPT_PROXY, $this->proxy);
if ($this->use_authentication) {
curl_setopt($handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
curl_setopt($handle, CURLOPT_PROXYUSERPWD, $this->get_auth_string());
}
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Proxy\_HTTP::get\_auth\_string()](get_auth_string) wp-includes/Requests/Proxy/HTTP.php | Get the authentication string (user:pass) |
| Version | Description |
| --- | --- |
| [1.6](https://developer.wordpress.org/reference/since/1.6/) | Introduced. |
wordpress Requests_Proxy_HTTP::register( Requests_Hooks $hooks ) Requests\_Proxy\_HTTP::register( Requests\_Hooks $hooks )
=========================================================
Register the necessary callbacks
* [curl\_before\_send](../../functions/curl_before_send)
* [fsockopen\_remote\_socket](../../functions/fsockopen_remote_socket)
* [fsockopen\_remote\_host\_path](../../functions/fsockopen_remote_host_path)
* [fsockopen\_header](../../functions/fsockopen_header)
`$hooks` [Requests\_Hooks](../requests_hooks) Required Hook system File: `wp-includes/Requests/Proxy/HTTP.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/proxy/http.php/)
```
public function register(Requests_Hooks $hooks) {
$hooks->register('curl.before_send', array($this, 'curl_before_send'));
$hooks->register('fsockopen.remote_socket', array($this, 'fsockopen_remote_socket'));
$hooks->register('fsockopen.remote_host_path', array($this, 'fsockopen_remote_host_path'));
if ($this->use_authentication) {
$hooks->register('fsockopen.after_headers', array($this, 'fsockopen_header'));
}
}
```
| Version | Description |
| --- | --- |
| [1.6](https://developer.wordpress.org/reference/since/1.6/) | Introduced. |
wordpress Requests_Proxy_HTTP::fsockopen_remote_host_path( string $path, string $url ) Requests\_Proxy\_HTTP::fsockopen\_remote\_host\_path( string $path, string $url )
=================================================================================
Alter remote path before getting stream data
`$path` string Required Path to send in HTTP request string ("GET ...") `$url` string Required Full URL we're requesting File: `wp-includes/Requests/Proxy/HTTP.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/proxy/http.php/)
```
public function fsockopen_remote_host_path(&$path, $url) {
$path = $url;
}
```
| Version | Description |
| --- | --- |
| [1.6](https://developer.wordpress.org/reference/since/1.6/) | Introduced. |
wordpress Requests_Proxy_HTTP::fsockopen_remote_socket( string $remote_socket ) Requests\_Proxy\_HTTP::fsockopen\_remote\_socket( string $remote\_socket )
==========================================================================
Alter remote socket information before opening socket connection
`$remote_socket` string Required Socket connection string File: `wp-includes/Requests/Proxy/HTTP.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/proxy/http.php/)
```
public function fsockopen_remote_socket(&$remote_socket) {
$remote_socket = $this->proxy;
}
```
| Version | Description |
| --- | --- |
| [1.6](https://developer.wordpress.org/reference/since/1.6/) | Introduced. |
wordpress Requests_Proxy_HTTP::get_auth_string(): string Requests\_Proxy\_HTTP::get\_auth\_string(): string
==================================================
Get the authentication string (user:pass)
string
File: `wp-includes/Requests/Proxy/HTTP.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/proxy/http.php/)
```
public function get_auth_string() {
return $this->user . ':' . $this->pass;
}
```
| Used By | Description |
| --- | --- |
| [Requests\_Proxy\_HTTP::fsockopen\_header()](fsockopen_header) wp-includes/Requests/Proxy/HTTP.php | Add extra headers to the request before sending |
| [Requests\_Proxy\_HTTP::curl\_before\_send()](curl_before_send) wp-includes/Requests/Proxy/HTTP.php | Set cURL parameters before the data is sent |
| Version | Description |
| --- | --- |
| [1.6](https://developer.wordpress.org/reference/since/1.6/) | Introduced. |
wordpress Requests_Proxy_HTTP::fsockopen_header( string $out ) Requests\_Proxy\_HTTP::fsockopen\_header( string $out )
=======================================================
Add extra headers to the request before sending
`$out` string Required HTTP header string File: `wp-includes/Requests/Proxy/HTTP.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/proxy/http.php/)
```
public function fsockopen_header(&$out) {
$out .= sprintf("Proxy-Authorization: Basic %s\r\n", base64_encode($this->get_auth_string()));
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Proxy\_HTTP::get\_auth\_string()](get_auth_string) wp-includes/Requests/Proxy/HTTP.php | Get the authentication string (user:pass) |
| Version | Description |
| --- | --- |
| [1.6](https://developer.wordpress.org/reference/since/1.6/) | Introduced. |
wordpress Requests_Proxy_HTTP::__construct( array|null $args = null ) Requests\_Proxy\_HTTP::\_\_construct( array|null $args = null )
===============================================================
Constructor
`$args` array|null Optional Array of user and password. Must have exactly two elements Default: `null`
File: `wp-includes/Requests/Proxy/HTTP.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/proxy/http.php/)
```
public function __construct($args = null) {
if (is_string($args)) {
$this->proxy = $args;
}
elseif (is_array($args)) {
if (count($args) === 1) {
list($this->proxy) = $args;
}
elseif (count($args) === 3) {
list($this->proxy, $this->user, $this->pass) = $args;
$this->use_authentication = true;
}
else {
throw new Requests_Exception('Invalid number of arguments', 'proxyhttpbadargs');
}
}
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
| Used By | Description |
| --- | --- |
| [Requests::set\_defaults()](../requests/set_defaults) wp-includes/class-requests.php | Set the default values |
| [WP\_Http::request()](../wp_http/request) wp-includes/class-wp-http.php | Send an HTTP request to a URI. |
| Version | Description |
| --- | --- |
| [1.6](https://developer.wordpress.org/reference/since/1.6/) | Introduced. |
wordpress WP_Customize_New_Menu_Section::__construct( WP_Customize_Manager $manager, string $id, array $args = array() ) WP\_Customize\_New\_Menu\_Section::\_\_construct( WP\_Customize\_Manager $manager, string $id, array $args = array() )
======================================================================================================================
This method has been deprecated.
Constructor.
Any supplied $args override class property defaults.
`$manager` [WP\_Customize\_Manager](../wp_customize_manager) Required Customizer bootstrap instance. `$id` string Required A specific ID of the section. `$args` array Optional Section arguments. Default: `array()`
File: `wp-includes/customize/class-wp-customize-new-menu-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-new-menu-section.php/)
```
public function __construct( WP_Customize_Manager $manager, $id, array $args = array() ) {
_deprecated_function( __METHOD__, '4.9.0' );
parent::__construct( $manager, $id, $args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Section::\_\_construct()](../wp_customize_section/__construct) wp-includes/class-wp-customize-section.php | Constructor. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_New_Menu_Section::render() WP\_Customize\_New\_Menu\_Section::render()
===========================================
This method has been deprecated.
Render the section, and the controls that have been added to it.
File: `wp-includes/customize/class-wp-customize-new-menu-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-new-menu-section.php/)
```
protected function render() {
_deprecated_function( __METHOD__, '4.9.0' );
?>
<li id="accordion-section-<?php echo esc_attr( $this->id ); ?>" class="accordion-section-new-menu">
<button type="button" class="button add-new-menu-item add-menu-toggle" aria-expanded="false">
<?php echo esc_html( $this->title ); ?>
</button>
<ul class="new-menu-section-content"></ul>
</li>
<?php
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | This method has been deprecated. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_REST_Edit_Site_Export_Controller::register_routes() WP\_REST\_Edit\_Site\_Export\_Controller::register\_routes()
============================================================
Registers the site export route.
File: `wp-includes/rest-api/endpoints/class-wp-rest-edit-site-export-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-edit-site-export-controller.php/)
```
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base,
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'export' ),
'permission_callback' => array( $this, 'permissions_check' ),
),
)
);
}
```
| Uses | Description |
| --- | --- |
| [register\_rest\_route()](../../functions/register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Edit_Site_Export_Controller::__construct() WP\_REST\_Edit\_Site\_Export\_Controller::\_\_construct()
=========================================================
Constructor.
File: `wp-includes/rest-api/endpoints/class-wp-rest-edit-site-export-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-edit-site-export-controller.php/)
```
public function __construct() {
$this->namespace = 'wp-block-editor/v1';
$this->rest_base = 'export';
}
```
| Used By | Description |
| --- | --- |
| [create\_initial\_rest\_routes()](../../functions/create_initial_rest_routes) wp-includes/rest-api.php | Registers default REST API routes. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Edit_Site_Export_Controller::permissions_check(): WP_Error|true WP\_REST\_Edit\_Site\_Export\_Controller::permissions\_check(): WP\_Error|true
==============================================================================
Checks whether a given request has permission to export.
[WP\_Error](../wp_error)|true True if the request has access, or [WP\_Error](../wp_error) object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-edit-site-export-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-edit-site-export-controller.php/)
```
public function permissions_check() {
if ( current_user_can( 'edit_theme_options' ) ) {
return true;
}
return new WP_Error(
'rest_cannot_export_templates',
__( 'Sorry, you are not allowed to export templates and template parts.' ),
array( 'status' => rest_authorization_required_code() )
);
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Edit_Site_Export_Controller::export(): WP_Error|void WP\_REST\_Edit\_Site\_Export\_Controller::export(): WP\_Error|void
==================================================================
Output a ZIP file with an export of the current templates and template parts from the site editor, and close the connection.
[WP\_Error](../wp_error)|void
File: `wp-includes/rest-api/endpoints/class-wp-rest-edit-site-export-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-edit-site-export-controller.php/)
```
public function export() {
// Generate the export file.
$filename = wp_generate_block_templates_export_file();
if ( is_wp_error( $filename ) ) {
$filename->add_data( array( 'status' => 500 ) );
return $filename;
}
$theme_name = basename( get_stylesheet() );
header( 'Content-Type: application/zip' );
header( 'Content-Disposition: attachment; filename=' . $theme_name . '.zip' );
header( 'Content-Length: ' . filesize( $filename ) );
flush();
readfile( $filename );
unlink( $filename );
exit;
}
```
| Uses | Description |
| --- | --- |
| [wp\_generate\_block\_templates\_export\_file()](../../functions/wp_generate_block_templates_export_file) wp-includes/block-template-utils.php | Creates an export of the current templates and template parts from the site editor at the specified path in a ZIP file. |
| [get\_stylesheet()](../../functions/get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Rewrite::using_permalinks(): bool WP\_Rewrite::using\_permalinks(): bool
======================================
Determines whether permalinks are being used.
This can be either rewrite module or permalink in the HTTP query string.
bool True, if permalinks are enabled.
Returns true if your blog is using any permalink structure (i.e. not the default query URIs ?p=n, ?cat=n).
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function using_permalinks() {
return ! empty( $this->permalink_structure );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Sitemaps\_Provider::get\_sitemap\_url()](../wp_sitemaps_provider/get_sitemap_url) wp-includes/sitemaps/class-wp-sitemaps-provider.php | Gets the URL of a sitemap entry. |
| [WP\_Sitemaps\_Index::get\_index\_url()](../wp_sitemaps_index/get_index_url) wp-includes/sitemaps/class-wp-sitemaps-index.php | Builds the URL for the sitemap index. |
| [WP\_Sitemaps\_Renderer::get\_sitemap\_index\_stylesheet\_url()](../wp_sitemaps_renderer/get_sitemap_index_stylesheet_url) wp-includes/sitemaps/class-wp-sitemaps-renderer.php | Gets the URL for the sitemap index stylesheet. |
| [WP\_Sitemaps\_Renderer::get\_sitemap\_stylesheet\_url()](../wp_sitemaps_renderer/get_sitemap_stylesheet_url) wp-includes/sitemaps/class-wp-sitemaps-renderer.php | Gets the URL for the sitemap stylesheet. |
| [get\_the\_category\_list()](../../functions/get_the_category_list) wp-includes/category-template.php | Retrieves category list for a post in either HTML list or custom format. |
| [paginate\_links()](../../functions/paginate_links) wp-includes/general-template.php | Retrieves paginated links for archive post pages. |
| [get\_comments\_pagenum\_link()](../../functions/get_comments_pagenum_link) wp-includes/link-template.php | Retrieves the comments page number link. |
| [paginate\_comments\_links()](../../functions/paginate_comments_links) wp-includes/link-template.php | Displays or retrieves pagination links for the comments on the current post. |
| [get\_pagenum\_link()](../../functions/get_pagenum_link) wp-includes/link-template.php | Retrieves the link for a page number. |
| [get\_attachment\_link()](../../functions/get_attachment_link) wp-includes/link-template.php | Retrieves the permalink for an attachment. |
| [WP\_Rewrite::mod\_rewrite\_rules()](mod_rewrite_rules) wp-includes/class-wp-rewrite.php | Retrieves mod\_rewrite-formatted rewrite rules to write to .htaccess. |
| [WP\_Rewrite::iis7\_url\_rewrite\_rules()](iis7_url_rewrite_rules) wp-includes/class-wp-rewrite.php | Retrieves IIS7 URL Rewrite formatted rewrite rules to write to web.config file. |
| [WP\_Rewrite::using\_mod\_rewrite\_permalinks()](using_mod_rewrite_permalinks) wp-includes/class-wp-rewrite.php | Determines whether permalinks are being used and rewrite module is enabled. |
| [redirect\_canonical()](../../functions/redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| [wp\_redirect\_admin\_locations()](../../functions/wp_redirect_admin_locations) wp-includes/canonical.php | Redirects a variety of shorthand URLs to the admin. |
| [get\_comment\_link()](../../functions/get_comment_link) wp-includes/comment-template.php | Retrieves the link to a given comment. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
| programming_docs |
wordpress WP_Rewrite::remove_rewrite_tag( string $tag ) WP\_Rewrite::remove\_rewrite\_tag( string $tag )
================================================
Removes an existing rewrite tag.
* WP\_Rewrite::$rewritecode
* WP\_Rewrite::$rewritereplace
* WP\_Rewrite::$queryreplace
`$tag` string Required Name of the rewrite tag to remove. File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function remove_rewrite_tag( $tag ) {
$position = array_search( $tag, $this->rewritecode, true );
if ( false !== $position && null !== $position ) {
unset( $this->rewritecode[ $position ] );
unset( $this->rewritereplace[ $position ] );
unset( $this->queryreplace[ $position ] );
}
}
```
| Used By | Description |
| --- | --- |
| [remove\_rewrite\_tag()](../../functions/remove_rewrite_tag) wp-includes/rewrite.php | Removes an existing rewrite tag (like %postname%). |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Rewrite::add_external_rule( string $regex, string $query ) WP\_Rewrite::add\_external\_rule( string $regex, string $query )
================================================================
Adds a rewrite rule that doesn’t correspond to index.php.
`$regex` string Required Regular expression to match request against. `$query` string Required The corresponding query vars for this rewrite rule. File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function add_external_rule( $regex, $query ) {
$this->non_wp_rules[ $regex ] = $query;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Rewrite::add\_rule()](add_rule) wp-includes/class-wp-rewrite.php | Adds a rewrite rule that transforms a URL structure to a set of query vars. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Rewrite::mod_rewrite_rules(): string WP\_Rewrite::mod\_rewrite\_rules(): string
==========================================
Retrieves mod\_rewrite-formatted rewrite rules to write to .htaccess.
Does not actually write to the .htaccess file, but creates the rules for the process that will.
Will add the non\_wp\_rules property rules to the .htaccess file before the WordPress rewrite rules one.
string
returns a string (not an array) of all the rules. They are wrapped in an Apache [<IfModule>](http://httpd.apache.org/docs/2.0/mod/core.html#ifmodule) block, to ensure mod\_rewrite is enabled.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function mod_rewrite_rules() {
if ( ! $this->using_permalinks() ) {
return '';
}
$site_root = parse_url( site_url() );
if ( isset( $site_root['path'] ) ) {
$site_root = trailingslashit( $site_root['path'] );
}
$home_root = parse_url( home_url() );
if ( isset( $home_root['path'] ) ) {
$home_root = trailingslashit( $home_root['path'] );
} else {
$home_root = '/';
}
$rules = "<IfModule mod_rewrite.c>\n";
$rules .= "RewriteEngine On\n";
$rules .= "RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\n";
$rules .= "RewriteBase $home_root\n";
// Prevent -f checks on index.php.
$rules .= "RewriteRule ^index\.php$ - [L]\n";
// Add in the rules that don't redirect to WP's index.php (and thus shouldn't be handled by WP at all).
foreach ( (array) $this->non_wp_rules as $match => $query ) {
// Apache 1.3 does not support the reluctant (non-greedy) modifier.
$match = str_replace( '.+?', '.+', $match );
$rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
}
if ( $this->use_verbose_rules ) {
$this->matches = '';
$rewrite = $this->rewrite_rules();
$num_rules = count( $rewrite );
$rules .= "RewriteCond %{REQUEST_FILENAME} -f [OR]\n" .
"RewriteCond %{REQUEST_FILENAME} -d\n" .
"RewriteRule ^.*$ - [S=$num_rules]\n";
foreach ( (array) $rewrite as $match => $query ) {
// Apache 1.3 does not support the reluctant (non-greedy) modifier.
$match = str_replace( '.+?', '.+', $match );
if ( strpos( $query, $this->index ) !== false ) {
$rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
} else {
$rules .= 'RewriteRule ^' . $match . ' ' . $site_root . $query . " [QSA,L]\n";
}
}
} else {
$rules .= "RewriteCond %{REQUEST_FILENAME} !-f\n" .
"RewriteCond %{REQUEST_FILENAME} !-d\n" .
"RewriteRule . {$home_root}{$this->index} [L]\n";
}
$rules .= "</IfModule>\n";
/**
* Filters the list of rewrite rules formatted for output to an .htaccess file.
*
* @since 1.5.0
*
* @param string $rules mod_rewrite Rewrite rules formatted for .htaccess.
*/
$rules = apply_filters( 'mod_rewrite_rules', $rules );
/**
* Filters the list of rewrite rules formatted for output to an .htaccess file.
*
* @since 1.5.0
* @deprecated 1.5.0 Use the {@see 'mod_rewrite_rules'} filter instead.
*
* @param string $rules mod_rewrite Rewrite rules formatted for .htaccess.
*/
return apply_filters_deprecated( 'rewrite_rules', array( $rules ), '1.5.0', 'mod_rewrite_rules' );
}
```
[apply\_filters( 'mod\_rewrite\_rules', string $rules )](../../hooks/mod_rewrite_rules)
Filters the list of rewrite rules formatted for output to an .htaccess file.
[apply\_filters\_deprecated( 'rewrite\_rules', string $rules )](../../hooks/rewrite_rules)
Filters the list of rewrite rules formatted for output to an .htaccess file.
| Uses | Description |
| --- | --- |
| [apply\_filters\_deprecated()](../../functions/apply_filters_deprecated) wp-includes/plugin.php | Fires functions attached to a deprecated filter hook. |
| [site\_url()](../../functions/site_url) wp-includes/link-template.php | Retrieves the URL for the current site where WordPress application files (e.g. wp-blog-header.php or the wp-admin/ folder) are accessible. |
| [WP\_Rewrite::rewrite\_rules()](rewrite_rules) wp-includes/class-wp-rewrite.php | Constructs rewrite matches and queries from permalink structure. |
| [WP\_Rewrite::using\_permalinks()](using_permalinks) wp-includes/class-wp-rewrite.php | Determines whether permalinks are being used. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [save\_mod\_rewrite\_rules()](../../functions/save_mod_rewrite_rules) wp-admin/includes/misc.php | Updates the htaccess file with the current rules if it is writable. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::add_rule( string $regex, string|array $query, string $after = 'bottom' ) WP\_Rewrite::add\_rule( string $regex, string|array $query, string $after = 'bottom' )
======================================================================================
Adds a rewrite rule that transforms a URL structure to a set of query vars.
Any value in the $after parameter that isn’t ‘bottom’ will result in the rule being placed at the top of the rewrite rules.
`$regex` string Required Regular expression to match request against. `$query` string|array Required The corresponding query vars for this rewrite rule. `$after` string Optional Priority of the new rule. Accepts `'top'` or `'bottom'`. Default `'bottom'`. Default: `'bottom'`
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function add_rule( $regex, $query, $after = 'bottom' ) {
if ( is_array( $query ) ) {
$external = false;
$query = add_query_arg( $query, 'index.php' );
} else {
$index = false === strpos( $query, '?' ) ? strlen( $query ) : strpos( $query, '?' );
$front = substr( $query, 0, $index );
$external = $front != $this->index;
}
// "external" = it doesn't correspond to index.php.
if ( $external ) {
$this->add_external_rule( $regex, $query );
} else {
if ( 'bottom' === $after ) {
$this->extra_rules = array_merge( $this->extra_rules, array( $regex => $query ) );
} else {
$this->extra_rules_top = array_merge( $this->extra_rules_top, array( $regex => $query ) );
}
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::add\_external\_rule()](add_external_rule) wp-includes/class-wp-rewrite.php | Adds a rewrite rule that doesn’t correspond to index.php. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| Used By | Description |
| --- | --- |
| [add\_rewrite\_rule()](../../functions/add_rewrite_rule) wp-includes/rewrite.php | Adds a rewrite rule that transforms a URL structure to a set of query vars. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Array support was added to the `$query` parameter. |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Rewrite::using_mod_rewrite_permalinks(): bool WP\_Rewrite::using\_mod\_rewrite\_permalinks(): bool
====================================================
Determines whether permalinks are being used and rewrite module is enabled.
Using permalinks and index.php is not in the URL.
bool Whether permalink links are enabled and index.php is NOT in the URL.
Returns true your blog is using “pretty” permalinks via mod\_rewrite.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function using_mod_rewrite_permalinks() {
return $this->using_permalinks() && ! $this->using_index_permalinks();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::using\_index\_permalinks()](using_index_permalinks) wp-includes/class-wp-rewrite.php | Determines whether permalinks are being used and rewrite module is not enabled. |
| [WP\_Rewrite::using\_permalinks()](using_permalinks) wp-includes/class-wp-rewrite.php | Determines whether permalinks are being used. |
| Used By | Description |
| --- | --- |
| [save\_mod\_rewrite\_rules()](../../functions/save_mod_rewrite_rules) wp-admin/includes/misc.php | Updates the htaccess file with the current rules if it is writable. |
| [iis7\_save\_url\_rewrite\_rules()](../../functions/iis7_save_url_rewrite_rules) wp-admin/includes/misc.php | Updates the IIS web.config file with the current rules if it is writable. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::page_uri_index(): array WP\_Rewrite::page\_uri\_index(): array
======================================
Retrieves all pages and attachments for pages URIs.
The attachments are for those that have pages as parents and will be retrieved.
array Array of page URIs as first element and attachment URIs as second element.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function page_uri_index() {
global $wpdb;
// Get pages in order of hierarchy, i.e. children after parents.
$pages = $wpdb->get_results( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'page' AND post_status != 'auto-draft'" );
$posts = get_page_hierarchy( $pages );
// If we have no pages get out quick.
if ( ! $posts ) {
return array( array(), array() );
}
// Now reverse it, because we need parents after children for rewrite rules to work properly.
$posts = array_reverse( $posts, true );
$page_uris = array();
$page_attachment_uris = array();
foreach ( $posts as $id => $post ) {
// URL => page name.
$uri = get_page_uri( $id );
$attachments = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'attachment' AND post_parent = %d", $id ) );
if ( ! empty( $attachments ) ) {
foreach ( $attachments as $attachment ) {
$attach_uri = get_page_uri( $attachment->ID );
$page_attachment_uris[ $attach_uri ] = $attachment->ID;
}
}
$page_uris[ $uri ] = $id;
}
return array( $page_uris, $page_attachment_uris );
}
```
| Uses | Description |
| --- | --- |
| [get\_page\_hierarchy()](../../functions/get_page_hierarchy) wp-includes/post.php | Orders the pages with children under parents in a flat list. |
| [get\_page\_uri()](../../functions/get_page_uri) wp-includes/post.php | Builds the URI path for a page. |
| [wpdb::get\_results()](../wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Rewrite::init() WP\_Rewrite::init()
===================
Sets up the object’s properties.
The ‘use\_verbose\_page\_rules’ object property will be set to true if the permalink structure begins with one of the following: ‘%postname%’, ‘%category%’, ‘%tag%’, or ‘%author%’.
Set up the object, set $permalink\_structure and $category\_base from the database. Set $root to $index plus ‘/’. Set $front to everything up to the start of the first tag in the permalink structure. Unset all other properties.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function init() {
$this->extra_rules = array();
$this->non_wp_rules = array();
$this->endpoints = array();
$this->permalink_structure = get_option( 'permalink_structure' );
$this->front = substr( $this->permalink_structure, 0, strpos( $this->permalink_structure, '%' ) );
$this->root = '';
if ( $this->using_index_permalinks() ) {
$this->root = $this->index . '/';
}
unset( $this->author_structure );
unset( $this->date_structure );
unset( $this->page_structure );
unset( $this->search_structure );
unset( $this->feed_structure );
unset( $this->comment_feed_structure );
$this->use_trailing_slashes = ( '/' === substr( $this->permalink_structure, -1, 1 ) );
// Enable generic rules for pages if permalink structure doesn't begin with a wildcard.
if ( preg_match( '/^[^%]*%(?:postname|category|tag|author)%/', $this->permalink_structure ) ) {
$this->use_verbose_page_rules = true;
} else {
$this->use_verbose_page_rules = false;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::using\_index\_permalinks()](using_index_permalinks) wp-includes/class-wp-rewrite.php | Determines whether permalinks are being used and rewrite module is not enabled. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [wp\_install\_defaults()](../../functions/wp_install_defaults) wp-admin/includes/upgrade.php | Creates the initial content for a newly-installed site. |
| [WP\_Rewrite::set\_permalink\_structure()](set_permalink_structure) wp-includes/class-wp-rewrite.php | Sets the main permalink structure for the site. |
| [WP\_Rewrite::set\_category\_base()](set_category_base) wp-includes/class-wp-rewrite.php | Sets the category base for the category permalink. |
| [WP\_Rewrite::set\_tag\_base()](set_tag_base) wp-includes/class-wp-rewrite.php | Sets the tag base for the tag permalink. |
| [WP\_Rewrite::\_\_construct()](__construct) wp-includes/class-wp-rewrite.php | Constructor – Calls [init()](../../functions/init) , which runs setup. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::get_tag_permastruct(): string|false WP\_Rewrite::get\_tag\_permastruct(): string|false
==================================================
Retrieves the permalink structure for tags.
If the tag\_base property has no value, then the tag structure will have the front property value, followed by ‘tag’, and finally ‘%tag%’. If it does, then the root property will be used, along with the tag\_base property value.
string|false Tag permalink structure on success, false on failure.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function get_tag_permastruct() {
return $this->get_extra_permastruct( 'post_tag' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::get\_extra\_permastruct()](get_extra_permastruct) wp-includes/class-wp-rewrite.php | Retrieves an extra permalink structure by name. |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress WP_Rewrite::get_comment_feed_permastruct(): string|false WP\_Rewrite::get\_comment\_feed\_permastruct(): string|false
============================================================
Retrieves the comment feed permalink structure.
The permalink structure is root property, comment base property, feed base and finally ‘/%feed%’. Will set the comment\_feed\_structure property and then return it without attempting to set the value again.
string|false Comment feed permalink structure on success, false on failure.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function get_comment_feed_permastruct() {
if ( isset( $this->comment_feed_structure ) ) {
return $this->comment_feed_structure;
}
if ( empty( $this->permalink_structure ) ) {
$this->comment_feed_structure = '';
return false;
}
$this->comment_feed_structure = $this->root . $this->comments_base . '/' . $this->feed_base . '/%feed%';
return $this->comment_feed_structure;
}
```
| Used By | Description |
| --- | --- |
| [get\_feed\_link()](../../functions/get_feed_link) wp-includes/link-template.php | Retrieves the permalink for the feed type. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::get_feed_permastruct(): string|false WP\_Rewrite::get\_feed\_permastruct(): string|false
===================================================
Retrieves the feed permalink structure.
The permalink structure is root property, feed base, and finally ‘/%feed%’. Will set the feed\_structure property and then return it without attempting to set the value again.
string|false Feed permalink structure on success, false on failure.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function get_feed_permastruct() {
if ( isset( $this->feed_structure ) ) {
return $this->feed_structure;
}
if ( empty( $this->permalink_structure ) ) {
$this->feed_structure = '';
return false;
}
$this->feed_structure = $this->root . $this->feed_base . '/%feed%';
return $this->feed_structure;
}
```
| Used By | Description |
| --- | --- |
| [get\_feed\_link()](../../functions/get_feed_link) wp-includes/link-template.php | Retrieves the permalink for the feed type. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
| programming_docs |
wordpress WP_Rewrite::add_permastruct( string $name, string $struct, array $args = array() ) WP\_Rewrite::add\_permastruct( string $name, string $struct, array $args = array() )
====================================================================================
Adds a new permalink structure.
A permalink structure (permastruct) is an abstract definition of a set of rewrite rules; it is an easy way of expressing a set of regular expressions that rewrite to a set of query strings. The new permastruct is added to the WP\_Rewrite::$extra\_permastructs array.
When the rewrite rules are built by [WP\_Rewrite::rewrite\_rules()](rewrite_rules), all of these extra permastructs are passed to [WP\_Rewrite::generate\_rewrite\_rules()](generate_rewrite_rules) which transforms them into the regular expressions that many love to hate.
The `$args` parameter gives you control over how [WP\_Rewrite::generate\_rewrite\_rules()](generate_rewrite_rules) works on the new permastruct.
`$name` string Required Name for permalink structure. `$struct` string Required Permalink structure (e.g. category/%category%) `$args` array Optional Arguments for building rewrite rules based on the permalink structure.
* `with_front`boolWhether the structure should be prepended with `WP_Rewrite::$front`.
Default true.
* `ep_mask`intThe endpoint mask defining which endpoints are added to the structure.
Accepts a mask of:
+ `EP_ALL`
+ `EP_NONE`
+ `EP_ALL_ARCHIVES`
+ `EP_ATTACHMENT`
+ `EP_AUTHORS`
+ `EP_CATEGORIES`
+ `EP_COMMENTS`
+ `EP_DATE`
+ `EP_DAY`
+ `EP_MONTH`
+ `EP_PAGES`
+ `EP_PERMALINK`
+ `EP_ROOT`
+ `EP_SEARCH`
+ `EP_TAGS`
+ `EP_YEAR` Default `EP_NONE`.
* `paged`boolWhether archive pagination rules should be added for the structure.
Default true.
* `feed`boolWhether feed rewrite rules should be added for the structure. Default true.
* `forcomments`boolWhether the feed rules should be a query for a comments feed. Default false.
* `walk_dirs`boolWhether the `'directories'` making up the structure should be walked over and rewrite rules built for each in-turn. Default true.
* `endpoints`boolWhether endpoints should be applied to the generated rules. Default true.
Default: `array()`
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function add_permastruct( $name, $struct, $args = array() ) {
// Back-compat for the old parameters: $with_front and $ep_mask.
if ( ! is_array( $args ) ) {
$args = array( 'with_front' => $args );
}
if ( func_num_args() == 4 ) {
$args['ep_mask'] = func_get_arg( 3 );
}
$defaults = array(
'with_front' => true,
'ep_mask' => EP_NONE,
'paged' => true,
'feed' => true,
'forcomments' => false,
'walk_dirs' => true,
'endpoints' => true,
);
$args = array_intersect_key( $args, $defaults );
$args = wp_parse_args( $args, $defaults );
if ( $args['with_front'] ) {
$struct = $this->front . $struct;
} else {
$struct = $this->root . $struct;
}
$args['struct'] = $struct;
$this->extra_permastructs[ $name ] = $args;
}
```
| Uses | Description |
| --- | --- |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Used By | Description |
| --- | --- |
| [add\_permastruct()](../../functions/add_permastruct) wp-includes/rewrite.php | Adds a permalink structure. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Rewrite::get_date_permastruct(): string|false WP\_Rewrite::get\_date\_permastruct(): string|false
===================================================
Retrieves date permalink structure, with year, month, and day.
The permalink structure for the date, if not set already depends on the permalink structure. It can be one of three formats. The first is year, month, day; the second is day, month, year; and the last format is month, day, year. These are matched against the permalink structure for which one is used. If none matches, then the default will be used, which is year, month, day.
Prevents post ID and date permalinks from overlapping. In the case of post\_id, the date permalink will be prepended with front permalink with ‘date/’ before the actual permalink to form the complete date permalink structure.
string|false Date permalink structure on success, false on failure.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function get_date_permastruct() {
if ( isset( $this->date_structure ) ) {
return $this->date_structure;
}
if ( empty( $this->permalink_structure ) ) {
$this->date_structure = '';
return false;
}
// The date permalink must have year, month, and day separated by slashes.
$endians = array( '%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%' );
$this->date_structure = '';
$date_endian = '';
foreach ( $endians as $endian ) {
if ( false !== strpos( $this->permalink_structure, $endian ) ) {
$date_endian = $endian;
break;
}
}
if ( empty( $date_endian ) ) {
$date_endian = '%year%/%monthnum%/%day%';
}
/*
* Do not allow the date tags and %post_id% to overlap in the permalink
* structure. If they do, move the date tags to $front/date/.
*/
$front = $this->front;
preg_match_all( '/%.+?%/', $this->permalink_structure, $tokens );
$tok_index = 1;
foreach ( (array) $tokens[0] as $token ) {
if ( '%post_id%' === $token && ( $tok_index <= 3 ) ) {
$front = $front . 'date/';
break;
}
$tok_index++;
}
$this->date_structure = $front . $date_endian;
return $this->date_structure;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Rewrite::rewrite\_rules()](rewrite_rules) wp-includes/class-wp-rewrite.php | Constructs rewrite matches and queries from permalink structure. |
| [WP\_Rewrite::get\_year\_permastruct()](get_year_permastruct) wp-includes/class-wp-rewrite.php | Retrieves the year permalink structure without month and day. |
| [WP\_Rewrite::get\_month\_permastruct()](get_month_permastruct) wp-includes/class-wp-rewrite.php | Retrieves the month permalink structure without day and with year. |
| [WP\_Rewrite::get\_day\_permastruct()](get_day_permastruct) wp-includes/class-wp-rewrite.php | Retrieves the day permalink structure with month and year. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::set_tag_base( string $tag_base ) WP\_Rewrite::set\_tag\_base( string $tag\_base )
================================================
Sets the tag base for the tag permalink.
Will update the ‘tag\_base’ option, if there is a difference between the current tag base and the parameter value. Calls [WP\_Rewrite::init()](init) after the option is updated.
`$tag_base` string Required Tag permalink structure base. File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function set_tag_base( $tag_base ) {
if ( get_option( 'tag_base' ) !== $tag_base ) {
update_option( 'tag_base', $tag_base );
$this->init();
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::init()](init) wp-includes/class-wp-rewrite.php | Sets up the object’s properties. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress WP_Rewrite::add_endpoint( string $name, int $places, string|bool $query_var = true ) WP\_Rewrite::add\_endpoint( string $name, int $places, string|bool $query\_var = true )
=======================================================================================
Adds an endpoint, like /trackback/.
* [add\_rewrite\_endpoint()](../../functions/add_rewrite_endpoint) : for full documentation.
`$name` string Required Name of the endpoint. `$places` int Required Endpoint mask describing the places the endpoint should be added.
Accepts a mask of:
* `EP_ALL`
* `EP_NONE`
* `EP_ALL_ARCHIVES`
* `EP_ATTACHMENT`
* `EP_AUTHORS`
* `EP_CATEGORIES`
* `EP_COMMENTS`
* `EP_DATE`
* `EP_DAY`
* `EP_MONTH`
* `EP_PAGES`
* `EP_PERMALINK`
* `EP_ROOT`
* `EP_SEARCH`
* `EP_TAGS`
* `EP_YEAR`
`$query_var` string|bool Optional Name of the corresponding query variable. Pass `false` to skip registering a query\_var for this endpoint. Defaults to the value of `$name`. Default: `true`
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function add_endpoint( $name, $places, $query_var = true ) {
global $wp;
// For backward compatibility, if null has explicitly been passed as `$query_var`, assume `true`.
if ( true === $query_var || null === $query_var ) {
$query_var = $name;
}
$this->endpoints[] = array( $places, $name, $query_var );
if ( $query_var ) {
$wp->add_query_var( $query_var );
}
}
```
| Uses | Description |
| --- | --- |
| [WP::add\_query\_var()](../wp/add_query_var) wp-includes/class-wp.php | Adds a query variable to the list of public query variables. |
| Used By | Description |
| --- | --- |
| [add\_rewrite\_endpoint()](../../functions/add_rewrite_endpoint) wp-includes/rewrite.php | Adds an endpoint, like /trackback/. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Added support for skipping query var registration by passing `false` to `$query_var`. |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | $query\_var parameter added. |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Rewrite::set_category_base( string $category_base ) WP\_Rewrite::set\_category\_base( string $category\_base )
==========================================================
Sets the category base for the category permalink.
Will update the ‘category\_base’ option, if there is a difference between the current category base and the parameter value. Calls [WP\_Rewrite::init()](init) after the option is updated.
`$category_base` string Required Category permalink structure base. File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function set_category_base( $category_base ) {
if ( get_option( 'category_base' ) !== $category_base ) {
update_option( 'category_base', $category_base );
$this->init();
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::init()](init) wp-includes/class-wp-rewrite.php | Sets up the object’s properties. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::generate_rewrite_rules( string $permalink_structure, int $ep_mask = EP_NONE, bool $paged = true, bool $feed = true, bool $forcomments = false, bool $walk_dirs = true, bool $endpoints = true ): string[] WP\_Rewrite::generate\_rewrite\_rules( string $permalink\_structure, int $ep\_mask = EP\_NONE, bool $paged = true, bool $feed = true, bool $forcomments = false, bool $walk\_dirs = true, bool $endpoints = true ): string[]
============================================================================================================================================================================================================================
Generates rewrite rules from a permalink structure.
The main [WP\_Rewrite](../wp_rewrite) function for building the rewrite rule list. The contents of the function is a mix of black magic and regular expressions, so best just ignore the contents and move to the parameters.
`$permalink_structure` string Required The permalink structure. `$ep_mask` int Optional Endpoint mask defining what endpoints are added to the structure.
Accepts a mask of:
* `EP_ALL`
* `EP_NONE`
* `EP_ALL_ARCHIVES`
* `EP_ATTACHMENT`
* `EP_AUTHORS`
* `EP_CATEGORIES`
* `EP_COMMENTS`
* `EP_DATE`
* `EP_DAY`
* `EP_MONTH`
* `EP_PAGES`
* `EP_PERMALINK`
* `EP_ROOT`
* `EP_SEARCH`
* `EP_TAGS`
* `EP_YEAR` Default `EP_NONE`.
Default: `EP_NONE`
`$paged` bool Optional Whether archive pagination rules should be added for the structure.
Default: `true`
`$feed` bool Optional Whether feed rewrite rules should be added for the structure.
Default: `true`
`$forcomments` bool Optional Whether the feed rules should be a query for a comments feed.
Default: `false`
`$walk_dirs` bool Optional Whether the `'directories'` making up the structure should be walked over and rewrite rules built for each in-turn. Default: `true`
`$endpoints` bool Optional Whether endpoints should be applied to the generated rewrite rules.
Default: `true`
string[] Array of rewrite rules keyed by their regex pattern.
A large method that generates the rewrite rules for a given structure, $permalink\_structure.
If $page is true, an extra rewrite rule will be generated for accessing different pages (e.g. /category/tech/page/2 points to the second page of the ‘tech’ category archive).
If $feed is true, extra rewrite rules will be generated for obtaining a feed of the current page, and if $forcomments is true, this will be a comment feed.
If $walk\_dirs is true, then a rewrite rule will be generated for each directory of the structure provided, e.g. if you provide it with ‘/%year%/%month%/%day/’, rewrite rules will be generated for ‘/%year%/’, /%year%/%month%/’ and ‘/%year%/%month%/%day%/’.
This returns an associative array using the regex part of the rewrite rule as the keys and redirect part of the rewrite rule as the value.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function generate_rewrite_rules( $permalink_structure, $ep_mask = EP_NONE, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true, $endpoints = true ) {
// Build a regex to match the feed section of URLs, something like (feed|atom|rss|rss2)/?
$feedregex2 = '';
foreach ( (array) $this->feeds as $feed_name ) {
$feedregex2 .= $feed_name . '|';
}
$feedregex2 = '(' . trim( $feedregex2, '|' ) . ')/?$';
/*
* $feedregex is identical but with /feed/ added on as well, so URLs like <permalink>/feed/atom
* and <permalink>/atom are both possible
*/
$feedregex = $this->feed_base . '/' . $feedregex2;
// Build a regex to match the trackback and page/xx parts of URLs.
$trackbackregex = 'trackback/?$';
$pageregex = $this->pagination_base . '/?([0-9]{1,})/?$';
$commentregex = $this->comments_pagination_base . '-([0-9]{1,})/?$';
$embedregex = 'embed/?$';
// Build up an array of endpoint regexes to append => queries to append.
if ( $endpoints ) {
$ep_query_append = array();
foreach ( (array) $this->endpoints as $endpoint ) {
// Match everything after the endpoint name, but allow for nothing to appear there.
$epmatch = $endpoint[1] . '(/(.*))?/?$';
// This will be appended on to the rest of the query for each dir.
$epquery = '&' . $endpoint[2] . '=';
$ep_query_append[ $epmatch ] = array( $endpoint[0], $epquery );
}
}
// Get everything up to the first rewrite tag.
$front = substr( $permalink_structure, 0, strpos( $permalink_structure, '%' ) );
// Build an array of the tags (note that said array ends up being in $tokens[0]).
preg_match_all( '/%.+?%/', $permalink_structure, $tokens );
$num_tokens = count( $tokens[0] );
$index = $this->index; // Probably 'index.php'.
$feedindex = $index;
$trackbackindex = $index;
$embedindex = $index;
/*
* Build a list from the rewritecode and queryreplace arrays, that will look something
* like tagname=$matches[i] where i is the current $i.
*/
$queries = array();
for ( $i = 0; $i < $num_tokens; ++$i ) {
if ( 0 < $i ) {
$queries[ $i ] = $queries[ $i - 1 ] . '&';
} else {
$queries[ $i ] = '';
}
$query_token = str_replace( $this->rewritecode, $this->queryreplace, $tokens[0][ $i ] ) . $this->preg_index( $i + 1 );
$queries[ $i ] .= $query_token;
}
// Get the structure, minus any cruft (stuff that isn't tags) at the front.
$structure = $permalink_structure;
if ( '/' !== $front ) {
$structure = str_replace( $front, '', $structure );
}
/*
* Create a list of dirs to walk over, making rewrite rules for each level
* so for example, a $structure of /%year%/%monthnum%/%postname% would create
* rewrite rules for /%year%/, /%year%/%monthnum%/ and /%year%/%monthnum%/%postname%
*/
$structure = trim( $structure, '/' );
$dirs = $walk_dirs ? explode( '/', $structure ) : array( $structure );
$num_dirs = count( $dirs );
// Strip slashes from the front of $front.
$front = preg_replace( '|^/+|', '', $front );
// The main workhorse loop.
$post_rewrite = array();
$struct = $front;
for ( $j = 0; $j < $num_dirs; ++$j ) {
// Get the struct for this dir, and trim slashes off the front.
$struct .= $dirs[ $j ] . '/'; // Accumulate. see comment near explode('/', $structure) above.
$struct = ltrim( $struct, '/' );
// Replace tags with regexes.
$match = str_replace( $this->rewritecode, $this->rewritereplace, $struct );
// Make a list of tags, and store how many there are in $num_toks.
$num_toks = preg_match_all( '/%.+?%/', $struct, $toks );
// Get the 'tagname=$matches[i]'.
$query = ( ! empty( $num_toks ) && isset( $queries[ $num_toks - 1 ] ) ) ? $queries[ $num_toks - 1 ] : '';
// Set up $ep_mask_specific which is used to match more specific URL types.
switch ( $dirs[ $j ] ) {
case '%year%':
$ep_mask_specific = EP_YEAR;
break;
case '%monthnum%':
$ep_mask_specific = EP_MONTH;
break;
case '%day%':
$ep_mask_specific = EP_DAY;
break;
default:
$ep_mask_specific = EP_NONE;
}
// Create query for /page/xx.
$pagematch = $match . $pageregex;
$pagequery = $index . '?' . $query . '&paged=' . $this->preg_index( $num_toks + 1 );
// Create query for /comment-page-xx.
$commentmatch = $match . $commentregex;
$commentquery = $index . '?' . $query . '&cpage=' . $this->preg_index( $num_toks + 1 );
if ( get_option( 'page_on_front' ) ) {
// Create query for Root /comment-page-xx.
$rootcommentmatch = $match . $commentregex;
$rootcommentquery = $index . '?' . $query . '&page_id=' . get_option( 'page_on_front' ) . '&cpage=' . $this->preg_index( $num_toks + 1 );
}
// Create query for /feed/(feed|atom|rss|rss2|rdf).
$feedmatch = $match . $feedregex;
$feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index( $num_toks + 1 );
// Create query for /(feed|atom|rss|rss2|rdf) (see comment near creation of $feedregex).
$feedmatch2 = $match . $feedregex2;
$feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index( $num_toks + 1 );
// Create query and regex for embeds.
$embedmatch = $match . $embedregex;
$embedquery = $embedindex . '?' . $query . '&embed=true';
// If asked to, turn the feed queries into comment feed ones.
if ( $forcomments ) {
$feedquery .= '&withcomments=1';
$feedquery2 .= '&withcomments=1';
}
// Start creating the array of rewrites for this dir.
$rewrite = array();
// ...adding on /feed/ regexes => queries.
if ( $feed ) {
$rewrite = array(
$feedmatch => $feedquery,
$feedmatch2 => $feedquery2,
$embedmatch => $embedquery,
);
}
// ...and /page/xx ones.
if ( $paged ) {
$rewrite = array_merge( $rewrite, array( $pagematch => $pagequery ) );
}
// Only on pages with comments add ../comment-page-xx/.
if ( EP_PAGES & $ep_mask || EP_PERMALINK & $ep_mask ) {
$rewrite = array_merge( $rewrite, array( $commentmatch => $commentquery ) );
} elseif ( EP_ROOT & $ep_mask && get_option( 'page_on_front' ) ) {
$rewrite = array_merge( $rewrite, array( $rootcommentmatch => $rootcommentquery ) );
}
// Do endpoints.
if ( $endpoints ) {
foreach ( (array) $ep_query_append as $regex => $ep ) {
// Add the endpoints on if the mask fits.
if ( $ep[0] & $ep_mask || $ep[0] & $ep_mask_specific ) {
$rewrite[ $match . $regex ] = $index . '?' . $query . $ep[1] . $this->preg_index( $num_toks + 2 );
}
}
}
// If we've got some tags in this dir.
if ( $num_toks ) {
$post = false;
$page = false;
/*
* Check to see if this dir is permalink-level: i.e. the structure specifies an
* individual post. Do this by checking it contains at least one of 1) post name,
* 2) post ID, 3) page name, 4) timestamp (year, month, day, hour, second and
* minute all present). Set these flags now as we need them for the endpoints.
*/
if ( strpos( $struct, '%postname%' ) !== false
|| strpos( $struct, '%post_id%' ) !== false
|| strpos( $struct, '%pagename%' ) !== false
|| ( strpos( $struct, '%year%' ) !== false && strpos( $struct, '%monthnum%' ) !== false && strpos( $struct, '%day%' ) !== false && strpos( $struct, '%hour%' ) !== false && strpos( $struct, '%minute%' ) !== false && strpos( $struct, '%second%' ) !== false )
) {
$post = true;
if ( strpos( $struct, '%pagename%' ) !== false ) {
$page = true;
}
}
if ( ! $post ) {
// For custom post types, we need to add on endpoints as well.
foreach ( get_post_types( array( '_builtin' => false ) ) as $ptype ) {
if ( strpos( $struct, "%$ptype%" ) !== false ) {
$post = true;
// This is for page style attachment URLs.
$page = is_post_type_hierarchical( $ptype );
break;
}
}
}
// If creating rules for a permalink, do all the endpoints like attachments etc.
if ( $post ) {
// Create query and regex for trackback.
$trackbackmatch = $match . $trackbackregex;
$trackbackquery = $trackbackindex . '?' . $query . '&tb=1';
// Create query and regex for embeds.
$embedmatch = $match . $embedregex;
$embedquery = $embedindex . '?' . $query . '&embed=true';
// Trim slashes from the end of the regex for this dir.
$match = rtrim( $match, '/' );
// Get rid of brackets.
$submatchbase = str_replace( array( '(', ')' ), '', $match );
// Add a rule for at attachments, which take the form of <permalink>/some-text.
$sub1 = $submatchbase . '/([^/]+)/';
// Add trackback regex <permalink>/trackback/...
$sub1tb = $sub1 . $trackbackregex;
// And <permalink>/feed/(atom|...)
$sub1feed = $sub1 . $feedregex;
// And <permalink>/(feed|atom...)
$sub1feed2 = $sub1 . $feedregex2;
// And <permalink>/comment-page-xx
$sub1comment = $sub1 . $commentregex;
// And <permalink>/embed/...
$sub1embed = $sub1 . $embedregex;
/*
* Add another rule to match attachments in the explicit form:
* <permalink>/attachment/some-text
*/
$sub2 = $submatchbase . '/attachment/([^/]+)/';
// And add trackbacks <permalink>/attachment/trackback.
$sub2tb = $sub2 . $trackbackregex;
// Feeds, <permalink>/attachment/feed/(atom|...)
$sub2feed = $sub2 . $feedregex;
// And feeds again on to this <permalink>/attachment/(feed|atom...)
$sub2feed2 = $sub2 . $feedregex2;
// And <permalink>/comment-page-xx
$sub2comment = $sub2 . $commentregex;
// And <permalink>/embed/...
$sub2embed = $sub2 . $embedregex;
// Create queries for these extra tag-ons we've just dealt with.
$subquery = $index . '?attachment=' . $this->preg_index( 1 );
$subtbquery = $subquery . '&tb=1';
$subfeedquery = $subquery . '&feed=' . $this->preg_index( 2 );
$subcommentquery = $subquery . '&cpage=' . $this->preg_index( 2 );
$subembedquery = $subquery . '&embed=true';
// Do endpoints for attachments.
if ( ! empty( $endpoints ) ) {
foreach ( (array) $ep_query_append as $regex => $ep ) {
if ( $ep[0] & EP_ATTACHMENT ) {
$rewrite[ $sub1 . $regex ] = $subquery . $ep[1] . $this->preg_index( 3 );
$rewrite[ $sub2 . $regex ] = $subquery . $ep[1] . $this->preg_index( 3 );
}
}
}
/*
* Now we've finished with endpoints, finish off the $sub1 and $sub2 matches
* add a ? as we don't have to match that last slash, and finally a $ so we
* match to the end of the URL
*/
$sub1 .= '?$';
$sub2 .= '?$';
/*
* Post pagination, e.g. <permalink>/2/
* Previously: '(/[0-9]+)?/?$', which produced '/2' for page.
* When cast to int, returned 0.
*/
$match = $match . '(?:/([0-9]+))?/?$';
$query = $index . '?' . $query . '&page=' . $this->preg_index( $num_toks + 1 );
// Not matching a permalink so this is a lot simpler.
} else {
// Close the match and finalize the query.
$match .= '?$';
$query = $index . '?' . $query;
}
/*
* Create the final array for this dir by joining the $rewrite array (which currently
* only contains rules/queries for trackback, pages etc) to the main regex/query for
* this dir
*/
$rewrite = array_merge( $rewrite, array( $match => $query ) );
// If we're matching a permalink, add those extras (attachments etc) on.
if ( $post ) {
// Add trackback.
$rewrite = array_merge( array( $trackbackmatch => $trackbackquery ), $rewrite );
// Add embed.
$rewrite = array_merge( array( $embedmatch => $embedquery ), $rewrite );
// Add regexes/queries for attachments, attachment trackbacks and so on.
if ( ! $page ) {
// Require <permalink>/attachment/stuff form for pages because of confusion with subpages.
$rewrite = array_merge(
$rewrite,
array(
$sub1 => $subquery,
$sub1tb => $subtbquery,
$sub1feed => $subfeedquery,
$sub1feed2 => $subfeedquery,
$sub1comment => $subcommentquery,
$sub1embed => $subembedquery,
)
);
}
$rewrite = array_merge(
array(
$sub2 => $subquery,
$sub2tb => $subtbquery,
$sub2feed => $subfeedquery,
$sub2feed2 => $subfeedquery,
$sub2comment => $subcommentquery,
$sub2embed => $subembedquery,
),
$rewrite
);
}
}
// Add the rules for this dir to the accumulating $post_rewrite.
$post_rewrite = array_merge( $rewrite, $post_rewrite );
}
// The finished rules. phew!
return $post_rewrite;
}
```
| Uses | Description |
| --- | --- |
| [is\_post\_type\_hierarchical()](../../functions/is_post_type_hierarchical) wp-includes/post.php | Determines whether the post type is hierarchical. |
| [WP\_Rewrite::preg\_index()](preg_index) wp-includes/class-wp-rewrite.php | Indexes for matches for usage in preg\_\*() functions. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [get\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| Used By | Description |
| --- | --- |
| [WP\_Rewrite::generate\_rewrite\_rule()](generate_rewrite_rule) wp-includes/class-wp-rewrite.php | Generates rewrite rules with permalink structure and walking directory only. |
| [WP\_Rewrite::rewrite\_rules()](rewrite_rules) wp-includes/class-wp-rewrite.php | Constructs rewrite matches and queries from permalink structure. |
| [WP\_Rewrite::page\_rewrite\_rules()](page_rewrite_rules) wp-includes/class-wp-rewrite.php | Retrieves all of the rewrite rules for pages. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
| programming_docs |
wordpress WP_Rewrite::rewrite_rules(): string[] WP\_Rewrite::rewrite\_rules(): string[]
=======================================
Constructs rewrite matches and queries from permalink structure.
Runs the action [‘generate\_rewrite\_rules’](../../hooks/generate_rewrite_rules) with the parameter that is an reference to the current [WP\_Rewrite](../wp_rewrite) instance to further manipulate the permalink structures and rewrite rules. Runs the [‘rewrite\_rules\_array’](../../hooks/rewrite_rules_array) filter on the full rewrite rule array.
There are two ways to manipulate the rewrite rules, one by hooking into the [‘generate\_rewrite\_rules’](../../hooks/generate_rewrite_rules) action and gaining full control of the object or just manipulating the rewrite rule array before it is passed from the function.
string[] An associative array of matches and queries.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function rewrite_rules() {
$rewrite = array();
if ( empty( $this->permalink_structure ) ) {
return $rewrite;
}
// robots.txt -- only if installed at the root.
$home_path = parse_url( home_url() );
$robots_rewrite = ( empty( $home_path['path'] ) || '/' === $home_path['path'] ) ? array( 'robots\.txt$' => $this->index . '?robots=1' ) : array();
// favicon.ico -- only if installed at the root.
$favicon_rewrite = ( empty( $home_path['path'] ) || '/' === $home_path['path'] ) ? array( 'favicon\.ico$' => $this->index . '?favicon=1' ) : array();
// Old feed and service files.
$deprecated_files = array(
'.*wp-(atom|rdf|rss|rss2|feed|commentsrss2)\.php$' => $this->index . '?feed=old',
'.*wp-app\.php(/.*)?$' => $this->index . '?error=403',
);
// Registration rules.
$registration_pages = array();
if ( is_multisite() && is_main_site() ) {
$registration_pages['.*wp-signup.php$'] = $this->index . '?signup=true';
$registration_pages['.*wp-activate.php$'] = $this->index . '?activate=true';
}
// Deprecated.
$registration_pages['.*wp-register.php$'] = $this->index . '?register=true';
// Post rewrite rules.
$post_rewrite = $this->generate_rewrite_rules( $this->permalink_structure, EP_PERMALINK );
/**
* Filters rewrite rules used for "post" archives.
*
* @since 1.5.0
*
* @param string[] $post_rewrite Array of rewrite rules for posts, keyed by their regex pattern.
*/
$post_rewrite = apply_filters( 'post_rewrite_rules', $post_rewrite );
// Date rewrite rules.
$date_rewrite = $this->generate_rewrite_rules( $this->get_date_permastruct(), EP_DATE );
/**
* Filters rewrite rules used for date archives.
*
* Likely date archives would include `/yyyy/`, `/yyyy/mm/`, and `/yyyy/mm/dd/`.
*
* @since 1.5.0
*
* @param string[] $date_rewrite Array of rewrite rules for date archives, keyed by their regex pattern.
*/
$date_rewrite = apply_filters( 'date_rewrite_rules', $date_rewrite );
// Root-level rewrite rules.
$root_rewrite = $this->generate_rewrite_rules( $this->root . '/', EP_ROOT );
/**
* Filters rewrite rules used for root-level archives.
*
* Likely root-level archives would include pagination rules for the homepage
* as well as site-wide post feeds (e.g. `/feed/`, and `/feed/atom/`).
*
* @since 1.5.0
*
* @param string[] $root_rewrite Array of root-level rewrite rules, keyed by their regex pattern.
*/
$root_rewrite = apply_filters( 'root_rewrite_rules', $root_rewrite );
// Comments rewrite rules.
$comments_rewrite = $this->generate_rewrite_rules( $this->root . $this->comments_base, EP_COMMENTS, false, true, true, false );
/**
* Filters rewrite rules used for comment feed archives.
*
* Likely comments feed archives include `/comments/feed/` and `/comments/feed/atom/`.
*
* @since 1.5.0
*
* @param string[] $comments_rewrite Array of rewrite rules for the site-wide comments feeds, keyed by their regex pattern.
*/
$comments_rewrite = apply_filters( 'comments_rewrite_rules', $comments_rewrite );
// Search rewrite rules.
$search_structure = $this->get_search_permastruct();
$search_rewrite = $this->generate_rewrite_rules( $search_structure, EP_SEARCH );
/**
* Filters rewrite rules used for search archives.
*
* Likely search-related archives include `/search/search+query/` as well as
* pagination and feed paths for a search.
*
* @since 1.5.0
*
* @param string[] $search_rewrite Array of rewrite rules for search queries, keyed by their regex pattern.
*/
$search_rewrite = apply_filters( 'search_rewrite_rules', $search_rewrite );
// Author rewrite rules.
$author_rewrite = $this->generate_rewrite_rules( $this->get_author_permastruct(), EP_AUTHORS );
/**
* Filters rewrite rules used for author archives.
*
* Likely author archives would include `/author/author-name/`, as well as
* pagination and feed paths for author archives.
*
* @since 1.5.0
*
* @param string[] $author_rewrite Array of rewrite rules for author archives, keyed by their regex pattern.
*/
$author_rewrite = apply_filters( 'author_rewrite_rules', $author_rewrite );
// Pages rewrite rules.
$page_rewrite = $this->page_rewrite_rules();
/**
* Filters rewrite rules used for "page" post type archives.
*
* @since 1.5.0
*
* @param string[] $page_rewrite Array of rewrite rules for the "page" post type, keyed by their regex pattern.
*/
$page_rewrite = apply_filters( 'page_rewrite_rules', $page_rewrite );
// Extra permastructs.
foreach ( $this->extra_permastructs as $permastructname => $struct ) {
if ( is_array( $struct ) ) {
if ( count( $struct ) == 2 ) {
$rules = $this->generate_rewrite_rules( $struct[0], $struct[1] );
} else {
$rules = $this->generate_rewrite_rules( $struct['struct'], $struct['ep_mask'], $struct['paged'], $struct['feed'], $struct['forcomments'], $struct['walk_dirs'], $struct['endpoints'] );
}
} else {
$rules = $this->generate_rewrite_rules( $struct );
}
/**
* Filters rewrite rules used for individual permastructs.
*
* The dynamic portion of the hook name, `$permastructname`, refers
* to the name of the registered permastruct.
*
* Possible hook names include:
*
* - `category_rewrite_rules`
* - `post_format_rewrite_rules`
* - `post_tag_rewrite_rules`
*
* @since 3.1.0
*
* @param string[] $rules Array of rewrite rules generated for the current permastruct, keyed by their regex pattern.
*/
$rules = apply_filters( "{$permastructname}_rewrite_rules", $rules );
if ( 'post_tag' === $permastructname ) {
/**
* Filters rewrite rules used specifically for Tags.
*
* @since 2.3.0
* @deprecated 3.1.0 Use {@see 'post_tag_rewrite_rules'} instead.
*
* @param string[] $rules Array of rewrite rules generated for tags, keyed by their regex pattern.
*/
$rules = apply_filters_deprecated( 'tag_rewrite_rules', array( $rules ), '3.1.0', 'post_tag_rewrite_rules' );
}
$this->extra_rules_top = array_merge( $this->extra_rules_top, $rules );
}
// Put them together.
if ( $this->use_verbose_page_rules ) {
$this->rules = array_merge( $this->extra_rules_top, $robots_rewrite, $favicon_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $page_rewrite, $post_rewrite, $this->extra_rules );
} else {
$this->rules = array_merge( $this->extra_rules_top, $robots_rewrite, $favicon_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $post_rewrite, $page_rewrite, $this->extra_rules );
}
/**
* Fires after the rewrite rules are generated.
*
* @since 1.5.0
*
* @param WP_Rewrite $wp_rewrite Current WP_Rewrite instance (passed by reference).
*/
do_action_ref_array( 'generate_rewrite_rules', array( &$this ) );
/**
* Filters the full set of generated rewrite rules.
*
* @since 1.5.0
*
* @param string[] $rules The compiled array of rewrite rules, keyed by their regex pattern.
*/
$this->rules = apply_filters( 'rewrite_rules_array', $this->rules );
return $this->rules;
}
```
[apply\_filters( 'author\_rewrite\_rules', string[] $author\_rewrite )](../../hooks/author_rewrite_rules)
Filters rewrite rules used for author archives.
[apply\_filters( 'comments\_rewrite\_rules', string[] $comments\_rewrite )](../../hooks/comments_rewrite_rules)
Filters rewrite rules used for comment feed archives.
[apply\_filters( 'date\_rewrite\_rules', string[] $date\_rewrite )](../../hooks/date_rewrite_rules)
Filters rewrite rules used for date archives.
[do\_action\_ref\_array( 'generate\_rewrite\_rules', WP\_Rewrite $wp\_rewrite )](../../hooks/generate_rewrite_rules)
Fires after the rewrite rules are generated.
[apply\_filters( 'page\_rewrite\_rules', string[] $page\_rewrite )](../../hooks/page_rewrite_rules)
Filters rewrite rules used for “page” post type archives.
[apply\_filters( 'post\_rewrite\_rules', string[] $post\_rewrite )](../../hooks/post_rewrite_rules)
Filters rewrite rules used for “post” archives.
[apply\_filters( 'rewrite\_rules\_array', string[] $rules )](../../hooks/rewrite_rules_array)
Filters the full set of generated rewrite rules.
[apply\_filters( 'root\_rewrite\_rules', string[] $root\_rewrite )](../../hooks/root_rewrite_rules)
Filters rewrite rules used for root-level archives.
[apply\_filters( 'search\_rewrite\_rules', string[] $search\_rewrite )](../../hooks/search_rewrite_rules)
Filters rewrite rules used for search archives.
[apply\_filters\_deprecated( 'tag\_rewrite\_rules', string[] $rules )](../../hooks/tag_rewrite_rules)
Filters rewrite rules used specifically for Tags.
[apply\_filters( "{$permastructname}\_rewrite\_rules", string[] $rules )](../../hooks/permastructname_rewrite_rules)
Filters rewrite rules used for individual permastructs.
| Uses | Description |
| --- | --- |
| [apply\_filters\_deprecated()](../../functions/apply_filters_deprecated) wp-includes/plugin.php | Fires functions attached to a deprecated filter hook. |
| [is\_main\_site()](../../functions/is_main_site) wp-includes/functions.php | Determines whether a site is the main site of the current network. |
| [do\_action\_ref\_array()](../../functions/do_action_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook, specifying arguments in an array. |
| [WP\_Rewrite::generate\_rewrite\_rules()](generate_rewrite_rules) wp-includes/class-wp-rewrite.php | Generates rewrite rules from a permalink structure. |
| [WP\_Rewrite::get\_date\_permastruct()](get_date_permastruct) wp-includes/class-wp-rewrite.php | Retrieves date permalink structure, with year, month, and day. |
| [WP\_Rewrite::get\_search\_permastruct()](get_search_permastruct) wp-includes/class-wp-rewrite.php | Retrieves the search permalink structure. |
| [WP\_Rewrite::get\_author\_permastruct()](get_author_permastruct) wp-includes/class-wp-rewrite.php | Retrieves the author permalink structure. |
| [WP\_Rewrite::page\_rewrite\_rules()](page_rewrite_rules) wp-includes/class-wp-rewrite.php | Retrieves all of the rewrite rules for pages. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Rewrite::wp\_rewrite\_rules()](wp_rewrite_rules) wp-includes/class-wp-rewrite.php | Retrieves the rewrite rules. |
| [WP\_Rewrite::mod\_rewrite\_rules()](mod_rewrite_rules) wp-includes/class-wp-rewrite.php | Retrieves mod\_rewrite-formatted rewrite rules to write to .htaccess. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::set_permalink_structure( string $permalink_structure ) WP\_Rewrite::set\_permalink\_structure( string $permalink\_structure )
======================================================================
Sets the main permalink structure for the site.
Will update the ‘permalink\_structure’ option, if there is a difference between the current permalink structure and the parameter value. Calls [WP\_Rewrite::init()](init) after the option is updated.
Fires the [‘permalink\_structure\_changed’](../../hooks/permalink_structure_changed) action once the init call has processed passing the old and new values
`$permalink_structure` string Required Permalink structure. File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function set_permalink_structure( $permalink_structure ) {
if ( $permalink_structure != $this->permalink_structure ) {
$old_permalink_structure = $this->permalink_structure;
update_option( 'permalink_structure', $permalink_structure );
$this->init();
/**
* Fires after the permalink structure is updated.
*
* @since 2.8.0
*
* @param string $old_permalink_structure The previous permalink structure.
* @param string $permalink_structure The new permalink structure.
*/
do_action( 'permalink_structure_changed', $old_permalink_structure, $permalink_structure );
}
}
```
[do\_action( 'permalink\_structure\_changed', string $old\_permalink\_structure, string $permalink\_structure )](../../hooks/permalink_structure_changed)
Fires after the permalink structure is updated.
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::init()](init) wp-includes/class-wp-rewrite.php | Sets up the object’s properties. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| Used By | Description |
| --- | --- |
| [wp\_install\_maybe\_enable\_pretty\_permalinks()](../../functions/wp_install_maybe_enable_pretty_permalinks) wp-admin/includes/upgrade.php | Maybe enable pretty permalinks on installation. |
| [populate\_network()](../../functions/populate_network) wp-admin/includes/schema.php | Populate network settings. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::using_index_permalinks(): bool WP\_Rewrite::using\_index\_permalinks(): bool
=============================================
Determines whether permalinks are being used and rewrite module is not enabled.
Means that permalink links are enabled and index.php is in the URL.
bool Whether permalink links are enabled and index.php is in the URL.
Returns true if your blog is using PATHINFO permalinks.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function using_index_permalinks() {
if ( empty( $this->permalink_structure ) ) {
return false;
}
// If the index is not in the permalink, we're using mod_rewrite.
return preg_match( '#^/*' . $this->index . '#', $this->permalink_structure );
}
```
| Used By | Description |
| --- | --- |
| [get\_rest\_url()](../../functions/get_rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint on a site. |
| [paginate\_links()](../../functions/paginate_links) wp-includes/general-template.php | Retrieves paginated links for archive post pages. |
| [create\_initial\_taxonomies()](../../functions/create_initial_taxonomies) wp-includes/taxonomy.php | Creates the initial taxonomies. |
| [get\_pagenum\_link()](../../functions/get_pagenum_link) wp-includes/link-template.php | Retrieves the link for a page number. |
| [WP\_Rewrite::init()](init) wp-includes/class-wp-rewrite.php | Sets up the object’s properties. |
| [WP\_Rewrite::using\_mod\_rewrite\_permalinks()](using_mod_rewrite_permalinks) wp-includes/class-wp-rewrite.php | Determines whether permalinks are being used and rewrite module is enabled. |
| [url\_to\_postid()](../../functions/url_to_postid) wp-includes/rewrite.php | Examines a URL and try to determine the post ID it represents. |
| [redirect\_canonical()](../../functions/redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::preg_index( int $number ): string WP\_Rewrite::preg\_index( int $number ): string
===============================================
Indexes for matches for usage in preg\_\*() functions.
The format of the string is, with empty matches property value, ‘$NUM’.
The ‘NUM’ will be replaced with the value in the $number parameter. With the matches property not empty, the value of the returned string will contain that value of the matches property. The format then will be ‘$MATCHES[NUM]’, with MATCHES as the value in the property and NUM the value of the $number parameter.
`$number` int Required Index number. string
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function preg_index( $number ) {
$match_prefix = '$';
$match_suffix = '';
if ( ! empty( $this->matches ) ) {
$match_prefix = '$' . $this->matches . '[';
$match_suffix = ']';
}
return "$match_prefix$number$match_suffix";
}
```
| Used By | Description |
| --- | --- |
| [WP\_Rewrite::generate\_rewrite\_rules()](generate_rewrite_rules) wp-includes/class-wp-rewrite.php | Generates rewrite rules from a permalink structure. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::iis7_url_rewrite_rules( bool $add_parent_tags = false ): string WP\_Rewrite::iis7\_url\_rewrite\_rules( bool $add\_parent\_tags = false ): string
=================================================================================
Retrieves IIS7 URL Rewrite formatted rewrite rules to write to web.config file.
Does not actually write to the web.config file, but creates the rules for the process that will.
`$add_parent_tags` bool Optional Whether to add parent tags to the rewrite rule sets.
Default: `false`
string IIS7 URL rewrite rule sets.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function iis7_url_rewrite_rules( $add_parent_tags = false ) {
if ( ! $this->using_permalinks() ) {
return '';
}
$rules = '';
if ( $add_parent_tags ) {
$rules .= '<configuration>
<system.webServer>
<rewrite>
<rules>';
}
$rules .= '
<rule name="WordPress: ' . esc_attr( home_url() ) . '" patternSyntax="Wildcard">
<match url="*" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.php" />
</rule>';
if ( $add_parent_tags ) {
$rules .= '
</rules>
</rewrite>
</system.webServer>
</configuration>';
}
/**
* Filters the list of rewrite rules formatted for output to a web.config.
*
* @since 2.8.0
*
* @param string $rules Rewrite rules formatted for IIS web.config.
*/
return apply_filters( 'iis7_url_rewrite_rules', $rules );
}
```
[apply\_filters( 'iis7\_url\_rewrite\_rules', string $rules )](../../hooks/iis7_url_rewrite_rules)
Filters the list of rewrite rules formatted for output to a web.config.
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::using\_permalinks()](using_permalinks) wp-includes/class-wp-rewrite.php | Determines whether permalinks are being used. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [iis7\_save\_url\_rewrite\_rules()](../../functions/iis7_save_url_rewrite_rules) wp-admin/includes/misc.php | Updates the IIS web.config file with the current rules if it is writable. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Rewrite::get_category_permastruct(): string|false WP\_Rewrite::get\_category\_permastruct(): string|false
=======================================================
Retrieves the permalink structure for categories.
If the category\_base property has no value, then the category structure will have the front property value, followed by ‘category’, and finally ‘%category%’. If it does, then the root property will be used, along with the category\_base property value.
string|false Category permalink structure on success, false on failure.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function get_category_permastruct() {
return $this->get_extra_permastruct( 'category' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::get\_extra\_permastruct()](get_extra_permastruct) wp-includes/class-wp-rewrite.php | Retrieves an extra permalink structure by name. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::flush_rules( bool $hard = true ) WP\_Rewrite::flush\_rules( bool $hard = true )
==============================================
Removes rewrite rules and then recreate rewrite rules.
Calls [WP\_Rewrite::wp\_rewrite\_rules()](wp_rewrite_rules) after removing the ‘rewrite\_rules’ option.
If the function named ‘save\_mod\_rewrite\_rules’ exists, it will be called.
`$hard` bool Optional Whether to update .htaccess (hard flush) or just update rewrite\_rules option (soft flush). Default is true (hard). Default: `true`
This method can be used to refresh WordPress’ rewrite rule cache. Generally, this should be used after programmatically adding one or more custom rewrite rules.
Because this function can be extremely costly in terms of performance, it should be used as sparingly as possible – such as during activation or deactivation of plugins or themes. Every attempt should be made to avoid using it in hooks that execute on each page load, such as [init](../../hooks/init "Plugin API/Action Reference/init").
WordPress keeps a cache of all custom rewrite rules. Sometimes plugins or themes make modifications to those rules, however WordPress will not actually recognize the changes until the cache is regenerated.
This is not a procedural function, but a non-static method of the [WP\_Rewrite](../wp_rewrite) class. To call flush\_rules(), you must first ensure you are using WordPress’ $wp\_rewrite global, and call it as a method (see “Usage” above for an example).
**Note:** This same method is called whenever permalink settings are changed or saved in the WordPress admin, so rewrite rules can be manually refreshed by visiting the Settings > Permalinks screen in WordPress’s admin.
**WARNING:** If this function is called without a parameter or with a parameter of true, your .htaccess will be overwritten and any custom rules will be lost!
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function flush_rules( $hard = true ) {
static $do_hard_later = null;
// Prevent this action from running before everyone has registered their rewrites.
if ( ! did_action( 'wp_loaded' ) ) {
add_action( 'wp_loaded', array( $this, 'flush_rules' ) );
$do_hard_later = ( isset( $do_hard_later ) ) ? $do_hard_later || $hard : $hard;
return;
}
if ( isset( $do_hard_later ) ) {
$hard = $do_hard_later;
unset( $do_hard_later );
}
update_option( 'rewrite_rules', '' );
$this->wp_rewrite_rules();
/**
* Filters whether a "hard" rewrite rule flush should be performed when requested.
*
* A "hard" flush updates .htaccess (Apache) or web.config (IIS).
*
* @since 3.7.0
*
* @param bool $hard Whether to flush rewrite rules "hard". Default true.
*/
if ( ! $hard || ! apply_filters( 'flush_rewrite_rules_hard', true ) ) {
return;
}
if ( function_exists( 'save_mod_rewrite_rules' ) ) {
save_mod_rewrite_rules();
}
if ( function_exists( 'iis7_save_url_rewrite_rules' ) ) {
iis7_save_url_rewrite_rules();
}
}
```
[apply\_filters( 'flush\_rewrite\_rules\_hard', bool $hard )](../../hooks/flush_rewrite_rules_hard)
Filters whether a “hard” rewrite rule flush should be performed when requested.
| Uses | Description |
| --- | --- |
| [save\_mod\_rewrite\_rules()](../../functions/save_mod_rewrite_rules) wp-admin/includes/misc.php | Updates the htaccess file with the current rules if it is writable. |
| [iis7\_save\_url\_rewrite\_rules()](../../functions/iis7_save_url_rewrite_rules) wp-admin/includes/misc.php | Updates the IIS web.config file with the current rules if it is writable. |
| [did\_action()](../../functions/did_action) wp-includes/plugin.php | Retrieves the number of times an action has been fired during the current request. |
| [WP\_Rewrite::wp\_rewrite\_rules()](wp_rewrite_rules) wp-includes/class-wp-rewrite.php | Retrieves the rewrite rules. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| Used By | Description |
| --- | --- |
| [wp\_install\_maybe\_enable\_pretty\_permalinks()](../../functions/wp_install_maybe_enable_pretty_permalinks) wp-admin/includes/upgrade.php | Maybe enable pretty permalinks on installation. |
| [wp\_install\_defaults()](../../functions/wp_install_defaults) wp-admin/includes/upgrade.php | Creates the initial content for a newly-installed site. |
| [flush\_rewrite\_rules()](../../functions/flush_rewrite_rules) wp-includes/rewrite.php | Removes rewrite rules and then recreate rewrite rules. |
| Version | Description |
| --- | --- |
| [2.0.1](https://developer.wordpress.org/reference/since/2.0.1/) | Introduced. |
wordpress WP_Rewrite::add_rewrite_tag( string $tag, string $regex, string $query ) WP\_Rewrite::add\_rewrite\_tag( string $tag, string $regex, string $query )
===========================================================================
Adds or updates existing rewrite tags (e.g. %postname%).
If the tag already exists, replace the existing pattern and query for that tag, otherwise add the new tag.
* WP\_Rewrite::$rewritecode
* WP\_Rewrite::$rewritereplace
* WP\_Rewrite::$queryreplace
`$tag` string Required Name of the rewrite tag to add or update. `$regex` string Required Regular expression to substitute the tag for in rewrite rules. `$query` string Required String to append to the rewritten query. Must end in `'='`. Add an element to the $rewritecode, $rewritereplace and $queryreplace arrays using each parameter respectively. If $tag already exists in $rewritecode, the existing value will be overwritten.
See also: [add\_rewrite\_tag($tagname, $regex)](../../functions/add_rewrite_tag "Rewrite API/add rewrite tag")
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function add_rewrite_tag( $tag, $regex, $query ) {
$position = array_search( $tag, $this->rewritecode, true );
if ( false !== $position && null !== $position ) {
$this->rewritereplace[ $position ] = $regex;
$this->queryreplace[ $position ] = $query;
} else {
$this->rewritecode[] = $tag;
$this->rewritereplace[] = $regex;
$this->queryreplace[] = $query;
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Rewrite::page\_rewrite\_rules()](page_rewrite_rules) wp-includes/class-wp-rewrite.php | Retrieves all of the rewrite rules for pages. |
| [add\_rewrite\_tag()](../../functions/add_rewrite_tag) wp-includes/rewrite.php | Adds a new rewrite tag (like %postname%). |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::page_rewrite_rules(): string[] WP\_Rewrite::page\_rewrite\_rules(): string[]
=============================================
Retrieves all of the rewrite rules for pages.
string[] Page rewrite rules.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function page_rewrite_rules() {
// The extra .? at the beginning prevents clashes with other regular expressions in the rules array.
$this->add_rewrite_tag( '%pagename%', '(.?.+?)', 'pagename=' );
return $this->generate_rewrite_rules( $this->get_page_permastruct(), EP_PAGES, true, true, false, false );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::add\_rewrite\_tag()](add_rewrite_tag) wp-includes/class-wp-rewrite.php | Adds or updates existing rewrite tags (e.g. %postname%). |
| [WP\_Rewrite::generate\_rewrite\_rules()](generate_rewrite_rules) wp-includes/class-wp-rewrite.php | Generates rewrite rules from a permalink structure. |
| [WP\_Rewrite::get\_page\_permastruct()](get_page_permastruct) wp-includes/class-wp-rewrite.php | Retrieves the page permalink structure. |
| Used By | Description |
| --- | --- |
| [WP\_Rewrite::rewrite\_rules()](rewrite_rules) wp-includes/class-wp-rewrite.php | Constructs rewrite matches and queries from permalink structure. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::get_author_permastruct(): string|false WP\_Rewrite::get\_author\_permastruct(): string|false
=====================================================
Retrieves the author permalink structure.
The permalink structure is front property, author base, and finally ‘/%author%’. Will set the author\_structure property and then return it without attempting to set the value again.
string|false Author permalink structure on success, false on failure.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function get_author_permastruct() {
if ( isset( $this->author_structure ) ) {
return $this->author_structure;
}
if ( empty( $this->permalink_structure ) ) {
$this->author_structure = '';
return false;
}
$this->author_structure = $this->front . $this->author_base . '/%author%';
return $this->author_structure;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Rewrite::rewrite\_rules()](rewrite_rules) wp-includes/class-wp-rewrite.php | Constructs rewrite matches and queries from permalink structure. |
| [get\_author\_posts\_url()](../../functions/get_author_posts_url) wp-includes/author-template.php | Retrieves the URL to the author page for the user with the ID provided. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::get_page_permastruct(): string|false WP\_Rewrite::get\_page\_permastruct(): string|false
===================================================
Retrieves the page permalink structure.
The permalink structure is root property, and ‘%pagename%’. Will set the page\_structure property and then return it without attempting to set the value again.
string|false Page permalink structure on success, false on failure.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function get_page_permastruct() {
if ( isset( $this->page_structure ) ) {
return $this->page_structure;
}
if ( empty( $this->permalink_structure ) ) {
$this->page_structure = '';
return false;
}
$this->page_structure = $this->root . '%pagename%';
return $this->page_structure;
}
```
| Used By | Description |
| --- | --- |
| [\_get\_page\_link()](../../functions/_get_page_link) wp-includes/link-template.php | Retrieves the page permalink. |
| [WP\_Rewrite::page\_rewrite\_rules()](page_rewrite_rules) wp-includes/class-wp-rewrite.php | Retrieves all of the rewrite rules for pages. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::get_month_permastruct(): string|false WP\_Rewrite::get\_month\_permastruct(): string|false
====================================================
Retrieves the month permalink structure without day and with year.
Gets the date permalink structure and strips out the day permalink structures. Keeps the year permalink structure.
string|false Year/Month permalink structure on success, false on failure.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function get_month_permastruct() {
$structure = $this->get_date_permastruct();
if ( empty( $structure ) ) {
return false;
}
$structure = str_replace( '%day%', '', $structure );
$structure = preg_replace( '#/+#', '/', $structure );
return $structure;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::get\_date\_permastruct()](get_date_permastruct) wp-includes/class-wp-rewrite.php | Retrieves date permalink structure, with year, month, and day. |
| Used By | Description |
| --- | --- |
| [get\_month\_link()](../../functions/get_month_link) wp-includes/link-template.php | Retrieves the permalink for the month archives with year. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::generate_rewrite_rule( string $permalink_structure, bool $walk_dirs = false ): array WP\_Rewrite::generate\_rewrite\_rule( string $permalink\_structure, bool $walk\_dirs = false ): array
=====================================================================================================
Generates rewrite rules with permalink structure and walking directory only.
Shorten version of [WP\_Rewrite::generate\_rewrite\_rules()](generate_rewrite_rules) that allows for shorter list of parameters. See the method for longer description of what generating rewrite rules does.
* [WP\_Rewrite::generate\_rewrite\_rules()](../wp_rewrite/generate_rewrite_rules): See for long description and rest of parameters.
`$permalink_structure` string Required The permalink structure to generate rules. `$walk_dirs` bool Optional Whether to create list of directories to walk over.
Default: `false`
array An array of rewrite rules keyed by their regex pattern.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function generate_rewrite_rule( $permalink_structure, $walk_dirs = false ) {
return $this->generate_rewrite_rules( $permalink_structure, EP_NONE, false, false, false, $walk_dirs );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::generate\_rewrite\_rules()](generate_rewrite_rules) wp-includes/class-wp-rewrite.php | Generates rewrite rules from a permalink structure. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::wp_rewrite_rules(): string[] WP\_Rewrite::wp\_rewrite\_rules(): string[]
===========================================
Retrieves the rewrite rules.
The difference between this method and [WP\_Rewrite::rewrite\_rules()](rewrite_rules) is that this method stores the rewrite rules in the ‘rewrite\_rules’ option and retrieves it. This prevents having to process all of the permalinks to get the rewrite rules in the form of caching.
string[] Array of rewrite rules keyed by their regex pattern.
It returns the array of rewrite rules as in rewrite\_rules(), but using $matches[xxx] in the (where xxx is a number) instead of the normal mod\_rewrite backreferences, $xxx (where xxx is a number). This is useful when you’re going to be using the rules inside PHP, rather than writing them out to a .htaccess file.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function wp_rewrite_rules() {
$this->rules = get_option( 'rewrite_rules' );
if ( empty( $this->rules ) ) {
$this->matches = 'matches';
$this->rewrite_rules();
if ( ! did_action( 'wp_loaded' ) ) {
add_action( 'wp_loaded', array( $this, 'flush_rules' ) );
return $this->rules;
}
update_option( 'rewrite_rules', $this->rules );
}
return $this->rules;
}
```
| Uses | Description |
| --- | --- |
| [did\_action()](../../functions/did_action) wp-includes/plugin.php | Retrieves the number of times an action has been fired during the current request. |
| [WP\_Rewrite::rewrite\_rules()](rewrite_rules) wp-includes/class-wp-rewrite.php | Constructs rewrite matches and queries from permalink structure. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP::parse\_request()](../wp/parse_request) wp-includes/class-wp.php | Parses the request to find the correct WordPress query. |
| [WP\_Rewrite::flush\_rules()](flush_rules) wp-includes/class-wp-rewrite.php | Removes rewrite rules and then recreate rewrite rules. |
| [url\_to\_postid()](../../functions/url_to_postid) wp-includes/rewrite.php | Examines a URL and try to determine the post ID it represents. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::__construct() WP\_Rewrite::\_\_construct()
============================
Constructor – Calls [init()](../../functions/init) , which runs setup.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function __construct() {
$this->init();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::init()](init) wp-includes/class-wp-rewrite.php | Sets up the object’s properties. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::get_extra_permastruct( string $name ): string|false WP\_Rewrite::get\_extra\_permastruct( string $name ): string|false
==================================================================
Retrieves an extra permalink structure by name.
`$name` string Required Permalink structure name. string|false Permalink structure string on success, false on failure.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function get_extra_permastruct( $name ) {
if ( empty( $this->permalink_structure ) ) {
return false;
}
if ( isset( $this->extra_permastructs[ $name ] ) ) {
return $this->extra_permastructs[ $name ]['struct'];
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [get\_term\_link()](../../functions/get_term_link) wp-includes/taxonomy.php | Generates a permalink for a taxonomy term archive. |
| [get\_post\_permalink()](../../functions/get_post_permalink) wp-includes/link-template.php | Retrieves the permalink for a post of a custom post type. |
| [WP\_Rewrite::get\_category\_permastruct()](get_category_permastruct) wp-includes/class-wp-rewrite.php | Retrieves the permalink structure for categories. |
| [WP\_Rewrite::get\_tag\_permastruct()](get_tag_permastruct) wp-includes/class-wp-rewrite.php | Retrieves the permalink structure for tags. |
| [\_post\_format\_link()](../../functions/_post_format_link) wp-includes/post-formats.php | Filters the post format term link to remove the format prefix. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress WP_Rewrite::remove_permastruct( string $name ) WP\_Rewrite::remove\_permastruct( string $name )
================================================
Removes a permalink structure.
`$name` string Required Name for permalink structure. File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function remove_permastruct( $name ) {
unset( $this->extra_permastructs[ $name ] );
}
```
| Used By | Description |
| --- | --- |
| [remove\_permastruct()](../../functions/remove_permastruct) wp-includes/rewrite.php | Removes a permalink structure. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Rewrite::get_day_permastruct(): string|false WP\_Rewrite::get\_day\_permastruct(): string|false
==================================================
Retrieves the day permalink structure with month and year.
Keeps date permalink structure with all year, month, and day.
string|false Year/Month/Day permalink structure on success, false on failure.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function get_day_permastruct() {
return $this->get_date_permastruct();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::get\_date\_permastruct()](get_date_permastruct) wp-includes/class-wp-rewrite.php | Retrieves date permalink structure, with year, month, and day. |
| Used By | Description |
| --- | --- |
| [get\_day\_link()](../../functions/get_day_link) wp-includes/link-template.php | Retrieves the permalink for the day archives with year and month. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::get_year_permastruct(): string|false WP\_Rewrite::get\_year\_permastruct(): string|false
===================================================
Retrieves the year permalink structure without month and day.
Gets the date permalink structure and strips out the month and day permalink structures.
string|false Year permalink structure on success, false on failure.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function get_year_permastruct() {
$structure = $this->get_date_permastruct();
if ( empty( $structure ) ) {
return false;
}
$structure = str_replace( '%monthnum%', '', $structure );
$structure = str_replace( '%day%', '', $structure );
$structure = preg_replace( '#/+#', '/', $structure );
return $structure;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::get\_date\_permastruct()](get_date_permastruct) wp-includes/class-wp-rewrite.php | Retrieves date permalink structure, with year, month, and day. |
| Used By | Description |
| --- | --- |
| [get\_year\_link()](../../functions/get_year_link) wp-includes/link-template.php | Retrieves the permalink for the year archives. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Rewrite::get_search_permastruct(): string|false WP\_Rewrite::get\_search\_permastruct(): string|false
=====================================================
Retrieves the search permalink structure.
The permalink structure is root property, search base, and finally ‘/%search%’. Will set the search\_structure property and then return it without attempting to set the value again.
string|false Search permalink structure on success, false on failure.
File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/)
```
public function get_search_permastruct() {
if ( isset( $this->search_structure ) ) {
return $this->search_structure;
}
if ( empty( $this->permalink_structure ) ) {
$this->search_structure = '';
return false;
}
$this->search_structure = $this->root . $this->search_base . '/%search%';
return $this->search_structure;
}
```
| Used By | Description |
| --- | --- |
| [get\_search\_comments\_feed\_link()](../../functions/get_search_comments_feed_link) wp-includes/link-template.php | Retrieves the permalink for the search results comments feed. |
| [get\_search\_link()](../../functions/get_search_link) wp-includes/link-template.php | Retrieves the permalink for a search. |
| [get\_search\_feed\_link()](../../functions/get_search_feed_link) wp-includes/link-template.php | Retrieves the permalink for the search results feed. |
| [WP\_Rewrite::rewrite\_rules()](rewrite_rules) wp-includes/class-wp-rewrite.php | Constructs rewrite matches and queries from permalink structure. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Post_Comments_List_Table::get_per_page( bool $comment_status = false ): int WP\_Post\_Comments\_List\_Table::get\_per\_page( bool $comment\_status = false ): int
=====================================================================================
`$comment_status` bool Optional Default: `false`
int
File: `wp-admin/includes/class-wp-post-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-post-comments-list-table.php/)
```
public function get_per_page( $comment_status = false ) {
return 10;
}
```
wordpress WP_Post_Comments_List_Table::display( bool $output_empty = false ) WP\_Post\_Comments\_List\_Table::display( bool $output\_empty = false )
=======================================================================
`$output_empty` bool Optional Default: `false`
File: `wp-admin/includes/class-wp-post-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-post-comments-list-table.php/)
```
public function display( $output_empty = false ) {
$singular = $this->_args['singular'];
wp_nonce_field( 'fetch-list-' . get_class( $this ), '_ajax_fetch_list_nonce' );
?>
<table class="<?php echo implode( ' ', $this->get_table_classes() ); ?>" style="display:none;">
<tbody id="the-comment-list"
<?php
if ( $singular ) {
echo " data-wp-lists='list:$singular'";
}
?>
>
<?php
if ( ! $output_empty ) {
$this->display_rows_or_placeholder();
}
?>
</tbody>
</table>
<?php
}
```
| Uses | Description |
| --- | --- |
| [WP\_Post\_Comments\_List\_Table::get\_table\_classes()](get_table_classes) wp-admin/includes/class-wp-post-comments-list-table.php | |
| [wp\_nonce\_field()](../../functions/wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
wordpress WP_Post_Comments_List_Table::get_table_classes(): array WP\_Post\_Comments\_List\_Table::get\_table\_classes(): array
=============================================================
array
File: `wp-admin/includes/class-wp-post-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-post-comments-list-table.php/)
```
protected function get_table_classes() {
$classes = parent::get_table_classes();
$classes[] = 'wp-list-table';
$classes[] = 'comments-box';
return $classes;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Post\_Comments\_List\_Table::display()](display) wp-admin/includes/class-wp-post-comments-list-table.php | |
wordpress WP_Post_Comments_List_Table::get_column_info(): array WP\_Post\_Comments\_List\_Table::get\_column\_info(): array
===========================================================
array
File: `wp-admin/includes/class-wp-post-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-post-comments-list-table.php/)
```
protected function get_column_info() {
return array(
array(
'author' => __( 'Author' ),
'comment' => _x( 'Comment', 'column name' ),
),
array(),
array(),
'comment',
);
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
wordpress WP_Embed::find_oembed_post_id( string $cache_key ): int|null WP\_Embed::find\_oembed\_post\_id( string $cache\_key ): int|null
=================================================================
Finds the oEmbed cache post ID for a given cache key.
`$cache_key` string Required oEmbed cache key. int|null Post ID on success, null on failure.
File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/)
```
public function find_oembed_post_id( $cache_key ) {
$cache_group = 'oembed_cache_post';
$oembed_post_id = wp_cache_get( $cache_key, $cache_group );
if ( $oembed_post_id && 'oembed_cache' === get_post_type( $oembed_post_id ) ) {
return $oembed_post_id;
}
$oembed_post_query = new WP_Query(
array(
'post_type' => 'oembed_cache',
'post_status' => 'publish',
'name' => $cache_key,
'posts_per_page' => 1,
'no_found_rows' => true,
'cache_results' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'lazy_load_term_meta' => false,
)
);
if ( ! empty( $oembed_post_query->posts ) ) {
// Note: 'fields' => 'ids' is not being used in order to cache the post object as it will be needed.
$oembed_post_id = $oembed_post_query->posts[0]->ID;
wp_cache_set( $cache_key, $oembed_post_id, $cache_group );
return $oembed_post_id;
}
return null;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Query::\_\_construct()](../wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [wp\_cache\_set()](../../functions/wp_cache_set) wp-includes/cache.php | Saves the data to the cache. |
| [get\_post\_type()](../../functions/get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| [wp\_cache\_get()](../../functions/wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| Used By | Description |
| --- | --- |
| [WP\_Embed::shortcode()](shortcode) wp-includes/class-wp-embed.php | The [do\_shortcode()](../../functions/do_shortcode) callback function. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Embed::get_embed_handler_html( array $attr, string $url ): string|false WP\_Embed::get\_embed\_handler\_html( array $attr, string $url ): string|false
==============================================================================
Returns embed HTML for a given URL from embed handlers.
Attempts to convert a URL into embed HTML by checking the URL against the regex of the registered embed handlers.
`$attr` array Required Shortcode attributes. Optional.
* `width`intWidth of the embed in pixels.
* `height`intHeight of the embed in pixels.
`$url` string Required The URL attempting to be embedded. string|false The embed HTML on success, false otherwise.
File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/)
```
public function get_embed_handler_html( $attr, $url ) {
$rawattr = $attr;
$attr = wp_parse_args( $attr, wp_embed_defaults( $url ) );
ksort( $this->handlers );
foreach ( $this->handlers as $priority => $handlers ) {
foreach ( $handlers as $id => $handler ) {
if ( preg_match( $handler['regex'], $url, $matches ) && is_callable( $handler['callback'] ) ) {
$return = call_user_func( $handler['callback'], $matches, $attr, $url, $rawattr );
if ( false !== $return ) {
/**
* Filters the returned embed HTML.
*
* @since 2.9.0
*
* @see WP_Embed::shortcode()
*
* @param string|false $return The HTML result of the shortcode, or false on failure.
* @param string $url The embed URL.
* @param array $attr An array of shortcode attributes.
*/
return apply_filters( 'embed_handler_html', $return, $url, $attr );
}
}
}
}
return false;
}
```
[apply\_filters( 'embed\_handler\_html', string|false $return, string $url, array $attr )](../../hooks/embed_handler_html)
Filters the returned embed HTML.
| Uses | Description |
| --- | --- |
| [wp\_embed\_defaults()](../../functions/wp_embed_defaults) wp-includes/embed.php | Creates default array of embed parameters. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_oEmbed\_Controller::get\_proxy\_item()](../wp_oembed_controller/get_proxy_item) wp-includes/class-wp-oembed-controller.php | Callback for the proxy API endpoint. |
| [WP\_Embed::shortcode()](shortcode) wp-includes/class-wp-embed.php | The [do\_shortcode()](../../functions/do_shortcode) callback function. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Embed::autoembed( string $content ): string WP\_Embed::autoembed( string $content ): string
===============================================
Passes any unlinked URLs that are on their own line to [WP\_Embed::shortcode()](shortcode) for potential embedding.
* [WP\_Embed::autoembed\_callback()](../wp_embed/autoembed_callback)
`$content` string Required The content to be searched. string Potentially modified $content.
File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/)
```
public function autoembed( $content ) {
// Replace line breaks from all HTML elements with placeholders.
$content = wp_replace_in_html_tags( $content, array( "\n" => '<!-- wp-line-break -->' ) );
if ( preg_match( '#(^|\s|>)https?://#i', $content ) ) {
// Find URLs on their own line.
$content = preg_replace_callback( '|^(\s*)(https?://[^\s<>"]+)(\s*)$|im', array( $this, 'autoembed_callback' ), $content );
// Find URLs in their own paragraph.
$content = preg_replace_callback( '|(<p(?: [^>]*)?>\s*)(https?://[^\s<>"]+)(\s*<\/p>)|i', array( $this, 'autoembed_callback' ), $content );
}
// Put the line breaks back.
return str_replace( '<!-- wp-line-break -->', "\n", $content );
}
```
| Uses | Description |
| --- | --- |
| [wp\_replace\_in\_html\_tags()](../../functions/wp_replace_in_html_tags) wp-includes/formatting.php | Replaces characters or phrases within HTML elements only. |
| Used By | Description |
| --- | --- |
| [get\_the\_block\_template\_html()](../../functions/get_the_block_template_html) wp-includes/block-template.php | Returns the markup for the current template. |
| [wp\_embed\_handler\_youtube()](../../functions/wp_embed_handler_youtube) wp-includes/embed.php | YouTube iframe embed handler callback. |
| [WP\_Embed::cache\_oembed()](cache_oembed) wp-includes/class-wp-embed.php | Triggers a caching of all oEmbed results. |
wordpress WP_Embed::maybe_run_ajax_cache() WP\_Embed::maybe\_run\_ajax\_cache()
====================================
If a post/page was saved, then output JavaScript to make an Ajax request that will call [WP\_Embed::cache\_oembed()](cache_oembed).
File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/)
```
public function maybe_run_ajax_cache() {
$post = get_post();
if ( ! $post || empty( $_GET['message'] ) ) {
return;
}
?>
<script type="text/javascript">
jQuery( function($) {
$.get("<?php echo esc_url( admin_url( 'admin-ajax.php', 'relative' ) ) . '?action=oembed-cache&post=' . $post->ID; ?>");
} );
</script>
<?php
}
```
| Uses | Description |
| --- | --- |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
wordpress WP_Embed::autoembed_callback( array $matches ): string WP\_Embed::autoembed\_callback( array $matches ): string
========================================================
Callback function for [WP\_Embed::autoembed()](autoembed).
`$matches` array Required A regex match array. string The embed HTML on success, otherwise the original URL.
File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/)
```
public function autoembed_callback( $matches ) {
$oldval = $this->linkifunknown;
$this->linkifunknown = false;
$return = $this->shortcode( array(), $matches[2] );
$this->linkifunknown = $oldval;
return $matches[1] . $return . $matches[3];
}
```
| Uses | Description |
| --- | --- |
| [WP\_Embed::shortcode()](shortcode) wp-includes/class-wp-embed.php | The [do\_shortcode()](../../functions/do_shortcode) callback function. |
wordpress WP_Embed::delete_oembed_caches( int $post_ID ) WP\_Embed::delete\_oembed\_caches( int $post\_ID )
==================================================
Deletes all oEmbed caches. Unused by core as of 4.0.0.
`$post_ID` int Required Post ID to delete the caches for. File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/)
```
public function delete_oembed_caches( $post_ID ) {
$post_metas = get_post_custom_keys( $post_ID );
if ( empty( $post_metas ) ) {
return;
}
foreach ( $post_metas as $post_meta_key ) {
if ( '_oembed_' === substr( $post_meta_key, 0, 8 ) ) {
delete_post_meta( $post_ID, $post_meta_key );
}
}
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_custom\_keys()](../../functions/get_post_custom_keys) wp-includes/post.php | Retrieves meta field names for a post. |
| [delete\_post\_meta()](../../functions/delete_post_meta) wp-includes/post.php | Deletes a post meta field for the given post ID. |
wordpress WP_Embed::cache_oembed( int $post_ID ) WP\_Embed::cache\_oembed( int $post\_ID )
=========================================
Triggers a caching of all oEmbed results.
`$post_ID` int Required Post ID to do the caching for. File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/)
```
public function cache_oembed( $post_ID ) {
$post = get_post( $post_ID );
$post_types = get_post_types( array( 'show_ui' => true ) );
/**
* Filters the array of post types to cache oEmbed results for.
*
* @since 2.9.0
*
* @param string[] $post_types Array of post type names to cache oEmbed results for. Defaults to post types with `show_ui` set to true.
*/
$cache_oembed_types = apply_filters( 'embed_cache_oembed_types', $post_types );
if ( empty( $post->ID ) || ! in_array( $post->post_type, $cache_oembed_types, true ) ) {
return;
}
// Trigger a caching.
if ( ! empty( $post->post_content ) ) {
$this->post_ID = $post->ID;
$this->usecache = false;
$content = $this->run_shortcode( $post->post_content );
$this->autoembed( $content );
$this->usecache = true;
}
}
```
[apply\_filters( 'embed\_cache\_oembed\_types', string[] $post\_types )](../../hooks/embed_cache_oembed_types)
Filters the array of post types to cache oEmbed results for.
| Uses | Description |
| --- | --- |
| [WP\_Embed::autoembed()](autoembed) wp-includes/class-wp-embed.php | Passes any unlinked URLs that are on their own line to [WP\_Embed::shortcode()](shortcode) for potential embedding. |
| [WP\_Embed::run\_shortcode()](run_shortcode) wp-includes/class-wp-embed.php | Processes the [embed] shortcode. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [get\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| programming_docs |
wordpress WP_Embed::run_shortcode( string $content ): string WP\_Embed::run\_shortcode( string $content ): string
====================================================
Processes the [embed] shortcode.
Since the shortcode needs to be run earlier than other shortcodes, this function removes all existing shortcodes, registers the shortcode, calls [do\_shortcode()](../../functions/do_shortcode) , and then re-registers the old shortcodes.
`$content` string Required Content to parse. string Content with shortcode parsed.
File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/)
```
public function run_shortcode( $content ) {
global $shortcode_tags;
// Back up current registered shortcodes and clear them all out.
$orig_shortcode_tags = $shortcode_tags;
remove_all_shortcodes();
add_shortcode( 'embed', array( $this, 'shortcode' ) );
// Do the shortcode (only the [embed] one is registered).
$content = do_shortcode( $content, true );
// Put the original shortcodes back.
$shortcode_tags = $orig_shortcode_tags;
return $content;
}
```
| Uses | Description |
| --- | --- |
| [do\_shortcode()](../../functions/do_shortcode) wp-includes/shortcodes.php | Searches content for shortcodes and filter shortcodes through their hooks. |
| [remove\_all\_shortcodes()](../../functions/remove_all_shortcodes) wp-includes/shortcodes.php | Clears all shortcodes. |
| [add\_shortcode()](../../functions/add_shortcode) wp-includes/shortcodes.php | Adds a new shortcode. |
| Used By | Description |
| --- | --- |
| [get\_the\_block\_template\_html()](../../functions/get_the_block_template_html) wp-includes/block-template.php | Returns the markup for the current template. |
| [wp\_ajax\_parse\_embed()](../../functions/wp_ajax_parse_embed) wp-admin/includes/ajax-actions.php | Apply [embed] Ajax handlers to a string. |
| [wp\_ajax\_send\_link\_to\_editor()](../../functions/wp_ajax_send_link_to_editor) wp-admin/includes/ajax-actions.php | Ajax handler for sending a link to the editor. |
| [WP\_Embed::cache\_oembed()](cache_oembed) wp-includes/class-wp-embed.php | Triggers a caching of all oEmbed results. |
wordpress WP_Embed::__construct() WP\_Embed::\_\_construct()
==========================
Constructor
File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/)
```
public function __construct() {
// Hack to get the [embed] shortcode to run before wpautop().
add_filter( 'the_content', array( $this, 'run_shortcode' ), 8 );
add_filter( 'widget_text_content', array( $this, 'run_shortcode' ), 8 );
add_filter( 'widget_block_content', array( $this, 'run_shortcode' ), 8 );
// Shortcode placeholder for strip_shortcodes().
add_shortcode( 'embed', '__return_false' );
// Attempts to embed all URLs in a post.
add_filter( 'the_content', array( $this, 'autoembed' ), 8 );
add_filter( 'widget_text_content', array( $this, 'autoembed' ), 8 );
add_filter( 'widget_block_content', array( $this, 'autoembed' ), 8 );
// After a post is saved, cache oEmbed items via Ajax.
add_action( 'edit_form_advanced', array( $this, 'maybe_run_ajax_cache' ) );
add_action( 'edit_page_form', array( $this, 'maybe_run_ajax_cache' ) );
}
```
| Uses | Description |
| --- | --- |
| [add\_shortcode()](../../functions/add_shortcode) wp-includes/shortcodes.php | Adds a new shortcode. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
wordpress WP_Embed::unregister_handler( string $id, int $priority = 10 ) WP\_Embed::unregister\_handler( string $id, int $priority = 10 )
================================================================
Unregisters a previously-registered embed handler.
Do not use this function directly, use [wp\_embed\_unregister\_handler()](../../functions/wp_embed_unregister_handler) instead.
`$id` string Required The handler ID that should be removed. `$priority` int Optional The priority of the handler to be removed (default: 10). Default: `10`
File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/)
```
public function unregister_handler( $id, $priority = 10 ) {
unset( $this->handlers[ $priority ][ $id ] );
}
```
| Used By | Description |
| --- | --- |
| [wp\_embed\_unregister\_handler()](../../functions/wp_embed_unregister_handler) wp-includes/embed.php | Unregisters a previously-registered embed handler. |
wordpress WP_Embed::maybe_make_link( string $url ): string|false WP\_Embed::maybe\_make\_link( string $url ): string|false
=========================================================
Conditionally makes a hyperlink based on an internal class variable.
`$url` string Required URL to potentially be linked. string|false Linked URL or the original URL. False if `'return_false_on_fail'` is true.
File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/)
```
public function maybe_make_link( $url ) {
if ( $this->return_false_on_fail ) {
return false;
}
$output = ( $this->linkifunknown ) ? '<a href="' . esc_url( $url ) . '">' . esc_html( $url ) . '</a>' : $url;
/**
* Filters the returned, maybe-linked embed URL.
*
* @since 2.9.0
*
* @param string $output The linked or original URL.
* @param string $url The original URL.
*/
return apply_filters( 'embed_maybe_make_link', $output, $url );
}
```
[apply\_filters( 'embed\_maybe\_make\_link', string $output, string $url )](../../hooks/embed_maybe_make_link)
Filters the returned, maybe-linked embed URL.
| Uses | Description |
| --- | --- |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_ajax\_send\_link\_to\_editor()](../../functions/wp_ajax_send_link_to_editor) wp-admin/includes/ajax-actions.php | Ajax handler for sending a link to the editor. |
| [WP\_Embed::shortcode()](shortcode) wp-includes/class-wp-embed.php | The [do\_shortcode()](../../functions/do_shortcode) callback function. |
wordpress WP_Embed::shortcode( array $attr, string $url = '' ): string|false WP\_Embed::shortcode( array $attr, string $url = '' ): string|false
===================================================================
The [do\_shortcode()](../../functions/do_shortcode) callback function.
Attempts to convert a URL into embed HTML. Starts by checking the URL against the regex of the registered embed handlers. If none of the regex matches and it’s enabled, then the URL will be given to the [WP\_oEmbed](../wp_oembed) class.
`$attr` array Required Shortcode attributes. Optional.
* `width`intWidth of the embed in pixels.
* `height`intHeight of the embed in pixels.
`$url` string Optional The URL attempting to be embedded. Default: `''`
string|false The embed HTML on success, otherwise the original URL.
`->maybe_make_link()` can return false on failure.
File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/)
```
public function shortcode( $attr, $url = '' ) {
$post = get_post();
if ( empty( $url ) && ! empty( $attr['src'] ) ) {
$url = $attr['src'];
}
$this->last_url = $url;
if ( empty( $url ) ) {
$this->last_attr = $attr;
return '';
}
$rawattr = $attr;
$attr = wp_parse_args( $attr, wp_embed_defaults( $url ) );
$this->last_attr = $attr;
// KSES converts & into & and we need to undo this.
// See https://core.trac.wordpress.org/ticket/11311
$url = str_replace( '&', '&', $url );
// Look for known internal handlers.
$embed_handler_html = $this->get_embed_handler_html( $rawattr, $url );
if ( false !== $embed_handler_html ) {
return $embed_handler_html;
}
$post_ID = ( ! empty( $post->ID ) ) ? $post->ID : null;
// Potentially set by WP_Embed::cache_oembed().
if ( ! empty( $this->post_ID ) ) {
$post_ID = $this->post_ID;
}
// Check for a cached result (stored as custom post or in the post meta).
$key_suffix = md5( $url . serialize( $attr ) );
$cachekey = '_oembed_' . $key_suffix;
$cachekey_time = '_oembed_time_' . $key_suffix;
/**
* Filters the oEmbed TTL value (time to live).
*
* @since 4.0.0
*
* @param int $time Time to live (in seconds).
* @param string $url The attempted embed URL.
* @param array $attr An array of shortcode attributes.
* @param int $post_ID Post ID.
*/
$ttl = apply_filters( 'oembed_ttl', DAY_IN_SECONDS, $url, $attr, $post_ID );
$cache = '';
$cache_time = 0;
$cached_post_id = $this->find_oembed_post_id( $key_suffix );
if ( $post_ID ) {
$cache = get_post_meta( $post_ID, $cachekey, true );
$cache_time = get_post_meta( $post_ID, $cachekey_time, true );
if ( ! $cache_time ) {
$cache_time = 0;
}
} elseif ( $cached_post_id ) {
$cached_post = get_post( $cached_post_id );
$cache = $cached_post->post_content;
$cache_time = strtotime( $cached_post->post_modified_gmt );
}
$cached_recently = ( time() - $cache_time ) < $ttl;
if ( $this->usecache || $cached_recently ) {
// Failures are cached. Serve one if we're using the cache.
if ( '{{unknown}}' === $cache ) {
return $this->maybe_make_link( $url );
}
if ( ! empty( $cache ) ) {
/**
* Filters the cached oEmbed HTML.
*
* @since 2.9.0
*
* @see WP_Embed::shortcode()
*
* @param string|false $cache The cached HTML result, stored in post meta.
* @param string $url The attempted embed URL.
* @param array $attr An array of shortcode attributes.
* @param int $post_ID Post ID.
*/
return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_ID );
}
}
/**
* Filters whether to inspect the given URL for discoverable link tags.
*
* @since 2.9.0
* @since 4.4.0 The default value changed to true.
*
* @see WP_oEmbed::discover()
*
* @param bool $enable Whether to enable `<link>` tag discovery. Default true.
*/
$attr['discover'] = apply_filters( 'embed_oembed_discover', true );
// Use oEmbed to get the HTML.
$html = wp_oembed_get( $url, $attr );
if ( $post_ID ) {
if ( $html ) {
update_post_meta( $post_ID, $cachekey, $html );
update_post_meta( $post_ID, $cachekey_time, time() );
} elseif ( ! $cache ) {
update_post_meta( $post_ID, $cachekey, '{{unknown}}' );
}
} else {
$has_kses = false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' );
if ( $has_kses ) {
// Prevent KSES from corrupting JSON in post_content.
kses_remove_filters();
}
$insert_post_args = array(
'post_name' => $key_suffix,
'post_status' => 'publish',
'post_type' => 'oembed_cache',
);
if ( $html ) {
if ( $cached_post_id ) {
wp_update_post(
wp_slash(
array(
'ID' => $cached_post_id,
'post_content' => $html,
)
)
);
} else {
wp_insert_post(
wp_slash(
array_merge(
$insert_post_args,
array(
'post_content' => $html,
)
)
)
);
}
} elseif ( ! $cache ) {
wp_insert_post(
wp_slash(
array_merge(
$insert_post_args,
array(
'post_content' => '{{unknown}}',
)
)
)
);
}
if ( $has_kses ) {
kses_init_filters();
}
}
// If there was a result, return it.
if ( $html ) {
/** This filter is documented in wp-includes/class-wp-embed.php */
return apply_filters( 'embed_oembed_html', $html, $url, $attr, $post_ID );
}
// Still unknown.
return $this->maybe_make_link( $url );
}
```
[apply\_filters( 'embed\_oembed\_discover', bool $enable )](../../hooks/embed_oembed_discover)
Filters whether to inspect the given URL for discoverable link tags.
[apply\_filters( 'embed\_oembed\_html', string|false $cache, string $url, array $attr, int $post\_ID )](../../hooks/embed_oembed_html)
Filters the cached oEmbed HTML.
[apply\_filters( 'oembed\_ttl', int $time, string $url, array $attr, int $post\_ID )](../../hooks/oembed_ttl)
Filters the oEmbed TTL value (time to live).
| Uses | Description |
| --- | --- |
| [WP\_Embed::get\_embed\_handler\_html()](get_embed_handler_html) wp-includes/class-wp-embed.php | Returns embed HTML for a given URL from embed handlers. |
| [WP\_Embed::find\_oembed\_post\_id()](find_oembed_post_id) wp-includes/class-wp-embed.php | Finds the oEmbed cache post ID for a given cache key. |
| [kses\_remove\_filters()](../../functions/kses_remove_filters) wp-includes/kses.php | Removes all KSES input form content filters. |
| [kses\_init\_filters()](../../functions/kses_init_filters) wp-includes/kses.php | Adds all KSES input form content filters. |
| [WP\_Embed::maybe\_make\_link()](maybe_make_link) wp-includes/class-wp-embed.php | Conditionally makes a hyperlink based on an internal class variable. |
| [has\_filter()](../../functions/has_filter) wp-includes/plugin.php | Checks if any filter has been registered for a hook. |
| [wp\_embed\_defaults()](../../functions/wp_embed_defaults) wp-includes/embed.php | Creates default array of embed parameters. |
| [wp\_oembed\_get()](../../functions/wp_oembed_get) wp-includes/embed.php | Attempts to fetch the embed HTML for a provided URL using oEmbed. |
| [wp\_update\_post()](../../functions/wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post\_meta()](../../functions/get_post_meta) wp-includes/post.php | Retrieves a post meta field for the given post ID. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [WP\_Embed::autoembed\_callback()](autoembed_callback) wp-includes/class-wp-embed.php | Callback function for [WP\_Embed::autoembed()](autoembed). |
wordpress WP_Embed::register_handler( string $id, string $regex, callable $callback, int $priority = 10 ) WP\_Embed::register\_handler( string $id, string $regex, callable $callback, int $priority = 10 )
=================================================================================================
Registers an embed handler.
Do not use this function directly, use [wp\_embed\_register\_handler()](../../functions/wp_embed_register_handler) instead.
This function should probably also only be used for sites that do not support oEmbed.
`$id` string Required An internal ID/name for the handler. Needs to be unique. `$regex` string Required The regex that will be used to see if this handler should be used for a URL. `$callback` callable Required The callback function that will be called if the regex is matched. `$priority` int Optional Used to specify the order in which the registered handlers will be tested.
Lower numbers correspond with earlier testing, and handlers with the same priority are tested in the order in which they were added to the action. Default: `10`
File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/)
```
public function register_handler( $id, $regex, $callback, $priority = 10 ) {
$this->handlers[ $priority ][ $id ] = array(
'regex' => $regex,
'callback' => $callback,
);
}
```
| Used By | Description |
| --- | --- |
| [wp\_embed\_register\_handler()](../../functions/wp_embed_register_handler) wp-includes/embed.php | Registers an embed handler. |
wordpress WP_Block_Type_Registry::register( string|WP_Block_Type $name, array $args = array() ): WP_Block_Type|false WP\_Block\_Type\_Registry::register( string|WP\_Block\_Type $name, array $args = array() ): WP\_Block\_Type|false
=================================================================================================================
Registers a block type.
* [WP\_Block\_Type::\_\_construct()](../wp_block_type/__construct)
`$name` string|[WP\_Block\_Type](../wp_block_type) Required Block type name including namespace, or alternatively a complete [WP\_Block\_Type](../wp_block_type) instance. In case a [WP\_Block\_Type](../wp_block_type) is provided, the $args parameter will be ignored. `$args` array Optional Array of block type arguments. Accepts any public property of `WP_Block_Type`. See [WP\_Block\_Type::\_\_construct()](../wp_block_type/__construct) for information on accepted arguments. More Arguments from WP\_Block\_Type::\_\_construct( ... $args ) Array or string of arguments for registering a block type. Any arguments may be defined, however the ones described below are supported by default.
* `api_version`stringBlock API version.
* `title`stringHuman-readable block type label.
* `category`string|nullBlock type category classification, used in search interfaces to arrange block types by category.
* `parent`string[]|nullSetting parent lets a block require that it is only available when nested within the specified blocks.
* `ancestor`string[]|nullSetting ancestor makes a block available only inside the specified block types at any position of the ancestor's block subtree.
* `icon`string|nullBlock type icon.
* `description`stringA detailed block type description.
* `keywords`string[]Additional keywords to produce block type as result in search interfaces.
* `textdomain`string|nullThe translation textdomain.
* `styles`array[]Alternative block styles.
* `variations`array[]Block variations.
* `supports`array|nullSupported features.
* `example`array|nullStructured data for the block preview.
* `render_callback`callable|nullBlock type render callback.
* `attributes`array|nullBlock type attributes property schemas.
* `uses_context`string[]Context values inherited by blocks of this type.
* `provides_context`string[]|nullContext provided by blocks of this type.
* `editor_script_handles`string[]Block type editor only script handles.
* `script_handles`string[]Block type front end and editor script handles.
* `view_script_handles`string[]Block type front end only script handles.
* `editor_style_handles`string[]Block type editor only style handles.
* `style_handles`string[]Block type front end and editor style handles.
Default: `array()`
[WP\_Block\_Type](../wp_block_type)|false The registered block type on success, or false on failure.
File: `wp-includes/class-wp-block-type-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type-registry.php/)
```
public function register( $name, $args = array() ) {
$block_type = null;
if ( $name instanceof WP_Block_Type ) {
$block_type = $name;
$name = $block_type->name;
}
if ( ! is_string( $name ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Block type names must be strings.' ),
'5.0.0'
);
return false;
}
if ( preg_match( '/[A-Z]+/', $name ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Block type names must not contain uppercase characters.' ),
'5.0.0'
);
return false;
}
$name_matcher = '/^[a-z0-9-]+\/[a-z0-9-]+$/';
if ( ! preg_match( $name_matcher, $name ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Block type names must contain a namespace prefix. Example: my-plugin/my-custom-block-type' ),
'5.0.0'
);
return false;
}
if ( $this->is_registered( $name ) ) {
_doing_it_wrong(
__METHOD__,
/* translators: %s: Block name. */
sprintf( __( 'Block type "%s" is already registered.' ), $name ),
'5.0.0'
);
return false;
}
if ( ! $block_type ) {
$block_type = new WP_Block_Type( $name, $args );
}
$this->registered_block_types[ $name ] = $block_type;
return $block_type;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_Type\_Registry::is\_registered()](is_registered) wp-includes/class-wp-block-type-registry.php | Checks if a block type is registered. |
| [WP\_Block\_Type::\_\_construct()](../wp_block_type/__construct) wp-includes/class-wp-block-type.php | Constructor. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](../../functions/_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
| programming_docs |
wordpress WP_Block_Type_Registry::unregister( string|WP_Block_Type $name ): WP_Block_Type|false WP\_Block\_Type\_Registry::unregister( string|WP\_Block\_Type $name ): WP\_Block\_Type|false
============================================================================================
Unregisters a block type.
`$name` string|[WP\_Block\_Type](../wp_block_type) Required Block type name including namespace, or alternatively a complete [WP\_Block\_Type](../wp_block_type) instance. [WP\_Block\_Type](../wp_block_type)|false The unregistered block type on success, or false on failure.
File: `wp-includes/class-wp-block-type-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type-registry.php/)
```
public function unregister( $name ) {
if ( $name instanceof WP_Block_Type ) {
$name = $name->name;
}
if ( ! $this->is_registered( $name ) ) {
_doing_it_wrong(
__METHOD__,
/* translators: %s: Block name. */
sprintf( __( 'Block type "%s" is not registered.' ), $name ),
'5.0.0'
);
return false;
}
$unregistered_block_type = $this->registered_block_types[ $name ];
unset( $this->registered_block_types[ $name ] );
return $unregistered_block_type;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_Type\_Registry::is\_registered()](is_registered) wp-includes/class-wp-block-type-registry.php | Checks if a block type is registered. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](../../functions/_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_Block_Type_Registry::get_registered( string $name ): WP_Block_Type|null WP\_Block\_Type\_Registry::get\_registered( string $name ): WP\_Block\_Type|null
================================================================================
Retrieves a registered block type.
`$name` string Required Block type name including namespace. [WP\_Block\_Type](../wp_block_type)|null The registered block type, or null if it is not registered.
File: `wp-includes/class-wp-block-type-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type-registry.php/)
```
public function get_registered( $name ) {
if ( ! $this->is_registered( $name ) ) {
return null;
}
return $this->registered_block_types[ $name ];
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_Type\_Registry::is\_registered()](is_registered) wp-includes/class-wp-block-type-registry.php | Checks if a block type is registered. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_Block_Type_Registry::get_all_registered(): WP_Block_Type[] WP\_Block\_Type\_Registry::get\_all\_registered(): WP\_Block\_Type[]
====================================================================
Retrieves all registered block types.
[WP\_Block\_Type](../wp_block_type)[] Associative array of `$block_type_name => $block_type` pairs.
File: `wp-includes/class-wp-block-type-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type-registry.php/)
```
public function get_all_registered() {
return $this->registered_block_types;
}
```
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_Block_Type_Registry::get_instance(): WP_Block_Type_Registry WP\_Block\_Type\_Registry::get\_instance(): WP\_Block\_Type\_Registry
=====================================================================
Utility method to retrieve the main instance of the class.
The instance will be created if it does not exist yet.
[WP\_Block\_Type\_Registry](../wp_block_type_registry) The main instance.
File: `wp-includes/class-wp-block-type-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type-registry.php/)
```
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Theme\_JSON::get\_layout\_styles()](../wp_theme_json/get_layout_styles) wp-includes/class-wp-theme-json.php | Gets the CSS layout rules for a particular block from theme.json layout definitions. |
| [WP\_Theme\_JSON\_Resolver::get\_block\_data()](../wp_theme_json_resolver/get_block_data) wp-includes/class-wp-theme-json-resolver.php | Gets the styles for blocks from the block.json file. |
| [WP\_Theme\_JSON\_Resolver::has\_same\_registered\_blocks()](../wp_theme_json_resolver/has_same_registered_blocks) wp-includes/class-wp-theme-json-resolver.php | Checks whether the registered blocks were already processed for this origin. |
| [\_wp\_get\_iframed\_editor\_assets()](../../functions/_wp_get_iframed_editor_assets) wp-includes/block-editor.php | Collect the block editor assets that need to be loaded into the editor’s iframe. |
| [WP\_REST\_Widget\_Types\_Controller::render\_legacy\_widget\_preview\_iframe()](../wp_rest_widget_types_controller/render_legacy_widget_preview_iframe) wp-includes/rest-api/endpoints/class-wp-rest-widget-types-controller.php | Renders a page containing a preview of the requested Legacy Widget block. |
| [WP\_Theme\_JSON::get\_blocks\_metadata()](../wp_theme_json/get_blocks_metadata) wp-includes/class-wp-theme-json.php | Returns the metadata for each block. |
| [WP\_Block\_Supports::apply\_block\_supports()](../wp_block_supports/apply_block_supports) wp-includes/class-wp-block-supports.php | Generates an array of HTML attributes, such as classes, by applying to the given block all of the features that the block supports. |
| [WP\_Block\_Supports::register\_attributes()](../wp_block_supports/register_attributes) wp-includes/class-wp-block-supports.php | Registers the block attributes required by the different block supports. |
| [WP\_Block::\_\_construct()](../wp_block/__construct) wp-includes/class-wp-block.php | Constructor. |
| [WP\_REST\_Block\_Types\_Controller::\_\_construct()](../wp_rest_block_types_controller/__construct) wp-includes/rest-api/endpoints/class-wp-rest-block-types-controller.php | Constructor. |
| [WP\_Block\_List::\_\_construct()](../wp_block_list/__construct) wp-includes/class-wp-block-list.php | Constructor. |
| [register\_block\_type\_from\_metadata()](../../functions/register_block_type_from_metadata) wp-includes/blocks.php | Registers a block type from the metadata stored in the `block.json` file. |
| [WP\_REST\_Block\_Renderer\_Controller::register\_routes()](../wp_rest_block_renderer_controller/register_routes) wp-includes/rest-api/endpoints/class-wp-rest-block-renderer-controller.php | Registers the necessary REST API routes, one for each dynamic block. |
| [WP\_REST\_Block\_Renderer\_Controller::get\_item()](../wp_rest_block_renderer_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-block-renderer-controller.php | Returns block output from block’s registered render\_callback. |
| [wp\_enqueue\_registered\_block\_scripts\_and\_styles()](../../functions/wp_enqueue_registered_block_scripts_and_styles) wp-includes/script-loader.php | Enqueues registered block scripts and styles, depending on current rendered context (only enqueuing editor scripts while in context of the editor). |
| [register\_block\_type()](../../functions/register_block_type) wp-includes/blocks.php | Registers a block type. The recommended way is to register a block type using the metadata stored in the `block.json` file. |
| [unregister\_block\_type()](../../functions/unregister_block_type) wp-includes/blocks.php | Unregisters a block type. |
| [get\_dynamic\_block\_names()](../../functions/get_dynamic_block_names) wp-includes/blocks.php | Returns an array of the names of all registered dynamic block types. |
| [get\_block\_editor\_server\_block\_settings()](../../functions/get_block_editor_server_block_settings) wp-admin/includes/post.php | Prepares server-registered blocks for the block editor. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_Block_Type_Registry::is_registered( string $name ): bool WP\_Block\_Type\_Registry::is\_registered( string $name ): bool
===============================================================
Checks if a block type is registered.
`$name` string Required Block type name including namespace. bool True if the block type is registered, false otherwise.
File: `wp-includes/class-wp-block-type-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type-registry.php/)
```
public function is_registered( $name ) {
return isset( $this->registered_block_types[ $name ] );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Block\_Type\_Registry::register()](register) wp-includes/class-wp-block-type-registry.php | Registers a block type. |
| [WP\_Block\_Type\_Registry::unregister()](unregister) wp-includes/class-wp-block-type-registry.php | Unregisters a block type. |
| [WP\_Block\_Type\_Registry::get\_registered()](get_registered) wp-includes/class-wp-block-type-registry.php | Retrieves a registered block type. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_Application_Passwords::chunk_password( string $raw_password ): string WP\_Application\_Passwords::chunk\_password( string $raw\_password ): string
============================================================================
Sanitizes and then splits a password into smaller chunks.
`$raw_password` string Required The raw application password. string The chunked password.
File: `wp-includes/class-wp-application-passwords.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-application-passwords.php/)
```
public static function chunk_password( $raw_password ) {
$raw_password = preg_replace( '/[^a-z\d]/i', '', $raw_password );
return trim( chunk_split( $raw_password, 4, ' ' ) );
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::create\_item()](../wp_rest_application_passwords_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Creates an application password. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords::is_in_use(): bool WP\_Application\_Passwords::is\_in\_use(): bool
===============================================
Checks if application passwords are being used by the site.
This returns true if at least one application password has ever been created.
bool
File: `wp-includes/class-wp-application-passwords.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-application-passwords.php/)
```
public static function is_in_use() {
$network_id = get_main_network_id();
return (bool) get_network_option( $network_id, self::OPTION_KEY_IN_USE );
}
```
| Uses | Description |
| --- | --- |
| [get\_network\_option()](../../functions/get_network_option) wp-includes/option.php | Retrieves a network’s option value based on the option name. |
| [get\_main\_network\_id()](../../functions/get_main_network_id) wp-includes/functions.php | Gets the main network ID. |
| Used By | Description |
| --- | --- |
| [wp\_authenticate\_application\_password()](../../functions/wp_authenticate_application_password) wp-includes/user.php | Authenticates the user using an application password. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords::record_application_password_usage( int $user_id, string $uuid ): true|WP_Error WP\_Application\_Passwords::record\_application\_password\_usage( int $user\_id, string $uuid ): true|WP\_Error
===============================================================================================================
Records that an application password has been used.
`$user_id` int Required User ID. `$uuid` string Required The password's UUID. true|[WP\_Error](../wp_error) True if the usage was recorded, a [WP\_Error](../wp_error) if an error occurs.
File: `wp-includes/class-wp-application-passwords.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-application-passwords.php/)
```
public static function record_application_password_usage( $user_id, $uuid ) {
$passwords = static::get_user_application_passwords( $user_id );
foreach ( $passwords as &$password ) {
if ( $password['uuid'] !== $uuid ) {
continue;
}
// Only record activity once a day.
if ( $password['last_used'] + DAY_IN_SECONDS > time() ) {
return true;
}
$password['last_used'] = time();
$password['last_ip'] = $_SERVER['REMOTE_ADDR'];
$saved = static::set_user_application_passwords( $user_id, $passwords );
if ( ! $saved ) {
return new WP_Error( 'db_error', __( 'Could not save application password.' ) );
}
return true;
}
// Specified application password not found!
return new WP_Error( 'application_password_not_found', __( 'Could not find an application password with that id.' ) );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [wp\_authenticate\_application\_password()](../../functions/wp_authenticate_application_password) wp-includes/user.php | Authenticates the user using an application password. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords::delete_application_password( int $user_id, string $uuid ): true|WP_Error WP\_Application\_Passwords::delete\_application\_password( int $user\_id, string $uuid ): true|WP\_Error
========================================================================================================
Deletes an application password.
`$user_id` int Required User ID. `$uuid` string Required The password's UUID. true|[WP\_Error](../wp_error) Whether the password was successfully found and deleted, a [WP\_Error](../wp_error) otherwise.
File: `wp-includes/class-wp-application-passwords.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-application-passwords.php/)
```
public static function delete_application_password( $user_id, $uuid ) {
$passwords = static::get_user_application_passwords( $user_id );
foreach ( $passwords as $key => $item ) {
if ( $item['uuid'] === $uuid ) {
unset( $passwords[ $key ] );
$saved = static::set_user_application_passwords( $user_id, $passwords );
if ( ! $saved ) {
return new WP_Error( 'db_error', __( 'Could not delete application password.' ) );
}
/**
* Fires when an application password is deleted.
*
* @since 5.6.0
*
* @param int $user_id The user ID.
* @param array $item The data about the application password.
*/
do_action( 'wp_delete_application_password', $user_id, $item );
return true;
}
}
return new WP_Error( 'application_password_not_found', __( 'Could not find an application password with that id.' ) );
}
```
[do\_action( 'wp\_delete\_application\_password', int $user\_id, array $item )](../../hooks/wp_delete_application_password)
Fires when an application password is deleted.
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::delete\_item()](../wp_rest_application_passwords_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Deletes an application password for a user. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords::update_application_password( int $user_id, string $uuid, array $update = array() ): true|WP_Error WP\_Application\_Passwords::update\_application\_password( int $user\_id, string $uuid, array $update = array() ): true|WP\_Error
=================================================================================================================================
Updates an application password.
`$user_id` int Required User ID. `$uuid` string Required The password's UUID. `$update` array Optional Information about the application password to update. Default: `array()`
true|[WP\_Error](../wp_error) True if successful, otherwise a [WP\_Error](../wp_error) instance is returned on error.
File: `wp-includes/class-wp-application-passwords.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-application-passwords.php/)
```
public static function update_application_password( $user_id, $uuid, $update = array() ) {
$passwords = static::get_user_application_passwords( $user_id );
foreach ( $passwords as &$item ) {
if ( $item['uuid'] !== $uuid ) {
continue;
}
if ( ! empty( $update['name'] ) ) {
$update['name'] = sanitize_text_field( $update['name'] );
}
$save = false;
if ( ! empty( $update['name'] ) && $item['name'] !== $update['name'] ) {
$item['name'] = $update['name'];
$save = true;
}
if ( $save ) {
$saved = static::set_user_application_passwords( $user_id, $passwords );
if ( ! $saved ) {
return new WP_Error( 'db_error', __( 'Could not save application password.' ) );
}
}
/**
* Fires when an application password is updated.
*
* @since 5.6.0
*
* @param int $user_id The user ID.
* @param array $item The updated app password details.
* @param array $update The information to update.
*/
do_action( 'wp_update_application_password', $user_id, $item, $update );
return true;
}
return new WP_Error( 'application_password_not_found', __( 'Could not find an application password with that id.' ) );
}
```
[do\_action( 'wp\_update\_application\_password', int $user\_id, array $item, array $update )](../../hooks/wp_update_application_password)
Fires when an application password is updated.
| Uses | Description |
| --- | --- |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::update\_item()](../wp_rest_application_passwords_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Updates an application password. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
| programming_docs |
wordpress WP_Application_Passwords::get_user_application_passwords( int $user_id ): array WP\_Application\_Passwords::get\_user\_application\_passwords( int $user\_id ): array
=====================================================================================
Gets a user’s application passwords.
`$user_id` int Required User ID. array The list of app passwords.
* `...$0`array
+ `uuid`stringThe unique identifier for the application password.
+ `app_id`stringA UUID provided by the application to uniquely identify it.
+ `name`stringThe name of the application password.
+ `password`stringA one-way hash of the password.
+ `created`intUnix timestamp of when the password was created.
+ `last_used`int|nullThe Unix timestamp of the GMT date the application password was last used.
+ `last_ip`string|nullThe IP address the application password was last used by. File: `wp-includes/class-wp-application-passwords.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-application-passwords.php/)
```
public static function get_user_application_passwords( $user_id ) {
$passwords = get_user_meta( $user_id, static::USERMETA_KEY_APPLICATION_PASSWORDS, true );
if ( ! is_array( $passwords ) ) {
return array();
}
$save = false;
foreach ( $passwords as $i => $password ) {
if ( ! isset( $password['uuid'] ) ) {
$passwords[ $i ]['uuid'] = wp_generate_uuid4();
$save = true;
}
}
if ( $save ) {
static::set_user_application_passwords( $user_id, $passwords );
}
return $passwords;
}
```
| Uses | Description |
| --- | --- |
| [wp\_generate\_uuid4()](../../functions/wp_generate_uuid4) wp-includes/functions.php | Generates a random UUID (version 4). |
| [get\_user\_meta()](../../functions/get_user_meta) wp-includes/user.php | Retrieves user meta field for a user. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_items()](../wp_rest_application_passwords_controller/get_items) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Retrieves a collection of application passwords. |
| [wp\_authenticate\_application\_password()](../../functions/wp_authenticate_application_password) wp-includes/user.php | Authenticates the user using an application password. |
| [WP\_Application\_Passwords\_List\_Table::prepare\_items()](../wp_application_passwords_list_table/prepare_items) wp-admin/includes/class-wp-application-passwords-list-table.php | Prepares the list of items for displaying. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords::set_user_application_passwords( int $user_id, array $passwords ): bool WP\_Application\_Passwords::set\_user\_application\_passwords( int $user\_id, array $passwords ): bool
======================================================================================================
Sets a user’s application passwords.
`$user_id` int Required User ID. `$passwords` array Required Application passwords. bool
File: `wp-includes/class-wp-application-passwords.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-application-passwords.php/)
```
protected static function set_user_application_passwords( $user_id, $passwords ) {
return update_user_meta( $user_id, static::USERMETA_KEY_APPLICATION_PASSWORDS, $passwords );
}
```
| Uses | Description |
| --- | --- |
| [update\_user\_meta()](../../functions/update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords::delete_all_application_passwords( int $user_id ): int|WP_Error WP\_Application\_Passwords::delete\_all\_application\_passwords( int $user\_id ): int|WP\_Error
===============================================================================================
Deletes all application passwords for the given user.
`$user_id` int Required User ID. int|[WP\_Error](../wp_error) The number of passwords that were deleted or a [WP\_Error](../wp_error) on failure.
File: `wp-includes/class-wp-application-passwords.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-application-passwords.php/)
```
public static function delete_all_application_passwords( $user_id ) {
$passwords = static::get_user_application_passwords( $user_id );
if ( $passwords ) {
$saved = static::set_user_application_passwords( $user_id, array() );
if ( ! $saved ) {
return new WP_Error( 'db_error', __( 'Could not delete application passwords.' ) );
}
foreach ( $passwords as $item ) {
/** This action is documented in wp-includes/class-wp-application-passwords.php */
do_action( 'wp_delete_application_password', $user_id, $item );
}
return count( $passwords );
}
return 0;
}
```
[do\_action( 'wp\_delete\_application\_password', int $user\_id, array $item )](../../hooks/wp_delete_application_password)
Fires when an application password is deleted.
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::delete\_items()](../wp_rest_application_passwords_controller/delete_items) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Deletes all application passwords for a user. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords::create_new_application_password( int $user_id, array $args = array() ): array|WP_Error WP\_Application\_Passwords::create\_new\_application\_password( int $user\_id, array $args = array() ): array|WP\_Error
=======================================================================================================================
Creates a new application password.
`$user_id` int Required User ID. `$args` array Optional Arguments used to create the application password.
* `name`stringThe name of the application password.
* `app_id`stringA UUID provided by the application to uniquely identify it.
Default: `array()`
array|[WP\_Error](../wp_error) The first key in the array is the new password, the second is its detailed information.
A [WP\_Error](../wp_error) instance is returned on error.
File: `wp-includes/class-wp-application-passwords.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-application-passwords.php/)
```
public static function create_new_application_password( $user_id, $args = array() ) {
if ( ! empty( $args['name'] ) ) {
$args['name'] = sanitize_text_field( $args['name'] );
}
if ( empty( $args['name'] ) ) {
return new WP_Error( 'application_password_empty_name', __( 'An application name is required to create an application password.' ), array( 'status' => 400 ) );
}
if ( self::application_name_exists_for_user( $user_id, $args['name'] ) ) {
return new WP_Error( 'application_password_duplicate_name', __( 'Each application name should be unique.' ), array( 'status' => 409 ) );
}
$new_password = wp_generate_password( static::PW_LENGTH, false );
$hashed_password = wp_hash_password( $new_password );
$new_item = array(
'uuid' => wp_generate_uuid4(),
'app_id' => empty( $args['app_id'] ) ? '' : $args['app_id'],
'name' => $args['name'],
'password' => $hashed_password,
'created' => time(),
'last_used' => null,
'last_ip' => null,
);
$passwords = static::get_user_application_passwords( $user_id );
$passwords[] = $new_item;
$saved = static::set_user_application_passwords( $user_id, $passwords );
if ( ! $saved ) {
return new WP_Error( 'db_error', __( 'Could not save application password.' ) );
}
$network_id = get_main_network_id();
if ( ! get_network_option( $network_id, self::OPTION_KEY_IN_USE ) ) {
update_network_option( $network_id, self::OPTION_KEY_IN_USE, true );
}
/**
* Fires when an application password is created.
*
* @since 5.6.0
*
* @param int $user_id The user ID.
* @param array $new_item {
* The details about the created password.
*
* @type string $uuid The unique identifier for the application password.
* @type string $app_id A UUID provided by the application to uniquely identify it.
* @type string $name The name of the application password.
* @type string $password A one-way hash of the password.
* @type int $created Unix timestamp of when the password was created.
* @type null $last_used Null.
* @type null $last_ip Null.
* }
* @param string $new_password The unhashed generated application password.
* @param array $args {
* Arguments used to create the application password.
*
* @type string $name The name of the application password.
* @type string $app_id A UUID provided by the application to uniquely identify it.
* }
*/
do_action( 'wp_create_application_password', $user_id, $new_item, $new_password, $args );
return array( $new_password, $new_item );
}
```
[do\_action( 'wp\_create\_application\_password', int $user\_id, array $new\_item, string $new\_password, array $args )](../../hooks/wp_create_application_password)
Fires when an application password is created.
| Uses | Description |
| --- | --- |
| [WP\_Application\_Passwords::application\_name\_exists\_for\_user()](application_name_exists_for_user) wp-includes/class-wp-application-passwords.php | Checks if an application password with the given name exists for this user. |
| [wp\_generate\_uuid4()](../../functions/wp_generate_uuid4) wp-includes/functions.php | Generates a random UUID (version 4). |
| [update\_network\_option()](../../functions/update_network_option) wp-includes/option.php | Updates the value of a network option that was already added. |
| [get\_network\_option()](../../functions/get_network_option) wp-includes/option.php | Retrieves a network’s option value based on the option name. |
| [get\_main\_network\_id()](../../functions/get_main_network_id) wp-includes/functions.php | Gets the main network ID. |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [wp\_generate\_password()](../../functions/wp_generate_password) wp-includes/pluggable.php | Generates a random password drawn from the defined set of characters. |
| [wp\_hash\_password()](../../functions/wp_hash_password) wp-includes/pluggable.php | Creates a hash (encrypt) of a plain text password. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::create\_item()](../wp_rest_application_passwords_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Creates an application password. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Returns [WP\_Error](../wp_error) if application name already exists. |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords::application_name_exists_for_user( int $user_id, string $name ): bool WP\_Application\_Passwords::application\_name\_exists\_for\_user( int $user\_id, string $name ): bool
=====================================================================================================
Checks if an application password with the given name exists for this user.
`$user_id` int Required User ID. `$name` string Required Application name. bool Whether the provided application name exists.
File: `wp-includes/class-wp-application-passwords.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-application-passwords.php/)
```
public static function application_name_exists_for_user( $user_id, $name ) {
$passwords = static::get_user_application_passwords( $user_id );
foreach ( $passwords as $password ) {
if ( strtolower( $password['name'] ) === strtolower( $name ) ) {
return true;
}
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Application\_Passwords::create\_new\_application\_password()](create_new_application_password) wp-includes/class-wp-application-passwords.php | Creates a new application password. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Introduced. |
wordpress WP_Application_Passwords::get_user_application_password( int $user_id, string $uuid ): array|null WP\_Application\_Passwords::get\_user\_application\_password( int $user\_id, string $uuid ): array|null
=======================================================================================================
Gets a user’s application password with the given UUID.
`$user_id` int Required User ID. `$uuid` string Required The password's UUID. array|null The application password if found, null otherwise.
File: `wp-includes/class-wp-application-passwords.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-application-passwords.php/)
```
public static function get_user_application_password( $user_id, $uuid ) {
$passwords = static::get_user_application_passwords( $user_id );
foreach ( $passwords as $password ) {
if ( $password['uuid'] === $uuid ) {
return $password;
}
}
return null;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_current\_item()](../wp_rest_application_passwords_controller/get_current_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Retrieves the application password being currently used for authentication of a user. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_application\_password()](../wp_rest_application_passwords_controller/get_application_password) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested application password for a user. |
| [WP\_REST\_Application\_Passwords\_Controller::create\_item()](../wp_rest_application_passwords_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Creates an application password. |
| [WP\_REST\_Application\_Passwords\_Controller::update\_item()](../wp_rest_application_passwords_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Updates an application password. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Blocks_Controller::filter_response_by_context( array $data, string $context ): array WP\_REST\_Blocks\_Controller::filter\_response\_by\_context( array $data, string $context ): array
==================================================================================================
Filters a response based on the context defined in the schema.
`$data` array Required Response data to filter. `$context` string Required Context defined in the schema. array Filtered response.
File: `wp-includes/rest-api/endpoints/class-wp-rest-blocks-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-blocks-controller.php/)
```
public function filter_response_by_context( $data, $context ) {
$data = parent::filter_response_by_context( $data, $context );
/*
* Remove `title.rendered` and `content.rendered` from the response. It
* doesn't make sense for a reusable block to have rendered content on its
* own, since rendering a block requires it to be inside a post or a page.
*/
unset( $data['title']['rendered'] );
unset( $data['content']['rendered'] );
return $data;
}
```
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Blocks_Controller::check_read_permission( WP_Post $post ): bool WP\_REST\_Blocks\_Controller::check\_read\_permission( WP\_Post $post ): bool
=============================================================================
Checks if a block can be read.
`$post` [WP\_Post](../wp_post) Required Post object that backs the block. bool Whether the block can be read.
File: `wp-includes/rest-api/endpoints/class-wp-rest-blocks-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-blocks-controller.php/)
```
public function check_read_permission( $post ) {
// By default the read_post capability is mapped to edit_posts.
if ( ! current_user_can( 'read_post', $post->ID ) ) {
return false;
}
return parent::check_read_permission( $post );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::check\_read\_permission()](../wp_rest_posts_controller/check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be read. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Blocks_Controller::get_item_schema(): array WP\_REST\_Blocks\_Controller::get\_item\_schema(): array
========================================================
Retrieves the block’s schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-blocks-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-blocks-controller.php/)
```
public function get_item_schema() {
// Do not cache this schema because all properties are derived from parent controller.
$schema = parent::get_item_schema();
/*
* Allow all contexts to access `title.raw` and `content.raw`. Clients always
* need the raw markup of a reusable block to do anything useful, e.g. parse
* it or display it in an editor.
*/
$schema['properties']['title']['properties']['raw']['context'] = array( 'view', 'edit' );
$schema['properties']['content']['properties']['raw']['context'] = array( 'view', 'edit' );
/*
* Remove `title.rendered` and `content.rendered` from the schema. It doesn’t
* make sense for a reusable block to have rendered content on its own, since
* rendering a block requires it to be inside a post or a page.
*/
unset( $schema['properties']['title']['properties']['rendered'] );
unset( $schema['properties']['content']['properties']['rendered'] );
return $schema;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::get\_item\_schema()](../wp_rest_posts_controller/get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves the post’s schema, conforming to JSON Schema. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
| programming_docs |
wordpress WP_Block_Styles_Registry::get_registered_styles_for_block( string $block_name ): array[] WP\_Block\_Styles\_Registry::get\_registered\_styles\_for\_block( string $block\_name ): array[]
================================================================================================
Retrieves registered block styles for a specific block type.
`$block_name` string Required Block type name including namespace. array[] Array whose keys are block style names and whose values are block style properties.
File: `wp-includes/class-wp-block-styles-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-styles-registry.php/)
```
public function get_registered_styles_for_block( $block_name ) {
if ( isset( $this->registered_block_styles[ $block_name ] ) ) {
return $this->registered_block_styles[ $block_name ];
}
return array();
}
```
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_Block_Styles_Registry::register( string $block_name, array $style_properties ): bool WP\_Block\_Styles\_Registry::register( string $block\_name, array $style\_properties ): bool
============================================================================================
Registers a block style for the given block type.
If the block styles are present in a standalone stylesheet, register it and pass its handle as the `style_handle` argument. If the block styles should be inline, use the `inline_style` argument. Usually, one of them would be used to pass CSS styles. However, you could also skip them and provide CSS styles in any stylesheet or with an inline tag.
`$block_name` string Required Block type name including namespace. `$style_properties` array Required Array containing the properties of the style.
* `name`stringThe identifier of the style used to compute a CSS class.
* `label`stringA human-readable label for the style.
* `inline_style`stringInline CSS code that registers the CSS class required for the style.
* `style_handle`stringThe handle to an already registered style that should be enqueued in places where block styles are needed.
* `is_default`boolWhether this is the default style for the block type.
bool True if the block style was registered with success and false otherwise.
File: `wp-includes/class-wp-block-styles-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-styles-registry.php/)
```
public function register( $block_name, $style_properties ) {
if ( ! isset( $block_name ) || ! is_string( $block_name ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Block name must be a string.' ),
'5.3.0'
);
return false;
}
if ( ! isset( $style_properties['name'] ) || ! is_string( $style_properties['name'] ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Block style name must be a string.' ),
'5.3.0'
);
return false;
}
if ( str_contains( $style_properties['name'], ' ' ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Block style name must not contain any spaces.' ),
'5.9.0'
);
return false;
}
$block_style_name = $style_properties['name'];
if ( ! isset( $this->registered_block_styles[ $block_name ] ) ) {
$this->registered_block_styles[ $block_name ] = array();
}
$this->registered_block_styles[ $block_name ][ $block_style_name ] = $style_properties;
return true;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](../../functions/_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_Block_Styles_Registry::unregister( string $block_name, string $block_style_name ): bool WP\_Block\_Styles\_Registry::unregister( string $block\_name, string $block\_style\_name ): bool
================================================================================================
Unregisters a block style of the given block type.
`$block_name` string Required Block type name including namespace. `$block_style_name` string Required Block style name. bool True if the block style was unregistered with success and false otherwise.
File: `wp-includes/class-wp-block-styles-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-styles-registry.php/)
```
public function unregister( $block_name, $block_style_name ) {
if ( ! $this->is_registered( $block_name, $block_style_name ) ) {
_doing_it_wrong(
__METHOD__,
/* translators: 1: Block name, 2: Block style name. */
sprintf( __( 'Block "%1$s" does not contain a style named "%2$s".' ), $block_name, $block_style_name ),
'5.3.0'
);
return false;
}
unset( $this->registered_block_styles[ $block_name ][ $block_style_name ] );
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_Styles\_Registry::is\_registered()](is_registered) wp-includes/class-wp-block-styles-registry.php | Checks if a block style is registered for the given block type. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](../../functions/_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_Block_Styles_Registry::get_registered( string $block_name, string $block_style_name ): array WP\_Block\_Styles\_Registry::get\_registered( string $block\_name, string $block\_style\_name ): array
======================================================================================================
Retrieves the properties of a registered block style for the given block type.
`$block_name` string Required Block type name including namespace. `$block_style_name` string Required Block style name. array Registered block style properties.
File: `wp-includes/class-wp-block-styles-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-styles-registry.php/)
```
public function get_registered( $block_name, $block_style_name ) {
if ( ! $this->is_registered( $block_name, $block_style_name ) ) {
return null;
}
return $this->registered_block_styles[ $block_name ][ $block_style_name ];
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_Styles\_Registry::is\_registered()](is_registered) wp-includes/class-wp-block-styles-registry.php | Checks if a block style is registered for the given block type. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_Block_Styles_Registry::get_all_registered(): array[] WP\_Block\_Styles\_Registry::get\_all\_registered(): array[]
============================================================
Retrieves all registered block styles.
array[] Array of arrays containing the registered block styles properties grouped by block type.
File: `wp-includes/class-wp-block-styles-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-styles-registry.php/)
```
public function get_all_registered() {
return $this->registered_block_styles;
}
```
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_Block_Styles_Registry::get_instance(): WP_Block_Styles_Registry WP\_Block\_Styles\_Registry::get\_instance(): WP\_Block\_Styles\_Registry
=========================================================================
Utility method to retrieve the main instance of the class.
The instance will be created if it does not exist yet.
[WP\_Block\_Styles\_Registry](../wp_block_styles_registry) The main instance.
File: `wp-includes/class-wp-block-styles-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-styles-registry.php/)
```
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Block\_Types\_Controller::\_\_construct()](../wp_rest_block_types_controller/__construct) wp-includes/rest-api/endpoints/class-wp-rest-block-types-controller.php | Constructor. |
| [enqueue\_block\_styles\_assets()](../../functions/enqueue_block_styles_assets) wp-includes/script-loader.php | Function responsible for enqueuing the styles required for block styles functionality on the editor and on the frontend. |
| [enqueue\_editor\_block\_styles\_assets()](../../functions/enqueue_editor_block_styles_assets) wp-includes/script-loader.php | Function responsible for enqueuing the assets required for block styles functionality on the editor. |
| [register\_block\_style()](../../functions/register_block_style) wp-includes/blocks.php | Registers a new block style. |
| [unregister\_block\_style()](../../functions/unregister_block_style) wp-includes/blocks.php | Unregisters a block style. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_Block_Styles_Registry::is_registered( string $block_name, string $block_style_name ): bool WP\_Block\_Styles\_Registry::is\_registered( string $block\_name, string $block\_style\_name ): bool
====================================================================================================
Checks if a block style is registered for the given block type.
`$block_name` string Required Block type name including namespace. `$block_style_name` string Required Block style name. bool True if the block style is registered, false otherwise.
File: `wp-includes/class-wp-block-styles-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-styles-registry.php/)
```
public function is_registered( $block_name, $block_style_name ) {
return isset( $this->registered_block_styles[ $block_name ][ $block_style_name ] );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Block\_Styles\_Registry::unregister()](unregister) wp-includes/class-wp-block-styles-registry.php | Unregisters a block style of the given block type. |
| [WP\_Block\_Styles\_Registry::get\_registered()](get_registered) wp-includes/class-wp-block-styles-registry.php | Retrieves the properties of a registered block style for the given block type. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_Styles::reset() WP\_Styles::reset()
===================
Resets class properties.
File: `wp-includes/class-wp-styles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-styles-php-2/)
```
public function reset() {
$this->do_concat = false;
$this->concat = '';
$this->concat_version = '';
$this->print_html = '';
}
```
| Used By | Description |
| --- | --- |
| [print\_admin\_styles()](../../functions/print_admin_styles) wp-includes/script-loader.php | Prints the styles queue in the HTML head on admin pages. |
| [print\_late\_styles()](../../functions/print_late_styles) wp-includes/script-loader.php | Prints the styles that were queued too late for the HTML head. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Styles::in_default_dir( string $src ): bool WP\_Styles::in\_default\_dir( string $src ): bool
=================================================
Whether a handle’s source is in a default directory.
`$src` string Required The source of the enqueued style. bool True if found, false if not.
File: `wp-includes/class-wp-styles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-styles-php-2/)
```
public function in_default_dir( $src ) {
if ( ! $this->default_dirs ) {
return true;
}
foreach ( (array) $this->default_dirs as $test ) {
if ( 0 === strpos( $src, $test ) ) {
return true;
}
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Styles::do\_item()](do_item) wp-includes/class-wp-styles.php | Processes a style dependency. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Styles::all_deps( string|string[] $handles, bool $recursion = false, int|false $group = false ): bool WP\_Styles::all\_deps( string|string[] $handles, bool $recursion = false, int|false $group = false ): bool
==========================================================================================================
Determines style dependencies.
* [WP\_Dependencies::all\_deps()](../wp_dependencies/all_deps)
`$handles` string|string[] Required Item handle (string) or item handles (array of strings). `$recursion` bool Optional Internal flag that function is calling itself.
Default: `false`
`$group` int|false Optional Group level: level (int), no groups (false).
Default: `false`
bool True on success, false on failure.
File: `wp-includes/class-wp-styles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-styles-php-2/)
```
public function all_deps( $handles, $recursion = false, $group = false ) {
$r = parent::all_deps( $handles, $recursion, $group );
if ( ! $recursion ) {
/**
* Filters the array of enqueued styles before processing for output.
*
* @since 2.6.0
*
* @param string[] $to_do The list of enqueued style handles about to be processed.
*/
$this->to_do = apply_filters( 'print_styles_array', $this->to_do );
}
return $r;
}
```
[apply\_filters( 'print\_styles\_array', string[] $to\_do )](../../hooks/print_styles_array)
Filters the array of enqueued styles before processing for output.
| Uses | Description |
| --- | --- |
| [WP\_Dependencies::all\_deps()](../wp_dependencies/all_deps) wp-includes/class-wp-dependencies.php | Determines dependencies. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress WP_Styles::add_inline_style( string $handle, string $code ): bool WP\_Styles::add\_inline\_style( string $handle, string $code ): bool
====================================================================
Adds extra CSS styles to a registered stylesheet.
`$handle` string Required The style's registered handle. `$code` string Required String containing the CSS styles to be added. bool True on success, false on failure.
This method adds style rules ($code) to the given stylesheet to be output as embedded style (i.e. in a <style> element).
File: `wp-includes/class-wp-styles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-styles-php-2/)
```
public function add_inline_style( $handle, $code ) {
if ( ! $code ) {
return false;
}
$after = $this->get_data( $handle, 'after' );
if ( ! $after ) {
$after = array();
}
$after[] = $code;
return $this->add_data( $handle, 'after', $after );
}
```
| Used By | Description |
| --- | --- |
| [wp\_add\_inline\_style()](../../functions/wp_add_inline_style) wp-includes/functions.wp-styles.php | Add extra CSS styles to a registered stylesheet. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Styles::do_item( string $handle, int|false $group = false ): bool WP\_Styles::do\_item( string $handle, int|false $group = false ): bool
======================================================================
Processes a style dependency.
* [WP\_Dependencies::do\_item()](../wp_dependencies/do_item)
`$handle` string Required The style's registered handle. `$group` int|false Optional Group level: level (int), no groups (false).
Default: `false`
bool True on success, false on failure.
File: `wp-includes/class-wp-styles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-styles-php-2/)
```
public function do_item( $handle, $group = false ) {
if ( ! parent::do_item( $handle ) ) {
return false;
}
$obj = $this->registered[ $handle ];
if ( null === $obj->ver ) {
$ver = '';
} else {
$ver = $obj->ver ? $obj->ver : $this->default_version;
}
if ( isset( $this->args[ $handle ] ) ) {
$ver = $ver ? $ver . '&' . $this->args[ $handle ] : $this->args[ $handle ];
}
$src = $obj->src;
$cond_before = '';
$cond_after = '';
$conditional = isset( $obj->extra['conditional'] ) ? $obj->extra['conditional'] : '';
if ( $conditional ) {
$cond_before = "<!--[if {$conditional}]>\n";
$cond_after = "<![endif]-->\n";
}
$inline_style = $this->print_inline_style( $handle, false );
if ( $inline_style ) {
$inline_style_tag = sprintf(
"<style id='%s-inline-css'%s>\n%s\n</style>\n",
esc_attr( $handle ),
$this->type_attr,
$inline_style
);
} else {
$inline_style_tag = '';
}
if ( $this->do_concat ) {
if ( $this->in_default_dir( $src ) && ! $conditional && ! isset( $obj->extra['alt'] ) ) {
$this->concat .= "$handle,";
$this->concat_version .= "$handle$ver";
$this->print_code .= $inline_style;
return true;
}
}
if ( isset( $obj->args ) ) {
$media = esc_attr( $obj->args );
} else {
$media = 'all';
}
// A single item may alias a set of items, by having dependencies, but no source.
if ( ! $src ) {
if ( $inline_style_tag ) {
if ( $this->do_concat ) {
$this->print_html .= $inline_style_tag;
} else {
echo $inline_style_tag;
}
}
return true;
}
$href = $this->_css_href( $src, $ver, $handle );
if ( ! $href ) {
return true;
}
$rel = isset( $obj->extra['alt'] ) && $obj->extra['alt'] ? 'alternate stylesheet' : 'stylesheet';
$title = isset( $obj->extra['title'] ) ? sprintf( " title='%s'", esc_attr( $obj->extra['title'] ) ) : '';
$tag = sprintf(
"<link rel='%s' id='%s-css'%s href='%s'%s media='%s' />\n",
$rel,
$handle,
$title,
$href,
$this->type_attr,
$media
);
/**
* Filters the HTML link tag of an enqueued style.
*
* @since 2.6.0
* @since 4.3.0 Introduced the `$href` parameter.
* @since 4.5.0 Introduced the `$media` parameter.
*
* @param string $tag The link tag for the enqueued style.
* @param string $handle The style's registered handle.
* @param string $href The stylesheet's source URL.
* @param string $media The stylesheet's media attribute.
*/
$tag = apply_filters( 'style_loader_tag', $tag, $handle, $href, $media );
if ( 'rtl' === $this->text_direction && isset( $obj->extra['rtl'] ) && $obj->extra['rtl'] ) {
if ( is_bool( $obj->extra['rtl'] ) || 'replace' === $obj->extra['rtl'] ) {
$suffix = isset( $obj->extra['suffix'] ) ? $obj->extra['suffix'] : '';
$rtl_href = str_replace( "{$suffix}.css", "-rtl{$suffix}.css", $this->_css_href( $src, $ver, "$handle-rtl" ) );
} else {
$rtl_href = $this->_css_href( $obj->extra['rtl'], $ver, "$handle-rtl" );
}
$rtl_tag = sprintf(
"<link rel='%s' id='%s-rtl-css'%s href='%s'%s media='%s' />\n",
$rel,
$handle,
$title,
$rtl_href,
$this->type_attr,
$media
);
/** This filter is documented in wp-includes/class-wp-styles.php */
$rtl_tag = apply_filters( 'style_loader_tag', $rtl_tag, $handle, $rtl_href, $media );
if ( 'replace' === $obj->extra['rtl'] ) {
$tag = $rtl_tag;
} else {
$tag .= $rtl_tag;
}
}
if ( $this->do_concat ) {
$this->print_html .= $cond_before;
$this->print_html .= $tag;
if ( $inline_style_tag ) {
$this->print_html .= $inline_style_tag;
}
$this->print_html .= $cond_after;
} else {
echo $cond_before;
echo $tag;
$this->print_inline_style( $handle );
echo $cond_after;
}
return true;
}
```
[apply\_filters( 'style\_loader\_tag', string $tag, string $handle, string $href, string $media )](../../hooks/style_loader_tag)
Filters the HTML link tag of an enqueued style.
| Uses | Description |
| --- | --- |
| [WP\_Styles::print\_inline\_style()](print_inline_style) wp-includes/class-wp-styles.php | Prints extra CSS styles of a registered stylesheet. |
| [WP\_Styles::in\_default\_dir()](in_default_dir) wp-includes/class-wp-styles.php | Whether a handle’s source is in a default directory. |
| [WP\_Styles::\_css\_href()](_css_href) wp-includes/class-wp-styles.php | Generates an enqueued style’s fully-qualified URL. |
| [WP\_Dependencies::do\_item()](../wp_dependencies/do_item) wp-includes/class-wp-dependencies.php | Processes a dependency. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Added the `$group` parameter. |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
| programming_docs |
wordpress WP_Styles::print_inline_style( string $handle, bool $display = true ): string|bool WP\_Styles::print\_inline\_style( string $handle, bool $display = true ): string|bool
=====================================================================================
Prints extra CSS styles of a registered stylesheet.
`$handle` string Required The style's registered handle. `$display` bool Optional Whether to print the inline style instead of just returning it. Default: `true`
string|bool False if no data exists, inline styles if `$display` is true, true otherwise.
File: `wp-includes/class-wp-styles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-styles-php-2/)
```
public function print_inline_style( $handle, $display = true ) {
$output = $this->get_data( $handle, 'after' );
if ( empty( $output ) ) {
return false;
}
$output = implode( "\n", $output );
if ( ! $display ) {
return $output;
}
printf(
"<style id='%s-inline-css'%s>\n%s\n</style>\n",
esc_attr( $handle ),
$this->type_attr,
$output
);
return true;
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Used By | Description |
| --- | --- |
| [WP\_Styles::do\_item()](do_item) wp-includes/class-wp-styles.php | Processes a style dependency. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Styles::do_footer_items(): string[] WP\_Styles::do\_footer\_items(): string[]
=========================================
Processes items and dependencies for the footer group.
HTML 5 allows styles in the body, grab late enqueued items and output them in the footer.
* [WP\_Dependencies::do\_items()](../wp_dependencies/do_items)
string[] Handles of items that have been processed.
File: `wp-includes/class-wp-styles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-styles-php-2/)
```
public function do_footer_items() {
$this->do_items( false, 1 );
return $this->done;
}
```
| Used By | Description |
| --- | --- |
| [print\_late\_styles()](../../functions/print_late_styles) wp-includes/script-loader.php | Prints the styles that were queued too late for the HTML head. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Styles::_css_href( string $src, string $ver, string $handle ): string WP\_Styles::\_css\_href( string $src, string $ver, string $handle ): string
===========================================================================
Generates an enqueued style’s fully-qualified URL.
`$src` string Required The source of the enqueued style. `$ver` string Required The version of the enqueued style. `$handle` string Required The style's registered handle. string Style's fully-qualified URL.
File: `wp-includes/class-wp-styles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-styles-php-2/)
```
public function _css_href( $src, $ver, $handle ) {
if ( ! is_bool( $src ) && ! preg_match( '|^(https?:)?//|', $src ) && ! ( $this->content_url && 0 === strpos( $src, $this->content_url ) ) ) {
$src = $this->base_url . $src;
}
if ( ! empty( $ver ) ) {
$src = add_query_arg( 'ver', $ver, $src );
}
/**
* Filters an enqueued style's fully-qualified URL.
*
* @since 2.6.0
*
* @param string $src The source URL of the enqueued style.
* @param string $handle The style's registered handle.
*/
$src = apply_filters( 'style_loader_src', $src, $handle );
return esc_url( $src );
}
```
[apply\_filters( 'style\_loader\_src', string $src, string $handle )](../../hooks/style_loader_src)
Filters an enqueued style’s fully-qualified URL.
| Uses | Description |
| --- | --- |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Styles::do\_item()](do_item) wp-includes/class-wp-styles.php | Processes a style dependency. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress WP_Styles::__construct() WP\_Styles::\_\_construct()
===========================
Constructor.
File: `wp-includes/class-wp-styles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-styles-php-2/)
```
public function __construct() {
if (
function_exists( 'is_admin' ) && ! is_admin()
&&
function_exists( 'current_theme_supports' ) && ! current_theme_supports( 'html5', 'style' )
) {
$this->type_attr = " type='text/css'";
}
/**
* Fires when the WP_Styles instance is initialized.
*
* @since 2.6.0
*
* @param WP_Styles $wp_styles WP_Styles instance (passed by reference).
*/
do_action_ref_array( 'wp_default_styles', array( &$this ) );
}
```
[do\_action\_ref\_array( 'wp\_default\_styles', WP\_Styles $wp\_styles )](../../hooks/wp_default_styles)
Fires when the [WP\_Styles](../wp_styles) instance is initialized.
| Uses | Description |
| --- | --- |
| [do\_action\_ref\_array()](../../functions/do_action_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook, specifying arguments in an array. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| Used By | Description |
| --- | --- |
| [wp\_styles()](../../functions/wp_styles) wp-includes/functions.wp-styles.php | Initialize $wp\_styles if it has not been set. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress Walker_Nav_Menu::start_lvl( string $output, int $depth, stdClass $args = null ) Walker\_Nav\_Menu::start\_lvl( string $output, int $depth, stdClass $args = null )
==================================================================================
Starts the list before the elements are added.
* [Walker::start\_lvl()](../walker/start_lvl)
`$output` string Required Used to append additional content (passed by reference). `$depth` int Required Depth of menu item. Used for padding. `$args` stdClass Optional An object of [wp\_nav\_menu()](../../functions/wp_nav_menu) arguments. More Arguments from wp\_nav\_menu( ... $args ) Array of nav menu arguments.
* `menu`int|string|[WP\_Term](../wp_term)Desired menu. Accepts a menu ID, slug, name, or object.
* `menu_class`stringCSS class to use for the ul element which forms the menu.
Default `'menu'`.
* `menu_id`stringThe ID that is applied to the ul element which forms the menu.
Default is the menu slug, incremented.
* `container`stringWhether to wrap the ul, and what to wrap it with.
Default `'div'`.
* `container_class`stringClass that is applied to the container.
Default 'menu-{menu slug}-container'.
* `container_id`stringThe ID that is applied to the container.
* `container_aria_label`stringThe aria-label attribute that is applied to the container when it's a nav element.
* `fallback_cb`callable|falseIf the menu doesn't exist, a callback function will fire.
Default is `'wp_page_menu'`. Set to false for no fallback.
* `before`stringText before the link markup.
* `after`stringText after the link markup.
* `link_before`stringText before the link text.
* `link_after`stringText after the link text.
* `echo`boolWhether to echo the menu or return it. Default true.
* `depth`intHow many levels of the hierarchy are to be included.
0 means all. Default 0.
Default 0.
* `walker`objectInstance of a custom walker class.
* `theme_location`stringTheme location to be used. Must be registered with [register\_nav\_menu()](../../functions/register_nav_menu) in order to be selectable by the user.
* `items_wrap`stringHow the list items should be wrapped. Uses printf() format with numbered placeholders. Default is a ul with an id and class.
* `item_spacing`stringWhether to preserve whitespace within the menu's HTML.
Accepts `'preserve'` or `'discard'`. Default `'preserve'`.
Default: `null`
File: `wp-includes/class-walker-nav-menu.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-nav-menu.php/)
```
public function start_lvl( &$output, $depth = 0, $args = null ) {
if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
$t = '';
$n = '';
} else {
$t = "\t";
$n = "\n";
}
$indent = str_repeat( $t, $depth );
// Default class.
$classes = array( 'sub-menu' );
/**
* Filters the CSS class(es) applied to a menu list element.
*
* @since 4.8.0
*
* @param string[] $classes Array of the CSS classes that are applied to the menu `<ul>` element.
* @param stdClass $args An object of `wp_nav_menu()` arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$class_names = implode( ' ', apply_filters( 'nav_menu_submenu_css_class', $classes, $args, $depth ) );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
$output .= "{$n}{$indent}<ul$class_names>{$n}";
}
```
[apply\_filters( 'nav\_menu\_submenu\_css\_class', string[] $classes, stdClass $args, int $depth )](../../hooks/nav_menu_submenu_css_class)
Filters the CSS class(es) applied to a menu list element.
| Uses | Description |
| --- | --- |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress Walker_Nav_Menu::start_el( string $output, WP_Post $data_object, int $depth, stdClass $args = null, int $current_object_id ) Walker\_Nav\_Menu::start\_el( string $output, WP\_Post $data\_object, int $depth, stdClass $args = null, int $current\_object\_id )
===================================================================================================================================
Starts the element output.
* [Walker::start\_el()](../walker/start_el)
`$output` string Required Used to append additional content (passed by reference). `$data_object` [WP\_Post](../wp_post) Required Menu item data object. `$depth` int Required Depth of menu item. Used for padding. `$args` stdClass Optional An object of [wp\_nav\_menu()](../../functions/wp_nav_menu) arguments. More Arguments from wp\_nav\_menu( ... $args ) Array of nav menu arguments.
* `menu`int|string|[WP\_Term](../wp_term)Desired menu. Accepts a menu ID, slug, name, or object.
* `menu_class`stringCSS class to use for the ul element which forms the menu.
Default `'menu'`.
* `menu_id`stringThe ID that is applied to the ul element which forms the menu.
Default is the menu slug, incremented.
* `container`stringWhether to wrap the ul, and what to wrap it with.
Default `'div'`.
* `container_class`stringClass that is applied to the container.
Default 'menu-{menu slug}-container'.
* `container_id`stringThe ID that is applied to the container.
* `container_aria_label`stringThe aria-label attribute that is applied to the container when it's a nav element.
* `fallback_cb`callable|falseIf the menu doesn't exist, a callback function will fire.
Default is `'wp_page_menu'`. Set to false for no fallback.
* `before`stringText before the link markup.
* `after`stringText after the link markup.
* `link_before`stringText before the link text.
* `link_after`stringText after the link text.
* `echo`boolWhether to echo the menu or return it. Default true.
* `depth`intHow many levels of the hierarchy are to be included.
0 means all. Default 0.
Default 0.
* `walker`objectInstance of a custom walker class.
* `theme_location`stringTheme location to be used. Must be registered with [register\_nav\_menu()](../../functions/register_nav_menu) in order to be selectable by the user.
* `items_wrap`stringHow the list items should be wrapped. Uses printf() format with numbered placeholders. Default is a ul with an id and class.
* `item_spacing`stringWhether to preserve whitespace within the menu's HTML.
Accepts `'preserve'` or `'discard'`. Default `'preserve'`.
Default: `null`
`$current_object_id` int Optional ID of the current menu item. Default 0. File: `wp-includes/class-walker-nav-menu.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-nav-menu.php/)
```
public function start_el( &$output, $data_object, $depth = 0, $args = null, $current_object_id = 0 ) {
// Restores the more descriptive, specific name for use within this method.
$menu_item = $data_object;
if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
$t = '';
$n = '';
} else {
$t = "\t";
$n = "\n";
}
$indent = ( $depth ) ? str_repeat( $t, $depth ) : '';
$classes = empty( $menu_item->classes ) ? array() : (array) $menu_item->classes;
$classes[] = 'menu-item-' . $menu_item->ID;
/**
* Filters the arguments for a single nav menu item.
*
* @since 4.4.0
*
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param WP_Post $menu_item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
*/
$args = apply_filters( 'nav_menu_item_args', $args, $menu_item, $depth );
/**
* Filters the CSS classes applied to a menu item's list item element.
*
* @since 3.0.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param string[] $classes Array of the CSS classes that are applied to the menu item's `<li>` element.
* @param WP_Post $menu_item The current menu item object.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$class_names = implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $menu_item, $args, $depth ) );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
/**
* Filters the ID attribute applied to a menu item's list item element.
*
* @since 3.0.1
* @since 4.1.0 The `$depth` parameter was added.
*
* @param string $menu_item_id The ID attribute applied to the menu item's `<li>` element.
* @param WP_Post $menu_item The current menu item.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $menu_item->ID, $menu_item, $args, $depth );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $class_names . '>';
$atts = array();
$atts['title'] = ! empty( $menu_item->attr_title ) ? $menu_item->attr_title : '';
$atts['target'] = ! empty( $menu_item->target ) ? $menu_item->target : '';
if ( '_blank' === $menu_item->target && empty( $menu_item->xfn ) ) {
$atts['rel'] = 'noopener';
} else {
$atts['rel'] = $menu_item->xfn;
}
$atts['href'] = ! empty( $menu_item->url ) ? $menu_item->url : '';
$atts['aria-current'] = $menu_item->current ? 'page' : '';
/**
* Filters the HTML attributes applied to a menu item's anchor element.
*
* @since 3.6.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param array $atts {
* The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.
*
* @type string $title Title attribute.
* @type string $target Target attribute.
* @type string $rel The rel attribute.
* @type string $href The href attribute.
* @type string $aria-current The aria-current attribute.
* }
* @param WP_Post $menu_item The current menu item object.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$atts = apply_filters( 'nav_menu_link_attributes', $atts, $menu_item, $args, $depth );
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( is_scalar( $value ) && '' !== $value && false !== $value ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
/** This filter is documented in wp-includes/post-template.php */
$title = apply_filters( 'the_title', $menu_item->title, $menu_item->ID );
/**
* Filters a menu item's title.
*
* @since 4.4.0
*
* @param string $title The menu item's title.
* @param WP_Post $menu_item The current menu item object.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$title = apply_filters( 'nav_menu_item_title', $title, $menu_item, $args, $depth );
$item_output = $args->before;
$item_output .= '<a' . $attributes . '>';
$item_output .= $args->link_before . $title . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
/**
* Filters a menu item's starting output.
*
* The menu item's starting output only includes `$args->before`, the opening `<a>`,
* the menu item's title, the closing `</a>`, and `$args->after`. Currently, there is
* no filter for modifying the opening and closing `<li>` for a menu item.
*
* @since 3.0.0
*
* @param string $item_output The menu item's starting HTML output.
* @param WP_Post $menu_item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param stdClass $args An object of wp_nav_menu() arguments.
*/
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $menu_item, $depth, $args );
}
```
[apply\_filters( 'nav\_menu\_css\_class', string[] $classes, WP\_Post $menu\_item, stdClass $args, int $depth )](../../hooks/nav_menu_css_class)
Filters the CSS classes applied to a menu item’s list item element.
[apply\_filters( 'nav\_menu\_item\_args', stdClass $args, WP\_Post $menu\_item, int $depth )](../../hooks/nav_menu_item_args)
Filters the arguments for a single nav menu item.
[apply\_filters( 'nav\_menu\_item\_id', string $menu\_item\_id, WP\_Post $menu\_item, stdClass $args, int $depth )](../../hooks/nav_menu_item_id)
Filters the ID attribute applied to a menu item’s list item element.
[apply\_filters( 'nav\_menu\_item\_title', string $title, WP\_Post $menu\_item, stdClass $args, int $depth )](../../hooks/nav_menu_item_title)
Filters a menu item’s title.
[apply\_filters( 'nav\_menu\_link\_attributes', array $atts, WP\_Post $menu\_item, stdClass $args, int $depth )](../../hooks/nav_menu_link_attributes)
Filters the HTML attributes applied to a menu item’s anchor element.
[apply\_filters( 'the\_title', string $post\_title, int $post\_id )](../../hooks/the_title)
Filters the post title.
[apply\_filters( 'walker\_nav\_menu\_start\_el', string $item\_output, WP\_Post $menu\_item, int $depth, stdClass $args )](../../hooks/walker_nav_menu_start_el)
Filters a menu item’s starting output.
| Uses | Description |
| --- | --- |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$item` to `$data_object` and `$id` to `$current_object_id` to match parent class for PHP 8 named parameter support. |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | The ['nav\_menu\_item\_args'](../../hooks/nav_menu_item_args) filter was added. |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
| programming_docs |
wordpress Walker_Nav_Menu::end_lvl( string $output, int $depth, stdClass $args = null ) Walker\_Nav\_Menu::end\_lvl( string $output, int $depth, stdClass $args = null )
================================================================================
Ends the list of after the elements are added.
* [Walker::end\_lvl()](../walker/end_lvl)
`$output` string Required Used to append additional content (passed by reference). `$depth` int Required Depth of menu item. Used for padding. `$args` stdClass Optional An object of [wp\_nav\_menu()](../../functions/wp_nav_menu) arguments. More Arguments from wp\_nav\_menu( ... $args ) Array of nav menu arguments.
* `menu`int|string|[WP\_Term](../wp_term)Desired menu. Accepts a menu ID, slug, name, or object.
* `menu_class`stringCSS class to use for the ul element which forms the menu.
Default `'menu'`.
* `menu_id`stringThe ID that is applied to the ul element which forms the menu.
Default is the menu slug, incremented.
* `container`stringWhether to wrap the ul, and what to wrap it with.
Default `'div'`.
* `container_class`stringClass that is applied to the container.
Default 'menu-{menu slug}-container'.
* `container_id`stringThe ID that is applied to the container.
* `container_aria_label`stringThe aria-label attribute that is applied to the container when it's a nav element.
* `fallback_cb`callable|falseIf the menu doesn't exist, a callback function will fire.
Default is `'wp_page_menu'`. Set to false for no fallback.
* `before`stringText before the link markup.
* `after`stringText after the link markup.
* `link_before`stringText before the link text.
* `link_after`stringText after the link text.
* `echo`boolWhether to echo the menu or return it. Default true.
* `depth`intHow many levels of the hierarchy are to be included.
0 means all. Default 0.
Default 0.
* `walker`objectInstance of a custom walker class.
* `theme_location`stringTheme location to be used. Must be registered with [register\_nav\_menu()](../../functions/register_nav_menu) in order to be selectable by the user.
* `items_wrap`stringHow the list items should be wrapped. Uses printf() format with numbered placeholders. Default is a ul with an id and class.
* `item_spacing`stringWhether to preserve whitespace within the menu's HTML.
Accepts `'preserve'` or `'discard'`. Default `'preserve'`.
Default: `null`
File: `wp-includes/class-walker-nav-menu.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-nav-menu.php/)
```
public function end_lvl( &$output, $depth = 0, $args = null ) {
if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
$t = '';
$n = '';
} else {
$t = "\t";
$n = "\n";
}
$indent = str_repeat( $t, $depth );
$output .= "$indent</ul>{$n}";
}
```
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress Walker_Nav_Menu::end_el( string $output, WP_Post $data_object, int $depth, stdClass $args = null ) Walker\_Nav\_Menu::end\_el( string $output, WP\_Post $data\_object, int $depth, stdClass $args = null )
=======================================================================================================
Ends the element output, if needed.
* [Walker::end\_el()](../walker/end_el)
`$output` string Required Used to append additional content (passed by reference). `$data_object` [WP\_Post](../wp_post) Required Menu item data object. Not used. `$depth` int Required Depth of page. Not Used. `$args` stdClass Optional An object of [wp\_nav\_menu()](../../functions/wp_nav_menu) arguments. More Arguments from wp\_nav\_menu( ... $args ) Array of nav menu arguments.
* `menu`int|string|[WP\_Term](../wp_term)Desired menu. Accepts a menu ID, slug, name, or object.
* `menu_class`stringCSS class to use for the ul element which forms the menu.
Default `'menu'`.
* `menu_id`stringThe ID that is applied to the ul element which forms the menu.
Default is the menu slug, incremented.
* `container`stringWhether to wrap the ul, and what to wrap it with.
Default `'div'`.
* `container_class`stringClass that is applied to the container.
Default 'menu-{menu slug}-container'.
* `container_id`stringThe ID that is applied to the container.
* `container_aria_label`stringThe aria-label attribute that is applied to the container when it's a nav element.
* `fallback_cb`callable|falseIf the menu doesn't exist, a callback function will fire.
Default is `'wp_page_menu'`. Set to false for no fallback.
* `before`stringText before the link markup.
* `after`stringText after the link markup.
* `link_before`stringText before the link text.
* `link_after`stringText after the link text.
* `echo`boolWhether to echo the menu or return it. Default true.
* `depth`intHow many levels of the hierarchy are to be included.
0 means all. Default 0.
Default 0.
* `walker`objectInstance of a custom walker class.
* `theme_location`stringTheme location to be used. Must be registered with [register\_nav\_menu()](../../functions/register_nav_menu) in order to be selectable by the user.
* `items_wrap`stringHow the list items should be wrapped. Uses printf() format with numbered placeholders. Default is a ul with an id and class.
* `item_spacing`stringWhether to preserve whitespace within the menu's HTML.
Accepts `'preserve'` or `'discard'`. Default `'preserve'`.
Default: `null`
File: `wp-includes/class-walker-nav-menu.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-nav-menu.php/)
```
public function end_el( &$output, $data_object, $depth = 0, $args = null ) {
if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
$t = '';
$n = '';
} else {
$t = "\t";
$n = "\n";
}
$output .= "</li>{$n}";
}
```
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$item` to `$data_object` to match parent class for PHP 8 named parameter support. |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress WP_REST_Server::check_authentication(): WP_Error|null WP\_REST\_Server::check\_authentication(): WP\_Error|null
=========================================================
Checks the authentication headers if supplied.
[WP\_Error](../wp_error)|null [WP\_Error](../wp_error) indicates unsuccessful login, null indicates successful or no authentication provided
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function check_authentication() {
/**
* Filters REST API authentication errors.
*
* This is used to pass a WP_Error from an authentication method back to
* the API.
*
* Authentication methods should check first if they're being used, as
* multiple authentication methods can be enabled on a site (cookies,
* HTTP basic auth, OAuth). If the authentication method hooked in is
* not actually being attempted, null should be returned to indicate
* another authentication method should check instead. Similarly,
* callbacks should ensure the value is `null` before checking for
* errors.
*
* A WP_Error instance can be returned if an error occurs, and this should
* match the format used by API methods internally (that is, the `status`
* data should be used). A callback can return `true` to indicate that
* the authentication method was used, and it succeeded.
*
* @since 4.4.0
*
* @param WP_Error|null|true $errors WP_Error if authentication error, null if authentication
* method wasn't used, true if authentication succeeded.
*/
return apply_filters( 'rest_authentication_errors', null );
}
```
[apply\_filters( 'rest\_authentication\_errors', WP\_Error|null|true $errors )](../../hooks/rest_authentication_errors)
Filters REST API authentication errors.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::json_error( string $code, string $message, int $status = null ): string WP\_REST\_Server::json\_error( string $code, string $message, int $status = null ): string
==========================================================================================
Retrieves an appropriate error representation in JSON.
Note: This should only be used in [WP\_REST\_Server::serve\_request()](serve_request), as it cannot handle [WP\_Error](../wp_error) internally. All callbacks and other internal methods should instead return a [WP\_Error](../wp_error) with the data set to an array that includes a ‘status’ key, with the value being the HTTP status to send.
`$code` string Required [WP\_Error](../wp_error)-style code. `$message` string Required Human-readable message. `$status` int Optional HTTP status code to send. Default: `null`
string JSON representation of the error
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
protected function json_error( $code, $message, $status = null ) {
if ( $status ) {
$this->set_status( $status );
}
$error = compact( 'code', 'message' );
return wp_json_encode( $error );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::set\_status()](set_status) wp-includes/rest-api/class-wp-rest-server.php | Sends an HTTP status code. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::get_data_for_route( string $route, array $callbacks, string $context = 'view' ): array|null WP\_REST\_Server::get\_data\_for\_route( string $route, array $callbacks, string $context = 'view' ): array|null
================================================================================================================
Retrieves publicly-visible data for the route.
`$route` string Required Route to get data for. `$callbacks` array Required Callbacks to convert to data. `$context` string Optional Context for the data. Accepts `'view'` or `'help'`. Default `'view'`. Default: `'view'`
array|null Data for the route, or null if no publicly-visible data.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function get_data_for_route( $route, $callbacks, $context = 'view' ) {
$data = array(
'namespace' => '',
'methods' => array(),
'endpoints' => array(),
);
$allow_batch = false;
if ( isset( $this->route_options[ $route ] ) ) {
$options = $this->route_options[ $route ];
if ( isset( $options['namespace'] ) ) {
$data['namespace'] = $options['namespace'];
}
$allow_batch = isset( $options['allow_batch'] ) ? $options['allow_batch'] : false;
if ( isset( $options['schema'] ) && 'help' === $context ) {
$data['schema'] = call_user_func( $options['schema'] );
}
}
$allowed_schema_keywords = array_flip( rest_get_allowed_schema_keywords() );
$route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route );
foreach ( $callbacks as $callback ) {
// Skip to the next route if any callback is hidden.
if ( empty( $callback['show_in_index'] ) ) {
continue;
}
$data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) );
$endpoint_data = array(
'methods' => array_keys( $callback['methods'] ),
);
$callback_batch = isset( $callback['allow_batch'] ) ? $callback['allow_batch'] : $allow_batch;
if ( $callback_batch ) {
$endpoint_data['allow_batch'] = $callback_batch;
}
if ( isset( $callback['args'] ) ) {
$endpoint_data['args'] = array();
foreach ( $callback['args'] as $key => $opts ) {
if ( is_string( $opts ) ) {
$opts = array( $opts => 0 );
} elseif ( ! is_array( $opts ) ) {
$opts = array();
}
$arg_data = array_intersect_key( $opts, $allowed_schema_keywords );
$arg_data['required'] = ! empty( $opts['required'] );
$endpoint_data['args'][ $key ] = $arg_data;
}
}
$data['endpoints'][] = $endpoint_data;
// For non-variable routes, generate links.
if ( strpos( $route, '{' ) === false ) {
$data['_links'] = array(
'self' => array(
array(
'href' => rest_url( $route ),
),
),
);
}
}
if ( empty( $data['methods'] ) ) {
// No methods supported, hide the route.
return null;
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [rest\_get\_allowed\_schema\_keywords()](../../functions/rest_get_allowed_schema_keywords) wp-includes/rest-api.php | Get all valid JSON schema properties. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::get\_data\_for\_routes()](get_data_for_routes) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the publicly-visible data for routes. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::send_header( string $key, string $value ) WP\_REST\_Server::send\_header( string $key, string $value )
============================================================
Sends an HTTP header.
`$key` string Required Header key. `$value` string Required Header value. File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function send_header( $key, $value ) {
/*
* Sanitize as per RFC2616 (Section 4.2):
*
* Any LWS that occurs between field-content MAY be replaced with a
* single SP before interpreting the field value or forwarding the
* message downstream.
*/
$value = preg_replace( '/\s+/', ' ', $value );
header( sprintf( '%s: %s', $key, $value ) );
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::send\_headers()](send_headers) wp-includes/rest-api/class-wp-rest-server.php | Sends multiple HTTP headers. |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::serve_batch_request_v1( WP_REST_Request $batch_request ): WP_REST_Response WP\_REST\_Server::serve\_batch\_request\_v1( WP\_REST\_Request $batch\_request ): WP\_REST\_Response
====================================================================================================
Serves the batch/v1 request.
`$batch_request` [WP\_REST\_Request](../wp_rest_request) Required The batch request object. [WP\_REST\_Response](../wp_rest_response) The generated response object.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function serve_batch_request_v1( WP_REST_Request $batch_request ) {
$requests = array();
foreach ( $batch_request['requests'] as $args ) {
$parsed_url = wp_parse_url( $args['path'] );
if ( false === $parsed_url ) {
$requests[] = new WP_Error( 'parse_path_failed', __( 'Could not parse the path.' ), array( 'status' => 400 ) );
continue;
}
$single_request = new WP_REST_Request( isset( $args['method'] ) ? $args['method'] : 'POST', $parsed_url['path'] );
if ( ! empty( $parsed_url['query'] ) ) {
$query_args = null; // Satisfy linter.
wp_parse_str( $parsed_url['query'], $query_args );
$single_request->set_query_params( $query_args );
}
if ( ! empty( $args['body'] ) ) {
$single_request->set_body_params( $args['body'] );
}
if ( ! empty( $args['headers'] ) ) {
$single_request->set_headers( $args['headers'] );
}
$requests[] = $single_request;
}
$matches = array();
$validation = array();
$has_error = false;
foreach ( $requests as $single_request ) {
$match = $this->match_request_to_handler( $single_request );
$matches[] = $match;
$error = null;
if ( is_wp_error( $match ) ) {
$error = $match;
}
if ( ! $error ) {
list( $route, $handler ) = $match;
if ( isset( $handler['allow_batch'] ) ) {
$allow_batch = $handler['allow_batch'];
} else {
$route_options = $this->get_route_options( $route );
$allow_batch = isset( $route_options['allow_batch'] ) ? $route_options['allow_batch'] : false;
}
if ( ! is_array( $allow_batch ) || empty( $allow_batch['v1'] ) ) {
$error = new WP_Error(
'rest_batch_not_allowed',
__( 'The requested route does not support batch requests.' ),
array( 'status' => 400 )
);
}
}
if ( ! $error ) {
$check_required = $single_request->has_valid_params();
if ( is_wp_error( $check_required ) ) {
$error = $check_required;
}
}
if ( ! $error ) {
$check_sanitized = $single_request->sanitize_params();
if ( is_wp_error( $check_sanitized ) ) {
$error = $check_sanitized;
}
}
if ( $error ) {
$has_error = true;
$validation[] = $error;
} else {
$validation[] = true;
}
}
$responses = array();
if ( $has_error && 'require-all-validate' === $batch_request['validation'] ) {
foreach ( $validation as $valid ) {
if ( is_wp_error( $valid ) ) {
$responses[] = $this->envelope_response( $this->error_to_response( $valid ), false )->get_data();
} else {
$responses[] = null;
}
}
return new WP_REST_Response(
array(
'failed' => 'validation',
'responses' => $responses,
),
WP_Http::MULTI_STATUS
);
}
foreach ( $requests as $i => $single_request ) {
$clean_request = clone $single_request;
$clean_request->set_url_params( array() );
$clean_request->set_attributes( array() );
$clean_request->set_default_params( array() );
/** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
$result = apply_filters( 'rest_pre_dispatch', null, $this, $clean_request );
if ( empty( $result ) ) {
$match = $matches[ $i ];
$error = null;
if ( is_wp_error( $validation[ $i ] ) ) {
$error = $validation[ $i ];
}
if ( is_wp_error( $match ) ) {
$result = $this->error_to_response( $match );
} else {
list( $route, $handler ) = $match;
if ( ! $error && ! is_callable( $handler['callback'] ) ) {
$error = new WP_Error(
'rest_invalid_handler',
__( 'The handler for the route is invalid' ),
array( 'status' => 500 )
);
}
$result = $this->respond_to_request( $single_request, $route, $handler, $error );
}
}
/** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
$result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $single_request );
$responses[] = $this->envelope_response( $result, false )->get_data();
}
return new WP_REST_Response( array( 'responses' => $responses ), WP_Http::MULTI_STATUS );
}
```
[apply\_filters( 'rest\_post\_dispatch', WP\_HTTP\_Response $result, WP\_REST\_Server $server, WP\_REST\_Request $request )](../../hooks/rest_post_dispatch)
Filters the REST API response.
[apply\_filters( 'rest\_pre\_dispatch', mixed $result, WP\_REST\_Server $server, WP\_REST\_Request $request )](../../hooks/rest_pre_dispatch)
Filters the pre-calculated result of a REST API dispatch request.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::match\_request\_to\_handler()](match_request_to_handler) wp-includes/rest-api/class-wp-rest-server.php | Matches a request object to its handler. |
| [WP\_REST\_Server::respond\_to\_request()](respond_to_request) wp-includes/rest-api/class-wp-rest-server.php | Dispatches the request to the callback handler. |
| [wp\_parse\_url()](../../functions/wp_parse_url) wp-includes/http.php | A wrapper for PHP’s parse\_url() function that handles consistency in the return values across PHP versions. |
| [WP\_REST\_Request::\_\_construct()](../wp_rest_request/__construct) wp-includes/rest-api/class-wp-rest-request.php | Constructor. |
| [WP\_REST\_Server::get\_route\_options()](get_route_options) wp-includes/rest-api/class-wp-rest-server.php | Retrieves specified options for a route. |
| [WP\_REST\_Server::envelope\_response()](envelope_response) wp-includes/rest-api/class-wp-rest-server.php | Wraps the response in an envelope. |
| [WP\_REST\_Server::error\_to\_response()](error_to_response) wp-includes/rest-api/class-wp-rest-server.php | Converts an error to a response object. |
| [wp\_parse\_str()](../../functions/wp_parse_str) wp-includes/formatting.php | Parses a string into variables to be stored in an array. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Server::serve_request( string $path = null ): null|false WP\_REST\_Server::serve\_request( string $path = null ): null|false
===================================================================
Handles serving a REST API request.
Matches the current server URI to a route and runs the first matching callback then outputs a JSON representation of the returned value.
* [WP\_REST\_Server::dispatch()](../wp_rest_server/dispatch)
`$path` string Optional The request route. If not set, `$_SERVER['PATH_INFO']` will be used.
Default: `null`
null|false Null if not served and a HEAD request, false otherwise.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function serve_request( $path = null ) {
/* @var WP_User|null $current_user */
global $current_user;
if ( $current_user instanceof WP_User && ! $current_user->exists() ) {
/*
* If there is no current user authenticated via other means, clear
* the cached lack of user, so that an authenticate check can set it
* properly.
*
* This is done because for authentications such as Application
* Passwords, we don't want it to be accepted unless the current HTTP
* request is a REST API request, which can't always be identified early
* enough in evaluation.
*/
$current_user = null;
}
/**
* Filters whether JSONP is enabled for the REST API.
*
* @since 4.4.0
*
* @param bool $jsonp_enabled Whether JSONP is enabled. Default true.
*/
$jsonp_enabled = apply_filters( 'rest_jsonp_enabled', true );
$jsonp_callback = false;
if ( isset( $_GET['_jsonp'] ) ) {
$jsonp_callback = $_GET['_jsonp'];
}
$content_type = ( $jsonp_callback && $jsonp_enabled ) ? 'application/javascript' : 'application/json';
$this->send_header( 'Content-Type', $content_type . '; charset=' . get_option( 'blog_charset' ) );
$this->send_header( 'X-Robots-Tag', 'noindex' );
$api_root = get_rest_url();
if ( ! empty( $api_root ) ) {
$this->send_header( 'Link', '<' . sanitize_url( $api_root ) . '>; rel="https://api.w.org/"' );
}
/*
* Mitigate possible JSONP Flash attacks.
*
* https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
*/
$this->send_header( 'X-Content-Type-Options', 'nosniff' );
$expose_headers = array( 'X-WP-Total', 'X-WP-TotalPages', 'Link' );
/**
* Filters the list of response headers that are exposed to REST API CORS requests.
*
* @since 5.5.0
*
* @param string[] $expose_headers The list of response headers to expose.
*/
$expose_headers = apply_filters( 'rest_exposed_cors_headers', $expose_headers );
$this->send_header( 'Access-Control-Expose-Headers', implode( ', ', $expose_headers ) );
$allow_headers = array(
'Authorization',
'X-WP-Nonce',
'Content-Disposition',
'Content-MD5',
'Content-Type',
);
/**
* Filters the list of request headers that are allowed for REST API CORS requests.
*
* The allowed headers are passed to the browser to specify which
* headers can be passed to the REST API. By default, we allow the
* Content-* headers needed to upload files to the media endpoints.
* As well as the Authorization and Nonce headers for allowing authentication.
*
* @since 5.5.0
*
* @param string[] $allow_headers The list of request headers to allow.
*/
$allow_headers = apply_filters( 'rest_allowed_cors_headers', $allow_headers );
$this->send_header( 'Access-Control-Allow-Headers', implode( ', ', $allow_headers ) );
/**
* Filters whether to send nocache headers on a REST API request.
*
* @since 4.4.0
*
* @param bool $rest_send_nocache_headers Whether to send no-cache headers.
*/
$send_no_cache_headers = apply_filters( 'rest_send_nocache_headers', is_user_logged_in() );
if ( $send_no_cache_headers ) {
foreach ( wp_get_nocache_headers() as $header => $header_value ) {
if ( empty( $header_value ) ) {
$this->remove_header( $header );
} else {
$this->send_header( $header, $header_value );
}
}
}
/**
* Filters whether the REST API is enabled.
*
* @since 4.4.0
* @deprecated 4.7.0 Use the {@see 'rest_authentication_errors'} filter to
* restrict access to the REST API.
*
* @param bool $rest_enabled Whether the REST API is enabled. Default true.
*/
apply_filters_deprecated(
'rest_enabled',
array( true ),
'4.7.0',
'rest_authentication_errors',
sprintf(
/* translators: %s: rest_authentication_errors */
__( 'The REST API can no longer be completely disabled, the %s filter can be used to restrict access to the API, instead.' ),
'rest_authentication_errors'
)
);
if ( $jsonp_callback ) {
if ( ! $jsonp_enabled ) {
echo $this->json_error( 'rest_callback_disabled', __( 'JSONP support is disabled on this site.' ), 400 );
return false;
}
if ( ! wp_check_jsonp_callback( $jsonp_callback ) ) {
echo $this->json_error( 'rest_callback_invalid', __( 'Invalid JSONP callback function.' ), 400 );
return false;
}
}
if ( empty( $path ) ) {
if ( isset( $_SERVER['PATH_INFO'] ) ) {
$path = $_SERVER['PATH_INFO'];
} else {
$path = '/';
}
}
$request = new WP_REST_Request( $_SERVER['REQUEST_METHOD'], $path );
$request->set_query_params( wp_unslash( $_GET ) );
$request->set_body_params( wp_unslash( $_POST ) );
$request->set_file_params( $_FILES );
$request->set_headers( $this->get_headers( wp_unslash( $_SERVER ) ) );
$request->set_body( self::get_raw_data() );
/*
* HTTP method override for clients that can't use PUT/PATCH/DELETE. First, we check
* $_GET['_method']. If that is not set, we check for the HTTP_X_HTTP_METHOD_OVERRIDE
* header.
*/
if ( isset( $_GET['_method'] ) ) {
$request->set_method( $_GET['_method'] );
} elseif ( isset( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ) ) {
$request->set_method( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] );
}
$result = $this->check_authentication();
if ( ! is_wp_error( $result ) ) {
$result = $this->dispatch( $request );
}
// Normalize to either WP_Error or WP_REST_Response...
$result = rest_ensure_response( $result );
// ...then convert WP_Error across.
if ( is_wp_error( $result ) ) {
$result = $this->error_to_response( $result );
}
/**
* Filters the REST API response.
*
* Allows modification of the response before returning.
*
* @since 4.4.0
* @since 4.5.0 Applied to embedded responses.
*
* @param WP_HTTP_Response $result Result to send to the client. Usually a `WP_REST_Response`.
* @param WP_REST_Server $server Server instance.
* @param WP_REST_Request $request Request used to generate the response.
*/
$result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $request );
// Wrap the response in an envelope if asked for.
if ( isset( $_GET['_envelope'] ) ) {
$embed = isset( $_GET['_embed'] ) ? rest_parse_embed_param( $_GET['_embed'] ) : false;
$result = $this->envelope_response( $result, $embed );
}
// Send extra data from response objects.
$headers = $result->get_headers();
$this->send_headers( $headers );
$code = $result->get_status();
$this->set_status( $code );
/**
* Filters whether the REST API request has already been served.
*
* Allow sending the request manually - by returning true, the API result
* will not be sent to the client.
*
* @since 4.4.0
*
* @param bool $served Whether the request has already been served.
* Default false.
* @param WP_HTTP_Response $result Result to send to the client. Usually a `WP_REST_Response`.
* @param WP_REST_Request $request Request used to generate the response.
* @param WP_REST_Server $server Server instance.
*/
$served = apply_filters( 'rest_pre_serve_request', false, $result, $request, $this );
if ( ! $served ) {
if ( 'HEAD' === $request->get_method() ) {
return null;
}
// Embed links inside the request.
$embed = isset( $_GET['_embed'] ) ? rest_parse_embed_param( $_GET['_embed'] ) : false;
$result = $this->response_to_data( $result, $embed );
/**
* Filters the REST API response.
*
* Allows modification of the response data after inserting
* embedded data (if any) and before echoing the response data.
*
* @since 4.8.1
*
* @param array $result Response data to send to the client.
* @param WP_REST_Server $server Server instance.
* @param WP_REST_Request $request Request used to generate the response.
*/
$result = apply_filters( 'rest_pre_echo_response', $result, $this, $request );
// The 204 response shouldn't have a body.
if ( 204 === $code || null === $result ) {
return null;
}
$result = wp_json_encode( $result, $this->get_json_encode_options( $request ) );
$json_error_message = $this->get_json_last_error();
if ( $json_error_message ) {
$this->set_status( 500 );
$json_error_obj = new WP_Error(
'rest_encode_error',
$json_error_message,
array( 'status' => 500 )
);
$result = $this->error_to_response( $json_error_obj );
$result = wp_json_encode( $result->data, $this->get_json_encode_options( $request ) );
}
if ( $jsonp_callback ) {
// Prepend '/**/' to mitigate possible JSONP Flash attacks.
// https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
echo '/**/' . $jsonp_callback . '(' . $result . ')';
} else {
echo $result;
}
}
return null;
}
```
[apply\_filters( 'rest\_allowed\_cors\_headers', string[] $allow\_headers )](../../hooks/rest_allowed_cors_headers)
Filters the list of request headers that are allowed for REST API CORS requests.
[apply\_filters\_deprecated( 'rest\_enabled', bool $rest\_enabled )](../../hooks/rest_enabled)
Filters whether the REST API is enabled.
[apply\_filters( 'rest\_exposed\_cors\_headers', string[] $expose\_headers )](../../hooks/rest_exposed_cors_headers)
Filters the list of response headers that are exposed to REST API CORS requests.
[apply\_filters( 'rest\_jsonp\_enabled', bool $jsonp\_enabled )](../../hooks/rest_jsonp_enabled)
Filters whether JSONP is enabled for the REST API.
[apply\_filters( 'rest\_post\_dispatch', WP\_HTTP\_Response $result, WP\_REST\_Server $server, WP\_REST\_Request $request )](../../hooks/rest_post_dispatch)
Filters the REST API response.
[apply\_filters( 'rest\_pre\_echo\_response', array $result, WP\_REST\_Server $server, WP\_REST\_Request $request )](../../hooks/rest_pre_echo_response)
Filters the REST API response.
[apply\_filters( 'rest\_pre\_serve\_request', bool $served, WP\_HTTP\_Response $result, WP\_REST\_Request $request, WP\_REST\_Server $server )](../../hooks/rest_pre_serve_request)
Filters whether the REST API request has already been served.
[apply\_filters( 'rest\_send\_nocache\_headers', bool $rest\_send\_nocache\_headers )](../../hooks/rest_send_nocache_headers)
Filters whether to send nocache headers on a REST API request.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::get\_json\_encode\_options()](get_json_encode_options) wp-includes/rest-api/class-wp-rest-server.php | Gets the encoding options passed to {@see wp\_json\_encode}. |
| [WP\_REST\_Server::set\_status()](set_status) wp-includes/rest-api/class-wp-rest-server.php | Sends an HTTP status code. |
| [wp\_get\_nocache\_headers()](../../functions/wp_get_nocache_headers) wp-includes/functions.php | Gets the header information to prevent caching. |
| [sanitize\_url()](../../functions/sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [WP\_REST\_Server::error\_to\_response()](error_to_response) wp-includes/rest-api/class-wp-rest-server.php | Converts an error to a response object. |
| [WP\_REST\_Server::check\_authentication()](check_authentication) wp-includes/rest-api/class-wp-rest-server.php | Checks the authentication headers if supplied. |
| [WP\_REST\_Server::json\_error()](json_error) wp-includes/rest-api/class-wp-rest-server.php | Retrieves an appropriate error representation in JSON. |
| [WP\_REST\_Server::response\_to\_data()](response_to_data) wp-includes/rest-api/class-wp-rest-server.php | Converts a response to data to send. |
| [rest\_parse\_embed\_param()](../../functions/rest_parse_embed_param) wp-includes/rest-api.php | Parses the “\_embed” parameter into the list of resources to embed. |
| [WP\_REST\_Server::get\_json\_last\_error()](get_json_last_error) wp-includes/rest-api/class-wp-rest-server.php | Returns if an error occurred during most recent JSON encode/decode. |
| [WP\_REST\_Server::dispatch()](dispatch) wp-includes/rest-api/class-wp-rest-server.php | Matches the request to a callback and call it. |
| [WP\_REST\_Server::envelope\_response()](envelope_response) wp-includes/rest-api/class-wp-rest-server.php | Wraps the response in an envelope. |
| [WP\_REST\_Server::send\_headers()](send_headers) wp-includes/rest-api/class-wp-rest-server.php | Sends multiple HTTP headers. |
| [wp\_check\_jsonp\_callback()](../../functions/wp_check_jsonp_callback) wp-includes/functions.php | Checks that a JSONP callback is a valid JavaScript callback name. |
| [WP\_REST\_Server::send\_header()](send_header) wp-includes/rest-api/class-wp-rest-server.php | Sends an HTTP header. |
| [WP\_REST\_Server::get\_headers()](get_headers) wp-includes/rest-api/class-wp-rest-server.php | Extracts headers from a PHP-style $\_SERVER array. |
| [WP\_REST\_Request::\_\_construct()](../wp_rest_request/__construct) wp-includes/rest-api/class-wp-rest-request.php | Constructor. |
| [get\_rest\_url()](../../functions/get_rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint on a site. |
| [apply\_filters\_deprecated()](../../functions/apply_filters_deprecated) wp-includes/plugin.php | Fires functions attached to a deprecated filter hook. |
| [WP\_REST\_Server::get\_raw\_data()](get_raw_data) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the raw request entity (body). |
| [WP\_REST\_Server::remove\_header()](remove_header) wp-includes/rest-api/class-wp-rest-server.php | Removes an HTTP header from the current response. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_user\_logged\_in()](../../functions/is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::get_compact_response_links( WP_REST_Response $response ): array WP\_REST\_Server::get\_compact\_response\_links( WP\_REST\_Response $response ): array
======================================================================================
Retrieves the CURIEs (compact URIs) used for relations.
Extracts the links from a response into a structured hash, suitable for direct output.
`$response` [WP\_REST\_Response](../wp_rest_response) Required Response to extract links from. array Map of link relation to list of link hashes.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public static function get_compact_response_links( $response ) {
$links = self::get_response_links( $response );
if ( empty( $links ) ) {
return array();
}
$curies = $response->get_curies();
$used_curies = array();
foreach ( $links as $rel => $items ) {
// Convert $rel URIs to their compact versions if they exist.
foreach ( $curies as $curie ) {
$href_prefix = substr( $curie['href'], 0, strpos( $curie['href'], '{rel}' ) );
if ( strpos( $rel, $href_prefix ) !== 0 ) {
continue;
}
// Relation now changes from '$uri' to '$curie:$relation'.
$rel_regex = str_replace( '\{rel\}', '(.+)', preg_quote( $curie['href'], '!' ) );
preg_match( '!' . $rel_regex . '!', $rel, $matches );
if ( $matches ) {
$new_rel = $curie['name'] . ':' . $matches[1];
$used_curies[ $curie['name'] ] = $curie;
$links[ $new_rel ] = $items;
unset( $links[ $rel ] );
break;
}
}
}
// Push the curies onto the start of the links array.
if ( $used_curies ) {
$links['curies'] = array_values( $used_curies );
}
return $links;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::get\_response\_links()](get_response_links) wp-includes/rest-api/class-wp-rest-server.php | Retrieves links from a response. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::response\_to\_data()](response_to_data) wp-includes/rest-api/class-wp-rest-server.php | Converts a response to data to send. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_REST_Server::add_site_icon_to_index( WP_REST_Response $response ) WP\_REST\_Server::add\_site\_icon\_to\_index( WP\_REST\_Response $response )
============================================================================
Exposes the site icon through the WordPress REST API.
This is used for fetching this information when user has no rights to update settings.
`$response` [WP\_REST\_Response](../wp_rest_response) Required REST API response. File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
protected function add_site_icon_to_index( WP_REST_Response $response ) {
$site_icon_id = get_option( 'site_icon', 0 );
$this->add_image_to_index( $response, $site_icon_id, 'site_icon' );
$response->data['site_icon_url'] = get_site_icon_url();
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::add\_image\_to\_index()](add_image_to_index) wp-includes/rest-api/class-wp-rest-server.php | Exposes an image through the WordPress REST API. |
| [get\_site\_icon\_url()](../../functions/get_site_icon_url) wp-includes/general-template.php | Returns the Site Icon URL. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::get\_index()](get_index) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the site index. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Server::get_json_last_error(): false|string WP\_REST\_Server::get\_json\_last\_error(): false|string
========================================================
Returns if an error occurred during most recent JSON encode/decode.
Strings to be translated will be in format like "Encoding error: Maximum stack depth exceeded".
false|string Boolean false or string error message.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
protected function get_json_last_error() {
$last_error_code = json_last_error();
if ( JSON_ERROR_NONE === $last_error_code || empty( $last_error_code ) ) {
return false;
}
return json_last_error_msg();
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Server::error_to_response( WP_Error $error ): WP_REST_Response WP\_REST\_Server::error\_to\_response( WP\_Error $error ): WP\_REST\_Response
=============================================================================
Converts an error to a response object.
This iterates over all error codes and messages to change it into a flat array. This enables simpler client behaviour, as it is represented as a list in JSON rather than an object/map.
`$error` [WP\_Error](../wp_error) Required [WP\_Error](../wp_error) instance. [WP\_REST\_Response](../wp_rest_response) List of associative arrays with code and message keys.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
protected function error_to_response( $error ) {
return rest_convert_error_to_response( $error );
}
```
| Uses | Description |
| --- | --- |
| [rest\_convert\_error\_to\_response()](../../functions/rest_convert_error_to_response) wp-includes/rest-api.php | Converts an error to a response object. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_batch\_request\_v1()](serve_batch_request_v1) wp-includes/rest-api/class-wp-rest-server.php | Serves the batch/v1 request. |
| [WP\_REST\_Server::respond\_to\_request()](respond_to_request) wp-includes/rest-api/class-wp-rest-server.php | Dispatches the request to the callback handler. |
| [WP\_REST\_Server::dispatch()](dispatch) wp-includes/rest-api/class-wp-rest-server.php | Matches the request to a callback and call it. |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Converted to a wrapper of [rest\_convert\_error\_to\_response()](../../functions/rest_convert_error_to_response) . |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::respond_to_request( WP_REST_Request $request, string $route, array $handler, WP_Error|null $response ): WP_REST_Response WP\_REST\_Server::respond\_to\_request( WP\_REST\_Request $request, string $route, array $handler, WP\_Error|null $response ): WP\_REST\_Response
=================================================================================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Dispatches the request to the callback handler.
`$request` [WP\_REST\_Request](../wp_rest_request) Required The request object. `$route` string Required The matched route regex. `$handler` array Required The matched route handler. `$response` [WP\_Error](../wp_error)|null Required The current error object if any. [WP\_REST\_Response](../wp_rest_response)
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
protected function respond_to_request( $request, $route, $handler, $response ) {
/**
* Filters the response before executing any REST API callbacks.
*
* Allows plugins to perform additional validation after a
* request is initialized and matched to a registered route,
* but before it is executed.
*
* Note that this filter will not be called for requests that
* fail to authenticate or match to a registered route.
*
* @since 4.7.0
*
* @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client.
* Usually a WP_REST_Response or WP_Error.
* @param array $handler Route handler used for the request.
* @param WP_REST_Request $request Request used to generate the response.
*/
$response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request );
// Check permission specified on the route.
if ( ! is_wp_error( $response ) && ! empty( $handler['permission_callback'] ) ) {
$permission = call_user_func( $handler['permission_callback'], $request );
if ( is_wp_error( $permission ) ) {
$response = $permission;
} elseif ( false === $permission || null === $permission ) {
$response = new WP_Error(
'rest_forbidden',
__( 'Sorry, you are not allowed to do that.' ),
array( 'status' => rest_authorization_required_code() )
);
}
}
if ( ! is_wp_error( $response ) ) {
/**
* Filters the REST API dispatch request result.
*
* Allow plugins to override dispatching the request.
*
* @since 4.4.0
* @since 4.5.0 Added `$route` and `$handler` parameters.
*
* @param mixed $dispatch_result Dispatch result, will be used if not empty.
* @param WP_REST_Request $request Request used to generate the response.
* @param string $route Route matched for the request.
* @param array $handler Route handler used for the request.
*/
$dispatch_result = apply_filters( 'rest_dispatch_request', null, $request, $route, $handler );
// Allow plugins to halt the request via this filter.
if ( null !== $dispatch_result ) {
$response = $dispatch_result;
} else {
$response = call_user_func( $handler['callback'], $request );
}
}
/**
* Filters the response immediately after executing any REST API
* callbacks.
*
* Allows plugins to perform any needed cleanup, for example,
* to undo changes made during the {@see 'rest_request_before_callbacks'}
* filter.
*
* Note that this filter will not be called for requests that
* fail to authenticate or match to a registered route.
*
* Note that an endpoint's `permission_callback` can still be
* called after this filter - see `rest_send_allow_header()`.
*
* @since 4.7.0
*
* @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client.
* Usually a WP_REST_Response or WP_Error.
* @param array $handler Route handler used for the request.
* @param WP_REST_Request $request Request used to generate the response.
*/
$response = apply_filters( 'rest_request_after_callbacks', $response, $handler, $request );
if ( is_wp_error( $response ) ) {
$response = $this->error_to_response( $response );
} else {
$response = rest_ensure_response( $response );
}
$response->set_matched_route( $route );
$response->set_matched_handler( $handler );
return $response;
}
```
[apply\_filters( 'rest\_dispatch\_request', mixed $dispatch\_result, WP\_REST\_Request $request, string $route, array $handler )](../../hooks/rest_dispatch_request)
Filters the REST API dispatch request result.
[apply\_filters( 'rest\_request\_after\_callbacks', WP\_REST\_Response|WP\_HTTP\_Response|WP\_Error|mixed $response, array $handler, WP\_REST\_Request $request )](../../hooks/rest_request_after_callbacks)
Filters the response immediately after executing any REST API callbacks.
[apply\_filters( 'rest\_request\_before\_callbacks', WP\_REST\_Response|WP\_HTTP\_Response|WP\_Error|mixed $response, array $handler, WP\_REST\_Request $request )](../../hooks/rest_request_before_callbacks)
Filters the response before executing any REST API callbacks.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::error\_to\_response()](error_to_response) wp-includes/rest-api/class-wp-rest-server.php | Converts an error to a response object. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_batch\_request\_v1()](serve_batch_request_v1) wp-includes/rest-api/class-wp-rest-server.php | Serves the batch/v1 request. |
| [WP\_REST\_Server::dispatch()](dispatch) wp-includes/rest-api/class-wp-rest-server.php | Matches the request to a callback and call it. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Server::add_site_logo_to_index( WP_REST_Response $response ) WP\_REST\_Server::add\_site\_logo\_to\_index( WP\_REST\_Response $response )
============================================================================
Exposes the site logo through the WordPress REST API.
This is used for fetching this information when user has no rights to update settings.
`$response` [WP\_REST\_Response](../wp_rest_response) Required REST API response. File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
protected function add_site_logo_to_index( WP_REST_Response $response ) {
$site_logo_id = get_theme_mod( 'custom_logo', 0 );
$this->add_image_to_index( $response, $site_logo_id, 'site_logo' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::add\_image\_to\_index()](add_image_to_index) wp-includes/rest-api/class-wp-rest-server.php | Exposes an image through the WordPress REST API. |
| [get\_theme\_mod()](../../functions/get_theme_mod) wp-includes/theme.php | Retrieves theme modification value for the active theme. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::get\_index()](get_index) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the site index. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Server::set_status( int $code ) WP\_REST\_Server::set\_status( int $code )
==========================================
Sends an HTTP status code.
`$code` int Required HTTP status. File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
protected function set_status( $code ) {
status_header( $code );
}
```
| Uses | Description |
| --- | --- |
| [status\_header()](../../functions/status_header) wp-includes/functions.php | Sets HTTP status header. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| [WP\_REST\_Server::json\_error()](json_error) wp-includes/rest-api/class-wp-rest-server.php | Retrieves an appropriate error representation in JSON. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::get_json_encode_options( WP_REST_Request $request ): int WP\_REST\_Server::get\_json\_encode\_options( WP\_REST\_Request $request ): int
===============================================================================
Gets the encoding options passed to {@see wp\_json\_encode}.
`$request` [WP\_REST\_Request](../wp_rest_request) Required The current request object. int The JSON encode options.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
protected function get_json_encode_options( WP_REST_Request $request ) {
$options = 0;
if ( $request->has_param( '_pretty' ) ) {
$options |= JSON_PRETTY_PRINT;
}
/**
* Filters the JSON encoding options used to send the REST API response.
*
* @since 6.1.0
*
* @param int $options JSON encoding options {@see json_encode()}.
* @param WP_REST_Request $request Current request object.
*/
return apply_filters( 'rest_json_encode_options', $options, $request );
}
```
[apply\_filters( 'rest\_json\_encode\_options', int $options, WP\_REST\_Request $request )](../../hooks/rest_json_encode_options)
Filters the JSON encoding options used to send the REST API response.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_REST_Server::get_index( array $request ): WP_REST_Response WP\_REST\_Server::get\_index( array $request ): WP\_REST\_Response
==================================================================
Retrieves the site index.
This endpoint describes the capabilities of the site.
`$request` array Required Request.
* `context`stringContext.
[WP\_REST\_Response](../wp_rest_response) The API root index data.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function get_index( $request ) {
// General site data.
$available = array(
'name' => get_option( 'blogname' ),
'description' => get_option( 'blogdescription' ),
'url' => get_option( 'siteurl' ),
'home' => home_url(),
'gmt_offset' => get_option( 'gmt_offset' ),
'timezone_string' => get_option( 'timezone_string' ),
'namespaces' => array_keys( $this->namespaces ),
'authentication' => array(),
'routes' => $this->get_data_for_routes( $this->get_routes(), $request['context'] ),
);
$response = new WP_REST_Response( $available );
$response->add_link( 'help', 'https://developer.wordpress.org/rest-api/' );
$this->add_active_theme_link_to_index( $response );
$this->add_site_logo_to_index( $response );
$this->add_site_icon_to_index( $response );
/**
* Filters the REST API root index data.
*
* This contains the data describing the API. This includes information
* about supported authentication schemes, supported namespaces, routes
* available on the API, and a small amount of data about the site.
*
* @since 4.4.0
* @since 6.0.0 Added `$request` parameter.
*
* @param WP_REST_Response $response Response data.
* @param WP_REST_Request $request Request data.
*/
return apply_filters( 'rest_index', $response, $request );
}
```
[apply\_filters( 'rest\_index', WP\_REST\_Response $response, WP\_REST\_Request $request )](../../hooks/rest_index)
Filters the REST API root index data.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::add\_site\_icon\_to\_index()](add_site_icon_to_index) wp-includes/rest-api/class-wp-rest-server.php | Exposes the site icon through the WordPress REST API. |
| [WP\_REST\_Server::add\_site\_logo\_to\_index()](add_site_logo_to_index) wp-includes/rest-api/class-wp-rest-server.php | Exposes the site logo through the WordPress REST API. |
| [WP\_REST\_Server::add\_active\_theme\_link\_to\_index()](add_active_theme_link_to_index) wp-includes/rest-api/class-wp-rest-server.php | Adds a link to the active theme for users who have proper permissions. |
| [WP\_REST\_Server::get\_data\_for\_routes()](get_data_for_routes) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the publicly-visible data for routes. |
| [WP\_REST\_Server::get\_routes()](get_routes) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the route map. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::get_headers( array $server ): array WP\_REST\_Server::get\_headers( array $server ): array
======================================================
Extracts headers from a PHP-style $\_SERVER array.
`$server` array Required Associative array similar to `$_SERVER`. array Headers extracted from the input.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function get_headers( $server ) {
$headers = array();
// CONTENT_* headers are not prefixed with HTTP_.
$additional = array(
'CONTENT_LENGTH' => true,
'CONTENT_MD5' => true,
'CONTENT_TYPE' => true,
);
foreach ( $server as $key => $value ) {
if ( strpos( $key, 'HTTP_' ) === 0 ) {
$headers[ substr( $key, 5 ) ] = $value;
} elseif ( 'REDIRECT_HTTP_AUTHORIZATION' === $key && empty( $server['HTTP_AUTHORIZATION'] ) ) {
/*
* In some server configurations, the authorization header is passed in this alternate location.
* Since it would not be passed in in both places we do not check for both headers and resolve.
*/
$headers['AUTHORIZATION'] = $value;
} elseif ( isset( $additional[ $key ] ) ) {
$headers[ $key ] = $value;
}
}
return $headers;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::dispatch( WP_REST_Request $request ): WP_REST_Response WP\_REST\_Server::dispatch( WP\_REST\_Request $request ): WP\_REST\_Response
============================================================================
Matches the request to a callback and call it.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Request to attempt dispatching. [WP\_REST\_Response](../wp_rest_response) Response returned by the callback.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function dispatch( $request ) {
/**
* Filters the pre-calculated result of a REST API dispatch request.
*
* Allow hijacking the request before dispatching by returning a non-empty. The returned value
* will be used to serve the request instead.
*
* @since 4.4.0
*
* @param mixed $result Response to replace the requested version with. Can be anything
* a normal endpoint can return, or null to not hijack the request.
* @param WP_REST_Server $server Server instance.
* @param WP_REST_Request $request Request used to generate the response.
*/
$result = apply_filters( 'rest_pre_dispatch', null, $this, $request );
if ( ! empty( $result ) ) {
return $result;
}
$error = null;
$matched = $this->match_request_to_handler( $request );
if ( is_wp_error( $matched ) ) {
return $this->error_to_response( $matched );
}
list( $route, $handler ) = $matched;
if ( ! is_callable( $handler['callback'] ) ) {
$error = new WP_Error(
'rest_invalid_handler',
__( 'The handler for the route is invalid.' ),
array( 'status' => 500 )
);
}
if ( ! is_wp_error( $error ) ) {
$check_required = $request->has_valid_params();
if ( is_wp_error( $check_required ) ) {
$error = $check_required;
} else {
$check_sanitized = $request->sanitize_params();
if ( is_wp_error( $check_sanitized ) ) {
$error = $check_sanitized;
}
}
}
return $this->respond_to_request( $request, $route, $handler, $error );
}
```
[apply\_filters( 'rest\_pre\_dispatch', mixed $result, WP\_REST\_Server $server, WP\_REST\_Request $request )](../../hooks/rest_pre_dispatch)
Filters the pre-calculated result of a REST API dispatch request.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::match\_request\_to\_handler()](match_request_to_handler) wp-includes/rest-api/class-wp-rest-server.php | Matches a request object to its handler. |
| [WP\_REST\_Server::respond\_to\_request()](respond_to_request) wp-includes/rest-api/class-wp-rest-server.php | Dispatches the request to the callback handler. |
| [WP\_REST\_Server::error\_to\_response()](error_to_response) wp-includes/rest-api/class-wp-rest-server.php | Converts an error to a response object. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| [WP\_REST\_Server::embed\_links()](embed_links) wp-includes/rest-api/class-wp-rest-server.php | Embeds the links from the data into the request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Server::get_routes( string $namespace = '' ): array WP\_REST\_Server::get\_routes( string $namespace = '' ): array
==============================================================
Retrieves the route map.
The route map is an associative array with path regexes as the keys. The value is an indexed array with the callback function/method as the first item, and a bitmask of HTTP methods as the second item (see the class constants).
Each route can be mapped to more than one callback by using an array of the indexed arrays. This allows mapping e.g. GET requests to one callback and POST requests to another.
Note that the path regexes (array keys) must have @ escaped, as this is used as the delimiter with preg\_match()
`$namespace` string Optional y, only return routes in the given namespace. Default: `''`
array `'/path/regex' => array( $callback, $bitmask )` or `'/path/regex' => array( array( $callback, $bitmask ), ...)`.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function get_routes( $namespace = '' ) {
$endpoints = $this->endpoints;
if ( $namespace ) {
$endpoints = wp_list_filter( $endpoints, array( 'namespace' => $namespace ) );
}
/**
* Filters the array of available REST API endpoints.
*
* @since 4.4.0
*
* @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped
* to an array of callbacks for the endpoint. These take the format
* `'/path/regex' => array( $callback, $bitmask )` or
* `'/path/regex' => array( array( $callback, $bitmask ).
*/
$endpoints = apply_filters( 'rest_endpoints', $endpoints );
// Normalize the endpoints.
$defaults = array(
'methods' => '',
'accept_json' => false,
'accept_raw' => false,
'show_in_index' => true,
'args' => array(),
);
foreach ( $endpoints as $route => &$handlers ) {
if ( isset( $handlers['callback'] ) ) {
// Single endpoint, add one deeper.
$handlers = array( $handlers );
}
if ( ! isset( $this->route_options[ $route ] ) ) {
$this->route_options[ $route ] = array();
}
foreach ( $handlers as $key => &$handler ) {
if ( ! is_numeric( $key ) ) {
// Route option, move it to the options.
$this->route_options[ $route ][ $key ] = $handler;
unset( $handlers[ $key ] );
continue;
}
$handler = wp_parse_args( $handler, $defaults );
// Allow comma-separated HTTP methods.
if ( is_string( $handler['methods'] ) ) {
$methods = explode( ',', $handler['methods'] );
} elseif ( is_array( $handler['methods'] ) ) {
$methods = $handler['methods'];
} else {
$methods = array();
}
$handler['methods'] = array();
foreach ( $methods as $method ) {
$method = strtoupper( trim( $method ) );
$handler['methods'][ $method ] = true;
}
}
}
return $endpoints;
}
```
[apply\_filters( 'rest\_endpoints', array $endpoints )](../../hooks/rest_endpoints)
Filters the array of available REST API endpoints.
| Uses | Description |
| --- | --- |
| [wp\_list\_filter()](../../functions/wp_list_filter) wp-includes/functions.php | Filters a list of objects, based on a set of key => value arguments. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::match\_request\_to\_handler()](match_request_to_handler) wp-includes/rest-api/class-wp-rest-server.php | Matches a request object to its handler. |
| [WP\_REST\_Server::get\_index()](get_index) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the site index. |
| [WP\_REST\_Server::get\_namespace\_index()](get_namespace_index) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the index for a namespace. |
| Version | Description |
| --- | --- |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | Add $namespace parameter. |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::get_namespace_index( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Server::get\_namespace\_index( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
===================================================================================================
Retrieves the index for a namespace.
`$request` [WP\_REST\_Request](../wp_rest_request) Required REST request instance. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) [WP\_REST\_Response](../wp_rest_response) instance if the index was found, [WP\_Error](../wp_error) if the namespace isn't set.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function get_namespace_index( $request ) {
$namespace = $request['namespace'];
if ( ! isset( $this->namespaces[ $namespace ] ) ) {
return new WP_Error(
'rest_invalid_namespace',
__( 'The specified namespace could not be found.' ),
array( 'status' => 404 )
);
}
$routes = $this->namespaces[ $namespace ];
$endpoints = array_intersect_key( $this->get_routes(), $routes );
$data = array(
'namespace' => $namespace,
'routes' => $this->get_data_for_routes( $endpoints, $request['context'] ),
);
$response = rest_ensure_response( $data );
// Link to the root index.
$response->add_link( 'up', rest_url( '/' ) );
/**
* Filters the REST API namespace index data.
*
* This typically is just the route data for the namespace, but you can
* add any data you'd like here.
*
* @since 4.4.0
*
* @param WP_REST_Response $response Response data.
* @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter.
*/
return apply_filters( 'rest_namespace_index', $response, $request );
}
```
[apply\_filters( 'rest\_namespace\_index', WP\_REST\_Response $response, WP\_REST\_Request $request )](../../hooks/rest_namespace_index)
Filters the REST API namespace index data.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::get\_data\_for\_routes()](get_data_for_routes) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the publicly-visible data for routes. |
| [WP\_REST\_Server::get\_routes()](get_routes) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the route map. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::remove_header( string $key ) WP\_REST\_Server::remove\_header( string $key )
===============================================
Removes an HTTP header from the current response.
`$key` string Required Header key. File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function remove_header( $key ) {
header_remove( $key );
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_REST_Server::add_active_theme_link_to_index( WP_REST_Response $response ) WP\_REST\_Server::add\_active\_theme\_link\_to\_index( WP\_REST\_Response $response )
=====================================================================================
Adds a link to the active theme for users who have proper permissions.
`$response` [WP\_REST\_Response](../wp_rest_response) Required REST API response. File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
protected function add_active_theme_link_to_index( WP_REST_Response $response ) {
$should_add = current_user_can( 'switch_themes' ) || current_user_can( 'manage_network_themes' );
if ( ! $should_add && current_user_can( 'edit_posts' ) ) {
$should_add = true;
}
if ( ! $should_add ) {
foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
if ( current_user_can( $post_type->cap->edit_posts ) ) {
$should_add = true;
break;
}
}
}
if ( $should_add ) {
$theme = wp_get_theme();
$response->add_link( 'https://api.w.org/active-theme', rest_url( 'wp/v2/themes/' . $theme->get_stylesheet() ) );
}
}
```
| Uses | Description |
| --- | --- |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [get\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::get\_index()](get_index) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the site index. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Introduced. |
wordpress WP_REST_Server::get_data_for_routes( array $routes, string $context = 'view' ): array[] WP\_REST\_Server::get\_data\_for\_routes( array $routes, string $context = 'view' ): array[]
============================================================================================
Retrieves the publicly-visible data for routes.
`$routes` array Required Routes to get data for. `$context` string Optional Context for data. Accepts `'view'` or `'help'`. Default `'view'`. Default: `'view'`
array[] Route data to expose in indexes, keyed by route.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function get_data_for_routes( $routes, $context = 'view' ) {
$available = array();
// Find the available routes.
foreach ( $routes as $route => $callbacks ) {
$data = $this->get_data_for_route( $route, $callbacks, $context );
if ( empty( $data ) ) {
continue;
}
/**
* Filters the publicly-visible data for a single REST API route.
*
* @since 4.4.0
*
* @param array $data Publicly-visible data for the route.
*/
$available[ $route ] = apply_filters( 'rest_endpoints_description', $data );
}
/**
* Filters the publicly-visible data for REST API routes.
*
* This data is exposed on indexes and can be used by clients or
* developers to investigate the site and find out how to use it. It
* acts as a form of self-documentation.
*
* @since 4.4.0
*
* @param array[] $available Route data to expose in indexes, keyed by route.
* @param array $routes Internal route data as an associative array.
*/
return apply_filters( 'rest_route_data', $available, $routes );
}
```
[apply\_filters( 'rest\_endpoints\_description', array $data )](../../hooks/rest_endpoints_description)
Filters the publicly-visible data for a single REST API route.
[apply\_filters( 'rest\_route\_data', array[] $available, array $routes )](../../hooks/rest_route_data)
Filters the publicly-visible data for REST API routes.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::get\_data\_for\_route()](get_data_for_route) wp-includes/rest-api/class-wp-rest-server.php | Retrieves publicly-visible data for the route. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::get\_index()](get_index) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the site index. |
| [WP\_REST\_Server::get\_namespace\_index()](get_namespace_index) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the index for a namespace. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::register_route( string $namespace, string $route, array $route_args, bool $override = false ) WP\_REST\_Server::register\_route( string $namespace, string $route, array $route\_args, bool $override = false )
=================================================================================================================
Registers a route to the server.
`$namespace` string Required Namespace. `$route` string Required The REST route. `$route_args` array Required Route arguments. `$override` bool Optional Whether the route should be overridden if it already exists.
Default: `false`
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function register_route( $namespace, $route, $route_args, $override = false ) {
if ( ! isset( $this->namespaces[ $namespace ] ) ) {
$this->namespaces[ $namespace ] = array();
$this->register_route(
$namespace,
'/' . $namespace,
array(
array(
'methods' => self::READABLE,
'callback' => array( $this, 'get_namespace_index' ),
'args' => array(
'namespace' => array(
'default' => $namespace,
),
'context' => array(
'default' => 'view',
),
),
),
)
);
}
// Associative to avoid double-registration.
$this->namespaces[ $namespace ][ $route ] = true;
$route_args['namespace'] = $namespace;
if ( $override || empty( $this->endpoints[ $route ] ) ) {
$this->endpoints[ $route ] = $route_args;
} else {
$this->endpoints[ $route ] = array_merge( $this->endpoints[ $route ], $route_args );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::register\_route()](register_route) wp-includes/rest-api/class-wp-rest-server.php | Registers a route to the server. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::register\_route()](register_route) wp-includes/rest-api/class-wp-rest-server.php | Registers a route to the server. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::get_raw_data(): string WP\_REST\_Server::get\_raw\_data(): string
==========================================
Retrieves the raw request entity (body).
string Raw request data.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public static function get_raw_data() {
// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
global $HTTP_RAW_POST_DATA;
// $HTTP_RAW_POST_DATA was deprecated in PHP 5.6 and removed in PHP 7.0.
if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
}
return $HTTP_RAW_POST_DATA;
// phpcs:enable
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::__construct() WP\_REST\_Server::\_\_construct()
=================================
Instantiates the REST server.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function __construct() {
$this->endpoints = array(
// Meta endpoints.
'/' => array(
'callback' => array( $this, 'get_index' ),
'methods' => 'GET',
'args' => array(
'context' => array(
'default' => 'view',
),
),
),
'/batch/v1' => array(
'callback' => array( $this, 'serve_batch_request_v1' ),
'methods' => 'POST',
'args' => array(
'validation' => array(
'type' => 'string',
'enum' => array( 'require-all-validate', 'normal' ),
'default' => 'normal',
),
'requests' => array(
'required' => true,
'type' => 'array',
'maxItems' => $this->get_max_batch_size(),
'items' => array(
'type' => 'object',
'properties' => array(
'method' => array(
'type' => 'string',
'enum' => array( 'POST', 'PUT', 'PATCH', 'DELETE' ),
'default' => 'POST',
),
'path' => array(
'type' => 'string',
'required' => true,
),
'body' => array(
'type' => 'object',
'properties' => array(),
'additionalProperties' => true,
),
'headers' => array(
'type' => 'object',
'properties' => array(),
'additionalProperties' => array(
'type' => array( 'string', 'array' ),
'items' => array(
'type' => 'string',
),
),
),
),
),
),
),
),
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::get\_max\_batch\_size()](get_max_batch_size) wp-includes/rest-api/class-wp-rest-server.php | Gets the maximum number of requests that can be included in a batch. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::get_namespaces(): string[] WP\_REST\_Server::get\_namespaces(): string[]
=============================================
Retrieves namespaces registered on the server.
string[] List of registered namespaces.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function get_namespaces() {
return array_keys( $this->namespaces );
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::match\_request\_to\_handler()](match_request_to_handler) wp-includes/rest-api/class-wp-rest-server.php | Matches a request object to its handler. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::add_image_to_index( WP_REST_Response $response, int $image_id, string $type ) WP\_REST\_Server::add\_image\_to\_index( WP\_REST\_Response $response, int $image\_id, string $type )
=====================================================================================================
Exposes an image through the WordPress REST API.
This is used for fetching this information when user has no rights to update settings.
`$response` [WP\_REST\_Response](../wp_rest_response) Required REST API response. `$image_id` int Required Image attachment ID. `$type` string Required Type of Image. File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
protected function add_image_to_index( WP_REST_Response $response, $image_id, $type ) {
$response->data[ $type ] = (int) $image_id;
if ( $image_id ) {
$response->add_link(
'https://api.w.org/featuredmedia',
rest_url( rest_get_route_for_post( $image_id ) ),
array(
'embeddable' => true,
'type' => $type,
)
);
}
}
```
| Uses | Description |
| --- | --- |
| [rest\_get\_route\_for\_post()](../../functions/rest_get_route_for_post) wp-includes/rest-api.php | Gets the REST API route for a post. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::add\_site\_icon\_to\_index()](add_site_icon_to_index) wp-includes/rest-api/class-wp-rest-server.php | Exposes the site icon through the WordPress REST API. |
| [WP\_REST\_Server::add\_site\_logo\_to\_index()](add_site_logo_to_index) wp-includes/rest-api/class-wp-rest-server.php | Exposes the site logo through the WordPress REST API. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Server::send_headers( array $headers ) WP\_REST\_Server::send\_headers( array $headers )
=================================================
Sends multiple HTTP headers.
`$headers` array Required Map of header name to header value. File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function send_headers( $headers ) {
foreach ( $headers as $key => $value ) {
$this->send_header( $key, $value );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::send\_header()](send_header) wp-includes/rest-api/class-wp-rest-server.php | Sends an HTTP header. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::response_to_data( WP_REST_Response $response, bool|string[] $embed ): array WP\_REST\_Server::response\_to\_data( WP\_REST\_Response $response, bool|string[] $embed ): array
=================================================================================================
Converts a response to data to send.
`$response` [WP\_REST\_Response](../wp_rest_response) Required Response object. `$embed` bool|string[] Required Whether to embed all links, a filtered list of link relations, or no links. array Data with sub-requests embedded.
* `_links`arrayLinks.
* `_embedded`arrayEmbedded objects.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function response_to_data( $response, $embed ) {
$data = $response->get_data();
$links = self::get_compact_response_links( $response );
if ( ! empty( $links ) ) {
// Convert links to part of the data.
$data['_links'] = $links;
}
if ( $embed ) {
$this->embed_cache = array();
// Determine if this is a numeric array.
if ( wp_is_numeric_array( $data ) ) {
foreach ( $data as $key => $item ) {
$data[ $key ] = $this->embed_links( $item, $embed );
}
} else {
$data = $this->embed_links( $data, $embed );
}
$this->embed_cache = array();
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::get\_compact\_response\_links()](get_compact_response_links) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the CURIEs (compact URIs) used for relations. |
| [WP\_REST\_Server::embed\_links()](embed_links) wp-includes/rest-api/class-wp-rest-server.php | Embeds the links from the data into the request. |
| [wp\_is\_numeric\_array()](../../functions/wp_is_numeric_array) wp-includes/functions.php | Determines if the variable is a numeric-indexed array. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::envelope\_response()](envelope_response) wp-includes/rest-api/class-wp-rest-server.php | Wraps the response in an envelope. |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| [WP\_REST\_Server::embed\_links()](embed_links) wp-includes/rest-api/class-wp-rest-server.php | Embeds the links from the data into the request. |
| Version | Description |
| --- | --- |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | The $embed parameter can now contain a list of link relations to include. |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::get_response_links( WP_REST_Response $response ): array WP\_REST\_Server::get\_response\_links( WP\_REST\_Response $response ): array
=============================================================================
Retrieves links from a response.
Extracts the links from a response into a structured hash, suitable for direct output.
`$response` [WP\_REST\_Response](../wp_rest_response) Required Response to extract links from. array Map of link relation to list of link hashes.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public static function get_response_links( $response ) {
$links = $response->get_links();
if ( empty( $links ) ) {
return array();
}
// Convert links to part of the data.
$data = array();
foreach ( $links as $rel => $items ) {
$data[ $rel ] = array();
foreach ( $items as $item ) {
$attributes = $item['attributes'];
$attributes['href'] = $item['href'];
$data[ $rel ][] = $attributes;
}
}
return $data;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::get\_compact\_response\_links()](get_compact_response_links) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the CURIEs (compact URIs) used for relations. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::get_route_options( string $route ): array|null WP\_REST\_Server::get\_route\_options( string $route ): array|null
==================================================================
Retrieves specified options for a route.
`$route` string Required Route pattern to fetch options for. array|null Data as an associative array if found, or null if not found.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function get_route_options( $route ) {
if ( ! isset( $this->route_options[ $route ] ) ) {
return null;
}
return $this->route_options[ $route ];
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_batch\_request\_v1()](serve_batch_request_v1) wp-includes/rest-api/class-wp-rest-server.php | Serves the batch/v1 request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::envelope_response( WP_REST_Response $response, bool|string[] $embed ): WP_REST_Response WP\_REST\_Server::envelope\_response( WP\_REST\_Response $response, bool|string[] $embed ): WP\_REST\_Response
==============================================================================================================
Wraps the response in an envelope.
The enveloping technique is used to work around browser/client compatibility issues. Essentially, it converts the full HTTP response to data instead.
`$response` [WP\_REST\_Response](../wp_rest_response) Required Response object. `$embed` bool|string[] Required Whether to embed all links, a filtered list of link relations, or no links. [WP\_REST\_Response](../wp_rest_response) New response with wrapped data
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
public function envelope_response( $response, $embed ) {
$envelope = array(
'body' => $this->response_to_data( $response, $embed ),
'status' => $response->get_status(),
'headers' => $response->get_headers(),
);
/**
* Filters the enveloped form of a REST API response.
*
* @since 4.4.0
*
* @param array $envelope {
* Envelope data.
*
* @type array $body Response data.
* @type int $status The 3-digit HTTP status code.
* @type array $headers Map of header name to header value.
* }
* @param WP_REST_Response $response Original response data.
*/
$envelope = apply_filters( 'rest_envelope_response', $envelope, $response );
// Ensure it's still a response and return.
return rest_ensure_response( $envelope );
}
```
[apply\_filters( 'rest\_envelope\_response', array $envelope, WP\_REST\_Response $response )](../../hooks/rest_envelope_response)
Filters the enveloped form of a REST API response.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::response\_to\_data()](response_to_data) wp-includes/rest-api/class-wp-rest-server.php | Converts a response to data to send. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_batch\_request\_v1()](serve_batch_request_v1) wp-includes/rest-api/class-wp-rest-server.php | Serves the batch/v1 request. |
| [WP\_REST\_Server::serve\_request()](serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | The $embed parameter can now contain a list of link relations to include |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::embed_links( array $data, bool|string[] $embed = true ): array WP\_REST\_Server::embed\_links( array $data, bool|string[] $embed = true ): array
=================================================================================
Embeds the links from the data into the request.
`$data` array Required Data from the request. `$embed` bool|string[] Optional Whether to embed all links or a filtered list of link relations. Default: `true`
array Data with sub-requests embedded.
* `_links`arrayLinks.
* `_embedded`arrayEmbedded objects.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
protected function embed_links( $data, $embed = true ) {
if ( empty( $data['_links'] ) ) {
return $data;
}
$embedded = array();
foreach ( $data['_links'] as $rel => $links ) {
// If a list of relations was specified, and the link relation
// is not in the list of allowed relations, don't process the link.
if ( is_array( $embed ) && ! in_array( $rel, $embed, true ) ) {
continue;
}
$embeds = array();
foreach ( $links as $item ) {
// Determine if the link is embeddable.
if ( empty( $item['embeddable'] ) ) {
// Ensure we keep the same order.
$embeds[] = array();
continue;
}
if ( ! array_key_exists( $item['href'], $this->embed_cache ) ) {
// Run through our internal routing and serve.
$request = WP_REST_Request::from_url( $item['href'] );
if ( ! $request ) {
$embeds[] = array();
continue;
}
// Embedded resources get passed context=embed.
if ( empty( $request['context'] ) ) {
$request['context'] = 'embed';
}
$response = $this->dispatch( $request );
/** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
$response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $this, $request );
$this->embed_cache[ $item['href'] ] = $this->response_to_data( $response, false );
}
$embeds[] = $this->embed_cache[ $item['href'] ];
}
// Determine if any real links were found.
$has_links = count( array_filter( $embeds ) );
if ( $has_links ) {
$embedded[ $rel ] = $embeds;
}
}
if ( ! empty( $embedded ) ) {
$data['_embedded'] = $embedded;
}
return $data;
}
```
[apply\_filters( 'rest\_post\_dispatch', WP\_HTTP\_Response $result, WP\_REST\_Server $server, WP\_REST\_Request $request )](../../hooks/rest_post_dispatch)
Filters the REST API response.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::from\_url()](../wp_rest_request/from_url) wp-includes/rest-api/class-wp-rest-request.php | Retrieves a [WP\_REST\_Request](../wp_rest_request) object from a full URL. |
| [WP\_REST\_Server::dispatch()](dispatch) wp-includes/rest-api/class-wp-rest-server.php | Matches the request to a callback and call it. |
| [WP\_REST\_Server::response\_to\_data()](response_to_data) wp-includes/rest-api/class-wp-rest-server.php | Converts a response to data to send. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::response\_to\_data()](response_to_data) wp-includes/rest-api/class-wp-rest-server.php | Converts a response to data to send. |
| Version | Description |
| --- | --- |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | The $embed parameter can now contain a list of link relations to include. |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Server::match_request_to_handler( WP_REST_Request $request ): array|WP_Error WP\_REST\_Server::match\_request\_to\_handler( WP\_REST\_Request $request ): array|WP\_Error
============================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Matches a request object to its handler.
`$request` [WP\_REST\_Request](../wp_rest_request) Required The request object. array|[WP\_Error](../wp_error) The route and request handler on success or a [WP\_Error](../wp_error) instance if no handler was found.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
protected function match_request_to_handler( $request ) {
$method = $request->get_method();
$path = $request->get_route();
$with_namespace = array();
foreach ( $this->get_namespaces() as $namespace ) {
if ( 0 === strpos( trailingslashit( ltrim( $path, '/' ) ), $namespace ) ) {
$with_namespace[] = $this->get_routes( $namespace );
}
}
if ( $with_namespace ) {
$routes = array_merge( ...$with_namespace );
} else {
$routes = $this->get_routes();
}
foreach ( $routes as $route => $handlers ) {
$match = preg_match( '@^' . $route . '$@i', $path, $matches );
if ( ! $match ) {
continue;
}
$args = array();
foreach ( $matches as $param => $value ) {
if ( ! is_int( $param ) ) {
$args[ $param ] = $value;
}
}
foreach ( $handlers as $handler ) {
$callback = $handler['callback'];
$response = null;
// Fallback to GET method if no HEAD method is registered.
$checked_method = $method;
if ( 'HEAD' === $method && empty( $handler['methods']['HEAD'] ) ) {
$checked_method = 'GET';
}
if ( empty( $handler['methods'][ $checked_method ] ) ) {
continue;
}
if ( ! is_callable( $callback ) ) {
return array( $route, $handler );
}
$request->set_url_params( $args );
$request->set_attributes( $handler );
$defaults = array();
foreach ( $handler['args'] as $arg => $options ) {
if ( isset( $options['default'] ) ) {
$defaults[ $arg ] = $options['default'];
}
}
$request->set_default_params( $defaults );
return array( $route, $handler );
}
}
return new WP_Error(
'rest_no_route',
__( 'No route was found matching the URL and request method.' ),
array( 'status' => 404 )
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Server::get\_namespaces()](get_namespaces) wp-includes/rest-api/class-wp-rest-server.php | Retrieves namespaces registered on the server. |
| [WP\_REST\_Server::get\_routes()](get_routes) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the route map. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::serve\_batch\_request\_v1()](serve_batch_request_v1) wp-includes/rest-api/class-wp-rest-server.php | Serves the batch/v1 request. |
| [WP\_REST\_Server::dispatch()](dispatch) wp-includes/rest-api/class-wp-rest-server.php | Matches the request to a callback and call it. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Server::get_max_batch_size(): int WP\_REST\_Server::get\_max\_batch\_size(): int
==============================================
Gets the maximum number of requests that can be included in a batch.
int The maximum requests.
File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/)
```
protected function get_max_batch_size() {
/**
* Filters the maximum number of REST API requests that can be included in a batch.
*
* @since 5.6.0
*
* @param int $max_size The maximum size.
*/
return apply_filters( 'rest_get_max_batch_size', 25 );
}
```
[apply\_filters( 'rest\_get\_max\_batch\_size', int $max\_size )](../../hooks/rest_get_max_batch_size)
Filters the maximum number of REST API requests that can be included in a batch.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::\_\_construct()](__construct) wp-includes/rest-api/class-wp-rest-server.php | Instantiates the REST server. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Widget_Factory::get_widget_key( string $id_base ): string WP\_Widget\_Factory::get\_widget\_key( string $id\_base ): string
=================================================================
Returns the registered key for the given widget type.
`$id_base` string Required Widget type ID. string
File: `wp-includes/class-wp-widget-factory.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-widget-factory.php/)
```
public function get_widget_key( $id_base ) {
foreach ( $this->widgets as $key => $widget_object ) {
if ( $widget_object->id_base === $id_base ) {
return $key;
}
}
return '';
}
```
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Factory::get\_widget\_object()](get_widget_object) wp-includes/class-wp-widget-factory.php | Returns the registered [WP\_Widget](../wp_widget) object for the given widget type. |
| [WP\_REST\_Widget\_Types\_Controller::encode\_form\_data()](../wp_rest_widget_types_controller/encode_form_data) wp-includes/rest-api/endpoints/class-wp-rest-widget-types-controller.php | An RPC-style endpoint which can be used by clients to turn user input in a widget admin form into an encoded instance object. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_Widget_Factory::_register_widgets() WP\_Widget\_Factory::\_register\_widgets()
==========================================
Serves as a utility method for adding widgets to the registered widgets global.
File: `wp-includes/class-wp-widget-factory.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-widget-factory.php/)
```
public function _register_widgets() {
global $wp_registered_widgets;
$keys = array_keys( $this->widgets );
$registered = array_keys( $wp_registered_widgets );
$registered = array_map( '_get_widget_id_base', $registered );
foreach ( $keys as $key ) {
// Don't register new widget if old widget with the same id is already registered.
if ( in_array( $this->widgets[ $key ]->id_base, $registered, true ) ) {
unset( $this->widgets[ $key ] );
continue;
}
$this->widgets[ $key ]->_register();
}
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Widget_Factory::WP_Widget_Factory() WP\_Widget\_Factory::WP\_Widget\_Factory()
==========================================
This method has been deprecated. Use [WP\_Widget\_Factory::\_\_construct()](../wp_widget_factory/__construct) instead.
PHP4 constructor.
* [WP\_Widget\_Factory::\_\_construct()](../wp_widget_factory/__construct)
File: `wp-includes/class-wp-widget-factory.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-widget-factory.php/)
```
public function WP_Widget_Factory() {
_deprecated_constructor( 'WP_Widget_Factory', '4.3.0' );
self::__construct();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Factory::\_\_construct()](__construct) wp-includes/class-wp-widget-factory.php | PHP5 constructor. |
| [\_deprecated\_constructor()](../../functions/_deprecated_constructor) wp-includes/functions.php | Marks a constructor as deprecated and informs when it has been used. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Use \_\_construct() instead. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Factory::get_widget_object( string $id_base ): WP_Widget|null WP\_Widget\_Factory::get\_widget\_object( string $id\_base ): WP\_Widget|null
=============================================================================
Returns the registered [WP\_Widget](../wp_widget) object for the given widget type.
`$id_base` string Required Widget type ID. [WP\_Widget](../wp_widget)|null
File: `wp-includes/class-wp-widget-factory.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-widget-factory.php/)
```
public function get_widget_object( $id_base ) {
$key = $this->get_widget_key( $id_base );
if ( '' === $key ) {
return null;
}
return $this->widgets[ $key ];
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Factory::get\_widget\_key()](get_widget_key) wp-includes/class-wp-widget-factory.php | Returns the registered key for the given widget type. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Widgets\_Controller::prepare\_item\_for\_response()](../wp_rest_widgets_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Prepares the widget for the REST response. |
| [WP\_REST\_Widgets\_Controller::update\_item()](../wp_rest_widgets_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Updates an existing widget. |
| [WP\_REST\_Widgets\_Controller::delete\_item()](../wp_rest_widgets_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Deletes a widget. |
| [WP\_REST\_Widgets\_Controller::save\_widget()](../wp_rest_widgets_controller/save_widget) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Saves the widget in the request object. |
| [WP\_REST\_Widget\_Types\_Controller::get\_widgets()](../wp_rest_widget_types_controller/get_widgets) wp-includes/rest-api/endpoints/class-wp-rest-widget-types-controller.php | Normalize array of widgets. |
| [WP\_REST\_Widget\_Types\_Controller::encode\_form\_data()](../wp_rest_widget_types_controller/encode_form_data) wp-includes/rest-api/endpoints/class-wp-rest-widget-types-controller.php | An RPC-style endpoint which can be used by clients to turn user input in a widget admin form into an encoded instance object. |
| [WP\_Customize\_Widgets::sanitize\_widget\_instance()](../wp_customize_widgets/sanitize_widget_instance) wp-includes/class-wp-customize-widgets.php | Sanitizes a widget instance. |
| [WP\_Customize\_Widgets::sanitize\_widget\_js\_instance()](../wp_customize_widgets/sanitize_widget_js_instance) wp-includes/class-wp-customize-widgets.php | Converts a widget instance into JSON-representable format. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_Widget_Factory::register( string|WP_Widget $widget ) WP\_Widget\_Factory::register( string|WP\_Widget $widget )
==========================================================
Registers a widget subclass.
`$widget` string|[WP\_Widget](../wp_widget) Required Either the name of a `WP_Widget` subclass or an instance of a `WP_Widget` subclass. File: `wp-includes/class-wp-widget-factory.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-widget-factory.php/)
```
public function register( $widget ) {
if ( $widget instanceof WP_Widget ) {
$this->widgets[ spl_object_hash( $widget ) ] = $widget;
} else {
$this->widgets[ $widget ] = new $widget();
}
}
```
| Used By | Description |
| --- | --- |
| [register\_widget()](../../functions/register_widget) wp-includes/widgets.php | Register a widget |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Updated the `$widget` parameter to also accept a [WP\_Widget](../wp_widget) instance object instead of simply a `WP_Widget` subclass name. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Factory::unregister( string|WP_Widget $widget ) WP\_Widget\_Factory::unregister( string|WP\_Widget $widget )
============================================================
Un-registers a widget subclass.
`$widget` string|[WP\_Widget](../wp_widget) Required Either the name of a `WP_Widget` subclass or an instance of a `WP_Widget` subclass. File: `wp-includes/class-wp-widget-factory.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-widget-factory.php/)
```
public function unregister( $widget ) {
if ( $widget instanceof WP_Widget ) {
unset( $this->widgets[ spl_object_hash( $widget ) ] );
} else {
unset( $this->widgets[ $widget ] );
}
}
```
| Used By | Description |
| --- | --- |
| [unregister\_widget()](../../functions/unregister_widget) wp-includes/widgets.php | Unregisters a widget. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Updated the `$widget` parameter to also accept a [WP\_Widget](../wp_widget) instance object instead of simply a `WP_Widget` subclass name. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Factory::__construct() WP\_Widget\_Factory::\_\_construct()
====================================
PHP5 constructor.
File: `wp-includes/class-wp-widget-factory.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-widget-factory.php/)
```
public function __construct() {
add_action( 'widgets_init', array( $this, '_register_widgets' ), 100 );
}
```
| Uses | Description |
| --- | --- |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Factory::WP\_Widget\_Factory()](wp_widget_factory) wp-includes/class-wp-widget-factory.php | PHP4 constructor. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Site_Icon::additional_sizes( array[] $sizes = array() ): array[] WP\_Site\_Icon::additional\_sizes( array[] $sizes = array() ): array[]
======================================================================
Adds additional sizes to be made when creating the site icon images.
`$sizes` array[] Optional Array of arrays containing information for additional sizes. Default: `array()`
array[] Array of arrays containing additional image sizes.
File: `wp-admin/includes/class-wp-site-icon.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-icon.php/)
```
public function additional_sizes( $sizes = array() ) {
$only_crop_sizes = array();
/**
* Filters the different dimensions that a site icon is saved in.
*
* @since 4.3.0
*
* @param int[] $site_icon_sizes Array of sizes available for the Site Icon.
*/
$this->site_icon_sizes = apply_filters( 'site_icon_image_sizes', $this->site_icon_sizes );
// Use a natural sort of numbers.
natsort( $this->site_icon_sizes );
$this->site_icon_sizes = array_reverse( $this->site_icon_sizes );
// Ensure that we only resize the image into sizes that allow cropping.
foreach ( $sizes as $name => $size_array ) {
if ( isset( $size_array['crop'] ) ) {
$only_crop_sizes[ $name ] = $size_array;
}
}
foreach ( $this->site_icon_sizes as $size ) {
if ( $size < $this->min_size ) {
$only_crop_sizes[ 'site_icon-' . $size ] = array(
'width ' => $size,
'height' => $size,
'crop' => true,
);
}
}
return $only_crop_sizes;
}
```
[apply\_filters( 'site\_icon\_image\_sizes', int[] $site\_icon\_sizes )](../../hooks/site_icon_image_sizes)
Filters the different dimensions that a site icon is saved in.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Site_Icon::get_post_metadata( null|array|string $value, int $post_id, string $meta_key, bool $single ): array|null|string WP\_Site\_Icon::get\_post\_metadata( null|array|string $value, int $post\_id, string $meta\_key, bool $single ): array|null|string
==================================================================================================================================
Adds custom image sizes when meta data for an image is requested, that happens to be used as Site Icon.
`$value` null|array|string Required The value [get\_metadata()](../../functions/get_metadata) should return a single metadata value, or an array of values. `$post_id` int Required Post ID. `$meta_key` string Required Meta key. `$single` bool Required Whether to return only the first value of the specified `$meta_key`. array|null|string The attachment metadata value, array of values, or null.
File: `wp-admin/includes/class-wp-site-icon.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-icon.php/)
```
public function get_post_metadata( $value, $post_id, $meta_key, $single ) {
if ( $single && '_wp_attachment_backup_sizes' === $meta_key ) {
$site_icon_id = get_option( 'site_icon' );
if ( $post_id == $site_icon_id ) {
add_filter( 'intermediate_image_sizes', array( $this, 'intermediate_image_sizes' ) );
}
}
return $value;
}
```
| Uses | Description |
| --- | --- |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Site_Icon::create_attachment_object( string $cropped, int $parent_attachment_id ): array WP\_Site\_Icon::create\_attachment\_object( string $cropped, int $parent\_attachment\_id ): array
=================================================================================================
Creates an attachment ‘object’.
`$cropped` string Required Cropped image URL. `$parent_attachment_id` int Required Attachment ID of parent image. array An array with attachment object data.
File: `wp-admin/includes/class-wp-site-icon.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-icon.php/)
```
public function create_attachment_object( $cropped, $parent_attachment_id ) {
$parent = get_post( $parent_attachment_id );
$parent_url = wp_get_attachment_url( $parent->ID );
$url = str_replace( wp_basename( $parent_url ), wp_basename( $cropped ), $parent_url );
$size = wp_getimagesize( $cropped );
$image_type = ( $size ) ? $size['mime'] : 'image/jpeg';
$attachment = array(
'ID' => $parent_attachment_id,
'post_title' => wp_basename( $cropped ),
'post_content' => $url,
'post_mime_type' => $image_type,
'guid' => $url,
'context' => 'site-icon',
);
return $attachment;
}
```
| Uses | Description |
| --- | --- |
| [wp\_getimagesize()](../../functions/wp_getimagesize) wp-includes/media.php | Allows PHP’s getimagesize() to be debuggable when necessary. |
| [wp\_get\_attachment\_url()](../../functions/wp_get_attachment_url) wp-includes/post.php | Retrieves the URL for an attachment. |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [wp\_ajax\_crop\_image()](../../functions/wp_ajax_crop_image) wp-admin/includes/ajax-actions.php | Ajax handler for cropping an image. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Site_Icon::insert_attachment( array $attachment, string $file ): int WP\_Site\_Icon::insert\_attachment( array $attachment, string $file ): int
==========================================================================
Inserts an attachment.
`$attachment` array Required An array with attachment object data. `$file` string Required File path of the attached image. int Attachment ID.
File: `wp-admin/includes/class-wp-site-icon.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-icon.php/)
```
public function insert_attachment( $attachment, $file ) {
$attachment_id = wp_insert_attachment( $attachment, $file );
$metadata = wp_generate_attachment_metadata( $attachment_id, $file );
/**
* Filters the site icon attachment metadata.
*
* @since 4.3.0
*
* @see wp_generate_attachment_metadata()
*
* @param array $metadata Attachment metadata.
*/
$metadata = apply_filters( 'site_icon_attachment_metadata', $metadata );
wp_update_attachment_metadata( $attachment_id, $metadata );
return $attachment_id;
}
```
[apply\_filters( 'site\_icon\_attachment\_metadata', array $metadata )](../../hooks/site_icon_attachment_metadata)
Filters the site icon attachment metadata.
| Uses | Description |
| --- | --- |
| [wp\_generate\_attachment\_metadata()](../../functions/wp_generate_attachment_metadata) wp-admin/includes/image.php | Generates attachment meta data and create image sub-sizes for images. |
| [wp\_insert\_attachment()](../../functions/wp_insert_attachment) wp-includes/post.php | Inserts an attachment. |
| [wp\_update\_attachment\_metadata()](../../functions/wp_update_attachment_metadata) wp-includes/post.php | Updates metadata for an attachment. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_ajax\_crop\_image()](../../functions/wp_ajax_crop_image) wp-admin/includes/ajax-actions.php | Ajax handler for cropping an image. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Site_Icon::delete_attachment_data( int $post_id ) WP\_Site\_Icon::delete\_attachment\_data( int $post\_id )
=========================================================
Deletes the Site Icon when the image file is deleted.
`$post_id` int Required Attachment ID. File: `wp-admin/includes/class-wp-site-icon.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-icon.php/)
```
public function delete_attachment_data( $post_id ) {
$site_icon_id = get_option( 'site_icon' );
if ( $site_icon_id && $post_id == $site_icon_id ) {
delete_option( 'site_icon' );
}
}
```
| Uses | Description |
| --- | --- |
| [delete\_option()](../../functions/delete_option) wp-includes/option.php | Removes option by name. Prevents removal of protected WordPress options. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Site_Icon::intermediate_image_sizes( string[] $sizes = array() ): string[] WP\_Site\_Icon::intermediate\_image\_sizes( string[] $sizes = array() ): string[]
=================================================================================
Adds Site Icon sizes to the array of image sizes on demand.
`$sizes` string[] Optional Array of image size names. Default: `array()`
string[] Array of image size names.
File: `wp-admin/includes/class-wp-site-icon.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-icon.php/)
```
public function intermediate_image_sizes( $sizes = array() ) {
/** This filter is documented in wp-admin/includes/class-wp-site-icon.php */
$this->site_icon_sizes = apply_filters( 'site_icon_image_sizes', $this->site_icon_sizes );
foreach ( $this->site_icon_sizes as $size ) {
$sizes[] = 'site_icon-' . $size;
}
return $sizes;
}
```
[apply\_filters( 'site\_icon\_image\_sizes', int[] $site\_icon\_sizes )](../../hooks/site_icon_image_sizes)
Filters the different dimensions that a site icon is saved in.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Site_Icon::__construct() WP\_Site\_Icon::\_\_construct()
===============================
Registers actions and filters.
File: `wp-admin/includes/class-wp-site-icon.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-icon.php/)
```
public function __construct() {
add_action( 'delete_attachment', array( $this, 'delete_attachment_data' ) );
add_filter( 'get_post_metadata', array( $this, 'get_post_metadata' ), 10, 4 );
}
```
| Uses | Description |
| --- | --- |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_ajax\_crop\_image()](../../functions/wp_ajax_crop_image) wp-admin/includes/ajax-actions.php | Ajax handler for cropping an image. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress IXR_Request::IXR_Request( $method, $args ) IXR\_Request::IXR\_Request( $method, $args )
============================================
PHP4 constructor.
File: `wp-includes/IXR/class-IXR-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-request.php/)
```
public function IXR_Request( $method, $args ) {
self::__construct( $method, $args );
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Request::\_\_construct()](__construct) wp-includes/IXR/class-IXR-request.php | PHP5 constructor. |
| programming_docs |
wordpress IXR_Request::getXml() IXR\_Request::getXml()
======================
File: `wp-includes/IXR/class-IXR-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-request.php/)
```
function getXml()
{
return $this->xml;
}
```
wordpress IXR_Request::__construct( $method, $args ) IXR\_Request::\_\_construct( $method, $args )
=============================================
PHP5 constructor.
File: `wp-includes/IXR/class-IXR-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-request.php/)
```
function __construct($method, $args)
{
$this->method = $method;
$this->args = $args;
$this->xml = <<<EOD
<?xml version="1.0"?>
<methodCall>
<methodName>{$this->method}</methodName>
<params>
EOD;
foreach ($this->args as $arg) {
$this->xml .= '<param><value>';
$v = new IXR_Value($arg);
$this->xml .= $v->getXml();
$this->xml .= "</value></param>\n";
}
$this->xml .= '</params></methodCall>';
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Value::\_\_construct()](../ixr_value/__construct) wp-includes/IXR/class-IXR-value.php | PHP5 constructor. |
| Used By | Description |
| --- | --- |
| [IXR\_Request::IXR\_Request()](ixr_request) wp-includes/IXR/class-IXR-request.php | PHP4 constructor. |
| [IXR\_Client::query()](../ixr_client/query) wp-includes/IXR/class-IXR-client.php | |
| [WP\_HTTP\_IXR\_Client::query()](../wp_http_ixr_client/query) wp-includes/class-wp-http-ixr-client.php | |
wordpress IXR_Request::getLength() IXR\_Request::getLength()
=========================
File: `wp-includes/IXR/class-IXR-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-request.php/)
```
function getLength()
{
return strlen($this->xml);
}
```
wordpress WP_HTTP_Proxy::is_enabled(): bool WP\_HTTP\_Proxy::is\_enabled(): bool
====================================
Whether proxy connection should be used.
Constants which control this behaviour:
* `WP_PROXY_HOST`
* `WP_PROXY_PORT`
bool
File: `wp-includes/class-wp-http-proxy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-proxy.php/)
```
public function is_enabled() {
return defined( 'WP_PROXY_HOST' ) && defined( 'WP_PROXY_PORT' );
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_HTTP_Proxy::port(): string WP\_HTTP\_Proxy::port(): string
===============================
Retrieve the port for the proxy server.
string
File: `wp-includes/class-wp-http-proxy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-proxy.php/)
```
public function port() {
if ( defined( 'WP_PROXY_PORT' ) ) {
return WP_PROXY_PORT;
}
return '';
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_HTTP_Proxy::send_through_proxy( string $uri ): bool WP\_HTTP\_Proxy::send\_through\_proxy( string $uri ): bool
==========================================================
Determines whether the request should be sent through a proxy.
We want to keep localhost and the site URL from being sent through the proxy, because some proxies can not handle this. We also have the constant available for defining other hosts that won’t be sent through the proxy.
`$uri` string Required URL of the request. bool Whether to send the request through the proxy.
File: `wp-includes/class-wp-http-proxy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-proxy.php/)
```
public function send_through_proxy( $uri ) {
$check = parse_url( $uri );
// Malformed URL, can not process, but this could mean ssl, so let through anyway.
if ( false === $check ) {
return true;
}
$home = parse_url( get_option( 'siteurl' ) );
/**
* Filters whether to preempt sending the request through the proxy.
*
* Returning false will bypass the proxy; returning true will send
* the request through the proxy. Returning null bypasses the filter.
*
* @since 3.5.0
*
* @param bool|null $override Whether to send the request through the proxy. Default null.
* @param string $uri URL of the request.
* @param array $check Associative array result of parsing the request URL with `parse_url()`.
* @param array $home Associative array result of parsing the site URL with `parse_url()`.
*/
$result = apply_filters( 'pre_http_send_through_proxy', null, $uri, $check, $home );
if ( ! is_null( $result ) ) {
return $result;
}
if ( 'localhost' === $check['host'] || ( isset( $home['host'] ) && $home['host'] === $check['host'] ) ) {
return false;
}
if ( ! defined( 'WP_PROXY_BYPASS_HOSTS' ) ) {
return true;
}
static $bypass_hosts = null;
static $wildcard_regex = array();
if ( null === $bypass_hosts ) {
$bypass_hosts = preg_split( '|,\s*|', WP_PROXY_BYPASS_HOSTS );
if ( false !== strpos( WP_PROXY_BYPASS_HOSTS, '*' ) ) {
$wildcard_regex = array();
foreach ( $bypass_hosts as $host ) {
$wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
}
$wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i';
}
}
if ( ! empty( $wildcard_regex ) ) {
return ! preg_match( $wildcard_regex, $check['host'] );
} else {
return ! in_array( $check['host'], $bypass_hosts, true );
}
}
```
[apply\_filters( 'pre\_http\_send\_through\_proxy', bool|null $override, string $uri, array $check, array $home )](../../hooks/pre_http_send_through_proxy)
Filters whether to preempt sending the request through the proxy.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_HTTP_Proxy::username(): string WP\_HTTP\_Proxy::username(): string
===================================
Retrieve the username for proxy authentication.
string
File: `wp-includes/class-wp-http-proxy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-proxy.php/)
```
public function username() {
if ( defined( 'WP_PROXY_USERNAME' ) ) {
return WP_PROXY_USERNAME;
}
return '';
}
```
| Used By | Description |
| --- | --- |
| [WP\_HTTP\_Proxy::authentication()](authentication) wp-includes/class-wp-http-proxy.php | Retrieve authentication string for proxy authentication. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_HTTP_Proxy::authentication(): string WP\_HTTP\_Proxy::authentication(): string
=========================================
Retrieve authentication string for proxy authentication.
string
File: `wp-includes/class-wp-http-proxy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-proxy.php/)
```
public function authentication() {
return $this->username() . ':' . $this->password();
}
```
| Uses | Description |
| --- | --- |
| [WP\_HTTP\_Proxy::username()](username) wp-includes/class-wp-http-proxy.php | Retrieve the username for proxy authentication. |
| [WP\_HTTP\_Proxy::password()](password) wp-includes/class-wp-http-proxy.php | Retrieve the password for proxy authentication. |
| Used By | Description |
| --- | --- |
| [WP\_HTTP\_Proxy::authentication\_header()](authentication_header) wp-includes/class-wp-http-proxy.php | Retrieve header string for proxy authentication. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_HTTP_Proxy::authentication_header(): string WP\_HTTP\_Proxy::authentication\_header(): string
=================================================
Retrieve header string for proxy authentication.
string
File: `wp-includes/class-wp-http-proxy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-proxy.php/)
```
public function authentication_header() {
return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() );
}
```
| Uses | Description |
| --- | --- |
| [WP\_HTTP\_Proxy::authentication()](authentication) wp-includes/class-wp-http-proxy.php | Retrieve authentication string for proxy authentication. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_HTTP_Proxy::host(): string WP\_HTTP\_Proxy::host(): string
===============================
Retrieve the host for the proxy server.
string
File: `wp-includes/class-wp-http-proxy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-proxy.php/)
```
public function host() {
if ( defined( 'WP_PROXY_HOST' ) ) {
return WP_PROXY_HOST;
}
return '';
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_HTTP_Proxy::password(): string WP\_HTTP\_Proxy::password(): string
===================================
Retrieve the password for proxy authentication.
string
File: `wp-includes/class-wp-http-proxy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-proxy.php/)
```
public function password() {
if ( defined( 'WP_PROXY_PASSWORD' ) ) {
return WP_PROXY_PASSWORD;
}
return '';
}
```
| Used By | Description |
| --- | --- |
| [WP\_HTTP\_Proxy::authentication()](authentication) wp-includes/class-wp-http-proxy.php | Retrieve authentication string for proxy authentication. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_HTTP_Proxy::use_authentication(): bool WP\_HTTP\_Proxy::use\_authentication(): bool
============================================
Whether authentication should be used.
Constants which control this behaviour:
* `WP_PROXY_USERNAME`
* `WP_PROXY_PASSWORD`
bool
File: `wp-includes/class-wp-http-proxy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-proxy.php/)
```
public function use_authentication() {
return defined( 'WP_PROXY_USERNAME' ) && defined( 'WP_PROXY_PASSWORD' );
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Recovery_Mode_Cookie_Service::get_session_id_from_cookie( string $cookie = '' ): string|WP_Error WP\_Recovery\_Mode\_Cookie\_Service::get\_session\_id\_from\_cookie( string $cookie = '' ): string|WP\_Error
============================================================================================================
Gets the session identifier from the cookie.
The cookie should be validated before calling this API.
`$cookie` string Optional y specify the cookie string.
If omitted, it will be retrieved from the super global. Default: `''`
string|[WP\_Error](../wp_error) Session ID on success, or error object on failure.
File: `wp-includes/class-wp-recovery-mode-cookie-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-cookie-service.php/)
```
public function get_session_id_from_cookie( $cookie = '' ) {
if ( ! $cookie ) {
if ( empty( $_COOKIE[ RECOVERY_MODE_COOKIE ] ) ) {
return new WP_Error( 'no_cookie', __( 'No cookie present.' ) );
}
$cookie = $_COOKIE[ RECOVERY_MODE_COOKIE ];
}
$parts = $this->parse_cookie( $cookie );
if ( is_wp_error( $parts ) ) {
return $parts;
}
list( , , $random ) = $parts;
return sha1( $random );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Cookie\_Service::parse\_cookie()](parse_cookie) wp-includes/class-wp-recovery-mode-cookie-service.php | Parses the cookie into its four parts. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Recovery_Mode_Cookie_Service::validate_cookie( string $cookie = '' ): true|WP_Error WP\_Recovery\_Mode\_Cookie\_Service::validate\_cookie( string $cookie = '' ): true|WP\_Error
============================================================================================
Validates the recovery mode cookie.
`$cookie` string Optional y specify the cookie string.
If omitted, it will be retrieved from the super global. Default: `''`
true|[WP\_Error](../wp_error) True on success, error object on failure.
File: `wp-includes/class-wp-recovery-mode-cookie-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-cookie-service.php/)
```
public function validate_cookie( $cookie = '' ) {
if ( ! $cookie ) {
if ( empty( $_COOKIE[ RECOVERY_MODE_COOKIE ] ) ) {
return new WP_Error( 'no_cookie', __( 'No cookie present.' ) );
}
$cookie = $_COOKIE[ RECOVERY_MODE_COOKIE ];
}
$parts = $this->parse_cookie( $cookie );
if ( is_wp_error( $parts ) ) {
return $parts;
}
list( , $created_at, $random, $signature ) = $parts;
if ( ! ctype_digit( $created_at ) ) {
return new WP_Error( 'invalid_created_at', __( 'Invalid cookie format.' ) );
}
/** This filter is documented in wp-includes/class-wp-recovery-mode-cookie-service.php */
$length = apply_filters( 'recovery_mode_cookie_length', WEEK_IN_SECONDS );
if ( time() > $created_at + $length ) {
return new WP_Error( 'expired', __( 'Cookie expired.' ) );
}
$to_sign = sprintf( 'recovery_mode|%s|%s', $created_at, $random );
$hashed = $this->recovery_mode_hash( $to_sign );
if ( ! hash_equals( $signature, $hashed ) ) {
return new WP_Error( 'signature_mismatch', __( 'Invalid cookie.' ) );
}
return true;
}
```
[apply\_filters( 'recovery\_mode\_cookie\_length', int $length )](../../hooks/recovery_mode_cookie_length)
Filters the length of time a Recovery Mode cookie is valid for.
| Uses | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Cookie\_Service::parse\_cookie()](parse_cookie) wp-includes/class-wp-recovery-mode-cookie-service.php | Parses the cookie into its four parts. |
| [WP\_Recovery\_Mode\_Cookie\_Service::recovery\_mode\_hash()](recovery_mode_hash) wp-includes/class-wp-recovery-mode-cookie-service.php | Gets a form of `wp_hash()` specific to Recovery Mode. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Recovery_Mode_Cookie_Service::is_cookie_set(): bool WP\_Recovery\_Mode\_Cookie\_Service::is\_cookie\_set(): bool
============================================================
Checks whether the recovery mode cookie is set.
bool True if the cookie is set, false otherwise.
File: `wp-includes/class-wp-recovery-mode-cookie-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-cookie-service.php/)
```
public function is_cookie_set() {
return ! empty( $_COOKIE[ RECOVERY_MODE_COOKIE ] );
}
```
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Recovery_Mode_Cookie_Service::generate_cookie(): string WP\_Recovery\_Mode\_Cookie\_Service::generate\_cookie(): string
===============================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Generates the recovery mode cookie value.
The cookie is a base64 encoded string with the following format:
recovery\_mode|iat|rand|signature
Where "recovery\_mode" is a constant string, iat is the time the cookie was generated at, rand is a randomly generated password that is also used as a session identifier and signature is an hmac of the preceding 3 parts.
string Generated cookie content.
File: `wp-includes/class-wp-recovery-mode-cookie-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-cookie-service.php/)
```
private function generate_cookie() {
$to_sign = sprintf( 'recovery_mode|%s|%s', time(), wp_generate_password( 20, false ) );
$signed = $this->recovery_mode_hash( $to_sign );
return base64_encode( sprintf( '%s|%s', $to_sign, $signed ) );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Cookie\_Service::recovery\_mode\_hash()](recovery_mode_hash) wp-includes/class-wp-recovery-mode-cookie-service.php | Gets a form of `wp_hash()` specific to Recovery Mode. |
| [wp\_generate\_password()](../../functions/wp_generate_password) wp-includes/pluggable.php | Generates a random password drawn from the defined set of characters. |
| Used By | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Cookie\_Service::set\_cookie()](set_cookie) wp-includes/class-wp-recovery-mode-cookie-service.php | Sets the recovery mode cookie. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Recovery_Mode_Cookie_Service::recovery_mode_hash( string $data ): string|false WP\_Recovery\_Mode\_Cookie\_Service::recovery\_mode\_hash( string $data ): string|false
=======================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Gets a form of `wp_hash()` specific to Recovery Mode.
We cannot use `wp_hash()` because it is defined in `pluggable.php` which is not loaded until after plugins are loaded, which is too late to verify the recovery mode cookie.
This tries to use the `AUTH` salts first, but if they aren’t valid specific salts will be generated and stored.
`$data` string Required Data to hash. string|false The hashed $data, or false on failure.
File: `wp-includes/class-wp-recovery-mode-cookie-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-cookie-service.php/)
```
private function recovery_mode_hash( $data ) {
$default_keys = array_unique(
array(
'put your unique phrase here',
/*
* translators: This string should only be translated if wp-config-sample.php is localized.
* You can check the localized release package or
* https://i18n.svn.wordpress.org/<locale code>/branches/<wp version>/dist/wp-config-sample.php
*/
__( 'put your unique phrase here' ),
)
);
if ( ! defined( 'AUTH_KEY' ) || in_array( AUTH_KEY, $default_keys, true ) ) {
$auth_key = get_site_option( 'recovery_mode_auth_key' );
if ( ! $auth_key ) {
if ( ! function_exists( 'wp_generate_password' ) ) {
require_once ABSPATH . WPINC . '/pluggable.php';
}
$auth_key = wp_generate_password( 64, true, true );
update_site_option( 'recovery_mode_auth_key', $auth_key );
}
} else {
$auth_key = AUTH_KEY;
}
if ( ! defined( 'AUTH_SALT' ) || in_array( AUTH_SALT, $default_keys, true ) || AUTH_SALT === $auth_key ) {
$auth_salt = get_site_option( 'recovery_mode_auth_salt' );
if ( ! $auth_salt ) {
if ( ! function_exists( 'wp_generate_password' ) ) {
require_once ABSPATH . WPINC . '/pluggable.php';
}
$auth_salt = wp_generate_password( 64, true, true );
update_site_option( 'recovery_mode_auth_salt', $auth_salt );
}
} else {
$auth_salt = AUTH_SALT;
}
$secret = $auth_key . $auth_salt;
return hash_hmac( 'sha1', $data, $secret );
}
```
| Uses | Description |
| --- | --- |
| [update\_site\_option()](../../functions/update_site_option) wp-includes/option.php | Updates the value of an option that was already added for the current network. |
| [wp\_generate\_password()](../../functions/wp_generate_password) wp-includes/pluggable.php | Generates a random password drawn from the defined set of characters. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_site\_option()](../../functions/get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| Used By | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Cookie\_Service::validate\_cookie()](validate_cookie) wp-includes/class-wp-recovery-mode-cookie-service.php | Validates the recovery mode cookie. |
| [WP\_Recovery\_Mode\_Cookie\_Service::generate\_cookie()](generate_cookie) wp-includes/class-wp-recovery-mode-cookie-service.php | Generates the recovery mode cookie value. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Recovery_Mode_Cookie_Service::set_cookie() WP\_Recovery\_Mode\_Cookie\_Service::set\_cookie()
==================================================
Sets the recovery mode cookie.
This must be immediately followed by exiting the request.
File: `wp-includes/class-wp-recovery-mode-cookie-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-cookie-service.php/)
```
public function set_cookie() {
$value = $this->generate_cookie();
/**
* Filters the length of time a Recovery Mode cookie is valid for.
*
* @since 5.2.0
*
* @param int $length Length in seconds.
*/
$length = apply_filters( 'recovery_mode_cookie_length', WEEK_IN_SECONDS );
$expire = time() + $length;
setcookie( RECOVERY_MODE_COOKIE, $value, $expire, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
if ( COOKIEPATH !== SITECOOKIEPATH ) {
setcookie( RECOVERY_MODE_COOKIE, $value, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
}
}
```
[apply\_filters( 'recovery\_mode\_cookie\_length', int $length )](../../hooks/recovery_mode_cookie_length)
Filters the length of time a Recovery Mode cookie is valid for.
| Uses | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Cookie\_Service::generate\_cookie()](generate_cookie) wp-includes/class-wp-recovery-mode-cookie-service.php | Generates the recovery mode cookie value. |
| [is\_ssl()](../../functions/is_ssl) wp-includes/load.php | Determines if SSL is used. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Recovery_Mode_Cookie_Service::clear_cookie() WP\_Recovery\_Mode\_Cookie\_Service::clear\_cookie()
====================================================
Clears the recovery mode cookie.
File: `wp-includes/class-wp-recovery-mode-cookie-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-cookie-service.php/)
```
public function clear_cookie() {
setcookie( RECOVERY_MODE_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
setcookie( RECOVERY_MODE_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
}
```
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Recovery_Mode_Cookie_Service::parse_cookie( string $cookie ): array|WP_Error WP\_Recovery\_Mode\_Cookie\_Service::parse\_cookie( string $cookie ): array|WP\_Error
=====================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Parses the cookie into its four parts.
`$cookie` string Required Cookie content. array|[WP\_Error](../wp_error) Cookie parts array, or error object on failure.
File: `wp-includes/class-wp-recovery-mode-cookie-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-cookie-service.php/)
```
private function parse_cookie( $cookie ) {
$cookie = base64_decode( $cookie );
$parts = explode( '|', $cookie );
if ( 4 !== count( $parts ) ) {
return new WP_Error( 'invalid_format', __( 'Invalid cookie format.' ) );
}
return $parts;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Cookie\_Service::validate\_cookie()](validate_cookie) wp-includes/class-wp-recovery-mode-cookie-service.php | Validates the recovery mode cookie. |
| [WP\_Recovery\_Mode\_Cookie\_Service::get\_session\_id\_from\_cookie()](get_session_id_from_cookie) wp-includes/class-wp-recovery-mode-cookie-service.php | Gets the session identifier from the cookie. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_User_Query::parse_order( string $order ): string WP\_User\_Query::parse\_order( string $order ): string
======================================================
Parses an ‘order’ query variable and casts it to ASC or DESC as necessary.
`$order` string Required The `'order'` query variable. string The sanitized `'order'` query variable.
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
protected function parse_order( $order ) {
if ( ! is_string( $order ) || empty( $order ) ) {
return 'DESC';
}
if ( 'ASC' === strtoupper( $order ) ) {
return 'ASC';
} else {
return 'DESC';
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_User\_Query::prepare\_query()](prepare_query) wp-includes/class-wp-user-query.php | Prepares the query variables. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_User_Query::prepare_query( string|array $query = array() ) WP\_User\_Query::prepare\_query( string|array $query = array() )
================================================================
Prepares the query variables.
`$query` string|array Optional Array or string of Query parameters.
* `blog_id`intThe site ID. Default is the current site.
* `role`string|string[]An array or a comma-separated list of role names that users must match to be included in results. Note that this is an inclusive list: users must match \*each\* role.
* `role__in`string[]An array of role names. Matched users must have at least one of these roles.
* `role__not_in`string[]An array of role names to exclude. Users matching one or more of these roles will not be included in results.
* `meta_key`string|string[]Meta key or keys to filter by.
* `meta_value`string|string[]Meta value or values to filter by.
* `meta_compare`stringMySQL operator used for comparing the meta value.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_compare_key`stringMySQL operator used for comparing the meta key.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type`stringMySQL data type that the meta\_value column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type_key`stringMySQL data type that the meta\_key column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_query`arrayAn associative array of [WP\_Meta\_Query](../wp_meta_query) arguments.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values.
* `capability`string|string[]An array or a comma-separated list of capability names that users must match to be included in results. Note that this is an inclusive list: users must match \*each\* capability.
Does NOT work for capabilities not in the database or filtered via ['map\_meta\_cap'](../../hooks/map_meta_cap).
* `capability__in`string[]An array of capability names. Matched users must have at least one of these capabilities.
Does NOT work for capabilities not in the database or filtered via ['map\_meta\_cap'](../../hooks/map_meta_cap).
* `capability__not_in`string[]An array of capability names to exclude. Users matching one or more of these capabilities will not be included in results.
Does NOT work for capabilities not in the database or filtered via ['map\_meta\_cap'](../../hooks/map_meta_cap).
* `include`int[]An array of user IDs to include.
* `exclude`int[]An array of user IDs to exclude.
* `search`stringSearch keyword. Searches for possible string matches on columns.
When `$search_columns` is left empty, it tries to determine which column to search in based on search string.
* `search_columns`string[]Array of column names to be searched. Accepts `'ID'`, `'user_login'`, `'user_email'`, `'user_url'`, `'user_nicename'`, `'display_name'`.
* `orderby`string|arrayField(s) to sort the retrieved users by. May be a single value, an array of values, or a multi-dimensional array with fields as keys and orders (`'ASC'` or `'DESC'`) as values. Accepted values are:
+ `'ID'`
+ `'display_name'` (or `'name'`)
+ `'include'`
+ `'user_login'` (or `'login'`)
+ `'login__in'`
+ `'user_nicename'` (or `'nicename'`),
+ `'nicename__in'`
+ 'user\_email (or `'email'`)
+ `'user_url'` (or `'url'`),
+ `'user_registered'` (or `'registered'`)
+ `'post_count'`
+ `'meta_value'`,
+ `'meta_value_num'`
+ The value of `$meta_key`
+ An array key of `$meta_query` To use `'meta_value'` or `'meta_value_num'`, `$meta_key` must be also be defined. Default `'user_login'`.
* `order`stringDesignates ascending or descending order of users. Order values passed as part of an `$orderby` array take precedence over this parameter. Accepts `'ASC'`, `'DESC'`. Default `'ASC'`.
* `offset`intNumber of users to offset in retrieved results. Can be used in conjunction with pagination. Default 0.
* `number`intNumber of users to limit the query for. Can be used in conjunction with pagination. Value -1 (all) is supported, but should be used with caution on larger sites.
Default -1 (all users).
* `paged`intWhen used with number, defines the page of results to return.
Default 1.
* `count_total`boolWhether to count the total number of users found. If pagination is not needed, setting this to false can improve performance.
Default true.
* `fields`string|string[]Which fields to return. Single or all fields (string), or array of fields. Accepts:
+ `'ID'`
+ `'display_name'`
+ `'user_login'`
+ `'user_nicename'`
+ `'user_email'`
+ `'user_url'`
+ `'user_registered'`
+ `'user_pass'`
+ `'user_activation_key'`
+ `'user_status'`
+ `'spam'` (only available on multisite installs)
+ `'deleted'` (only available on multisite installs)
+ `'all'` for all fields and loads user meta.
+ `'all_with_meta'` Deprecated. Use `'all'`. Default `'all'`.
* `who`stringType of users to query. Accepts `'authors'`.
Default empty (all users).
* `has_published_posts`bool|string[]Pass an array of post types to filter results to users who have published posts in those post types. `true` is an alias for all public post types.
* `nicename`stringThe user nicename.
* `nicename__in`string[]An array of nicenames to include. Users matching one of these nicenames will be included in results.
* `nicename__not_in`string[]An array of nicenames to exclude. Users matching one of these nicenames will not be included in results.
* `login`stringThe user login.
* `login__in`string[]An array of logins to include. Users matching one of these logins will be included in results.
* `login__not_in`string[]An array of logins to exclude. Users matching one of these logins will not be included in results.
Default: `array()`
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
public function prepare_query( $query = array() ) {
global $wpdb, $wp_roles;
if ( empty( $this->query_vars ) || ! empty( $query ) ) {
$this->query_limit = null;
$this->query_vars = $this->fill_query_vars( $query );
}
/**
* Fires before the WP_User_Query has been parsed.
*
* The passed WP_User_Query object contains the query variables,
* not yet passed into SQL.
*
* @since 4.0.0
*
* @param WP_User_Query $query Current instance of WP_User_Query (passed by reference).
*/
do_action_ref_array( 'pre_get_users', array( &$this ) );
// Ensure that query vars are filled after 'pre_get_users'.
$qv =& $this->query_vars;
$qv = $this->fill_query_vars( $qv );
$allowed_fields = array(
'id',
'user_login',
'user_pass',
'user_nicename',
'user_email',
'user_url',
'user_registered',
'user_activation_key',
'user_status',
'display_name',
);
if ( is_multisite() ) {
$allowed_fields[] = 'spam';
$allowed_fields[] = 'deleted';
}
if ( is_array( $qv['fields'] ) ) {
$qv['fields'] = array_map( 'strtolower', $qv['fields'] );
$qv['fields'] = array_intersect( array_unique( $qv['fields'] ), $allowed_fields );
if ( empty( $qv['fields'] ) ) {
$qv['fields'] = array( 'id' );
}
$this->query_fields = array();
foreach ( $qv['fields'] as $field ) {
$field = 'id' === $field ? 'ID' : sanitize_key( $field );
$this->query_fields[] = "$wpdb->users.$field";
}
$this->query_fields = implode( ',', $this->query_fields );
} elseif ( 'all_with_meta' === $qv['fields'] || 'all' === $qv['fields'] || ! in_array( $qv['fields'], $allowed_fields, true ) ) {
$this->query_fields = "$wpdb->users.ID";
} else {
$field = 'id' === strtolower( $qv['fields'] ) ? 'ID' : sanitize_key( $qv['fields'] );
$this->query_fields = "$wpdb->users.$field";
}
if ( isset( $qv['count_total'] ) && $qv['count_total'] ) {
$this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
}
$this->query_from = "FROM $wpdb->users";
$this->query_where = 'WHERE 1=1';
// Parse and sanitize 'include', for use by 'orderby' as well as 'include' below.
if ( ! empty( $qv['include'] ) ) {
$include = wp_parse_id_list( $qv['include'] );
} else {
$include = false;
}
$blog_id = 0;
if ( isset( $qv['blog_id'] ) ) {
$blog_id = absint( $qv['blog_id'] );
}
if ( $qv['has_published_posts'] && $blog_id ) {
if ( true === $qv['has_published_posts'] ) {
$post_types = get_post_types( array( 'public' => true ) );
} else {
$post_types = (array) $qv['has_published_posts'];
}
foreach ( $post_types as &$post_type ) {
$post_type = $wpdb->prepare( '%s', $post_type );
}
$posts_table = $wpdb->get_blog_prefix( $blog_id ) . 'posts';
$this->query_where .= " AND $wpdb->users.ID IN ( SELECT DISTINCT $posts_table.post_author FROM $posts_table WHERE $posts_table.post_status = 'publish' AND $posts_table.post_type IN ( " . implode( ', ', $post_types ) . ' ) )';
}
// nicename
if ( '' !== $qv['nicename'] ) {
$this->query_where .= $wpdb->prepare( ' AND user_nicename = %s', $qv['nicename'] );
}
if ( ! empty( $qv['nicename__in'] ) ) {
$sanitized_nicename__in = array_map( 'esc_sql', $qv['nicename__in'] );
$nicename__in = implode( "','", $sanitized_nicename__in );
$this->query_where .= " AND user_nicename IN ( '$nicename__in' )";
}
if ( ! empty( $qv['nicename__not_in'] ) ) {
$sanitized_nicename__not_in = array_map( 'esc_sql', $qv['nicename__not_in'] );
$nicename__not_in = implode( "','", $sanitized_nicename__not_in );
$this->query_where .= " AND user_nicename NOT IN ( '$nicename__not_in' )";
}
// login
if ( '' !== $qv['login'] ) {
$this->query_where .= $wpdb->prepare( ' AND user_login = %s', $qv['login'] );
}
if ( ! empty( $qv['login__in'] ) ) {
$sanitized_login__in = array_map( 'esc_sql', $qv['login__in'] );
$login__in = implode( "','", $sanitized_login__in );
$this->query_where .= " AND user_login IN ( '$login__in' )";
}
if ( ! empty( $qv['login__not_in'] ) ) {
$sanitized_login__not_in = array_map( 'esc_sql', $qv['login__not_in'] );
$login__not_in = implode( "','", $sanitized_login__not_in );
$this->query_where .= " AND user_login NOT IN ( '$login__not_in' )";
}
// Meta query.
$this->meta_query = new WP_Meta_Query();
$this->meta_query->parse_query_vars( $qv );
if ( isset( $qv['who'] ) && 'authors' === $qv['who'] && $blog_id ) {
_deprecated_argument(
'WP_User_Query',
'5.9.0',
sprintf(
/* translators: 1: who, 2: capability */
__( '%1$s is deprecated. Use %2$s instead.' ),
'<code>who</code>',
'<code>capability</code>'
)
);
$who_query = array(
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'user_level',
'value' => 0,
'compare' => '!=',
);
// Prevent extra meta query.
$qv['blog_id'] = 0;
$blog_id = 0;
if ( empty( $this->meta_query->queries ) ) {
$this->meta_query->queries = array( $who_query );
} else {
// Append the cap query to the original queries and reparse the query.
$this->meta_query->queries = array(
'relation' => 'AND',
array( $this->meta_query->queries, $who_query ),
);
}
$this->meta_query->parse_query_vars( $this->meta_query->queries );
}
// Roles.
$roles = array();
if ( isset( $qv['role'] ) ) {
if ( is_array( $qv['role'] ) ) {
$roles = $qv['role'];
} elseif ( is_string( $qv['role'] ) && ! empty( $qv['role'] ) ) {
$roles = array_map( 'trim', explode( ',', $qv['role'] ) );
}
}
$role__in = array();
if ( isset( $qv['role__in'] ) ) {
$role__in = (array) $qv['role__in'];
}
$role__not_in = array();
if ( isset( $qv['role__not_in'] ) ) {
$role__not_in = (array) $qv['role__not_in'];
}
// Capabilities.
$available_roles = array();
if ( ! empty( $qv['capability'] ) || ! empty( $qv['capability__in'] ) || ! empty( $qv['capability__not_in'] ) ) {
$wp_roles->for_site( $blog_id );
$available_roles = $wp_roles->roles;
}
$capabilities = array();
if ( ! empty( $qv['capability'] ) ) {
if ( is_array( $qv['capability'] ) ) {
$capabilities = $qv['capability'];
} elseif ( is_string( $qv['capability'] ) ) {
$capabilities = array_map( 'trim', explode( ',', $qv['capability'] ) );
}
}
$capability__in = array();
if ( ! empty( $qv['capability__in'] ) ) {
$capability__in = (array) $qv['capability__in'];
}
$capability__not_in = array();
if ( ! empty( $qv['capability__not_in'] ) ) {
$capability__not_in = (array) $qv['capability__not_in'];
}
// Keep track of all capabilities and the roles they're added on.
$caps_with_roles = array();
foreach ( $available_roles as $role => $role_data ) {
$role_caps = array_keys( array_filter( $role_data['capabilities'] ) );
foreach ( $capabilities as $cap ) {
if ( in_array( $cap, $role_caps, true ) ) {
$caps_with_roles[ $cap ][] = $role;
break;
}
}
foreach ( $capability__in as $cap ) {
if ( in_array( $cap, $role_caps, true ) ) {
$role__in[] = $role;
break;
}
}
foreach ( $capability__not_in as $cap ) {
if ( in_array( $cap, $role_caps, true ) ) {
$role__not_in[] = $role;
break;
}
}
}
$role__in = array_merge( $role__in, $capability__in );
$role__not_in = array_merge( $role__not_in, $capability__not_in );
$roles = array_unique( $roles );
$role__in = array_unique( $role__in );
$role__not_in = array_unique( $role__not_in );
// Support querying by capabilities added directly to users.
if ( $blog_id && ! empty( $capabilities ) ) {
$capabilities_clauses = array( 'relation' => 'AND' );
foreach ( $capabilities as $cap ) {
$clause = array( 'relation' => 'OR' );
$clause[] = array(
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
'value' => '"' . $cap . '"',
'compare' => 'LIKE',
);
if ( ! empty( $caps_with_roles[ $cap ] ) ) {
foreach ( $caps_with_roles[ $cap ] as $role ) {
$clause[] = array(
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
'value' => '"' . $role . '"',
'compare' => 'LIKE',
);
}
}
$capabilities_clauses[] = $clause;
}
$role_queries[] = $capabilities_clauses;
if ( empty( $this->meta_query->queries ) ) {
$this->meta_query->queries[] = $capabilities_clauses;
} else {
// Append the cap query to the original queries and reparse the query.
$this->meta_query->queries = array(
'relation' => 'AND',
array( $this->meta_query->queries, array( $capabilities_clauses ) ),
);
}
$this->meta_query->parse_query_vars( $this->meta_query->queries );
}
if ( $blog_id && ( ! empty( $roles ) || ! empty( $role__in ) || ! empty( $role__not_in ) || is_multisite() ) ) {
$role_queries = array();
$roles_clauses = array( 'relation' => 'AND' );
if ( ! empty( $roles ) ) {
foreach ( $roles as $role ) {
$roles_clauses[] = array(
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
'value' => '"' . $role . '"',
'compare' => 'LIKE',
);
}
$role_queries[] = $roles_clauses;
}
$role__in_clauses = array( 'relation' => 'OR' );
if ( ! empty( $role__in ) ) {
foreach ( $role__in as $role ) {
$role__in_clauses[] = array(
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
'value' => '"' . $role . '"',
'compare' => 'LIKE',
);
}
$role_queries[] = $role__in_clauses;
}
$role__not_in_clauses = array( 'relation' => 'AND' );
if ( ! empty( $role__not_in ) ) {
foreach ( $role__not_in as $role ) {
$role__not_in_clauses[] = array(
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
'value' => '"' . $role . '"',
'compare' => 'NOT LIKE',
);
}
$role_queries[] = $role__not_in_clauses;
}
// If there are no specific roles named, make sure the user is a member of the site.
if ( empty( $role_queries ) ) {
$role_queries[] = array(
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
'compare' => 'EXISTS',
);
}
// Specify that role queries should be joined with AND.
$role_queries['relation'] = 'AND';
if ( empty( $this->meta_query->queries ) ) {
$this->meta_query->queries = $role_queries;
} else {
// Append the cap query to the original queries and reparse the query.
$this->meta_query->queries = array(
'relation' => 'AND',
array( $this->meta_query->queries, $role_queries ),
);
}
$this->meta_query->parse_query_vars( $this->meta_query->queries );
}
if ( ! empty( $this->meta_query->queries ) ) {
$clauses = $this->meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
$this->query_from .= $clauses['join'];
$this->query_where .= $clauses['where'];
if ( $this->meta_query->has_or_relation() ) {
$this->query_fields = 'DISTINCT ' . $this->query_fields;
}
}
// Sorting.
$qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
$order = $this->parse_order( $qv['order'] );
if ( empty( $qv['orderby'] ) ) {
// Default order is by 'user_login'.
$ordersby = array( 'user_login' => $order );
} elseif ( is_array( $qv['orderby'] ) ) {
$ordersby = $qv['orderby'];
} else {
// 'orderby' values may be a comma- or space-separated list.
$ordersby = preg_split( '/[,\s]+/', $qv['orderby'] );
}
$orderby_array = array();
foreach ( $ordersby as $_key => $_value ) {
if ( ! $_value ) {
continue;
}
if ( is_int( $_key ) ) {
// Integer key means this is a flat array of 'orderby' fields.
$_orderby = $_value;
$_order = $order;
} else {
// Non-integer key means this the key is the field and the value is ASC/DESC.
$_orderby = $_key;
$_order = $_value;
}
$parsed = $this->parse_orderby( $_orderby );
if ( ! $parsed ) {
continue;
}
if ( 'nicename__in' === $_orderby || 'login__in' === $_orderby ) {
$orderby_array[] = $parsed;
} else {
$orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
}
}
// If no valid clauses were found, order by user_login.
if ( empty( $orderby_array ) ) {
$orderby_array[] = "user_login $order";
}
$this->query_orderby = 'ORDER BY ' . implode( ', ', $orderby_array );
// Limit.
if ( isset( $qv['number'] ) && $qv['number'] > 0 ) {
if ( $qv['offset'] ) {
$this->query_limit = $wpdb->prepare( 'LIMIT %d, %d', $qv['offset'], $qv['number'] );
} else {
$this->query_limit = $wpdb->prepare( 'LIMIT %d, %d', $qv['number'] * ( $qv['paged'] - 1 ), $qv['number'] );
}
}
$search = '';
if ( isset( $qv['search'] ) ) {
$search = trim( $qv['search'] );
}
if ( $search ) {
$leading_wild = ( ltrim( $search, '*' ) != $search );
$trailing_wild = ( rtrim( $search, '*' ) != $search );
if ( $leading_wild && $trailing_wild ) {
$wild = 'both';
} elseif ( $leading_wild ) {
$wild = 'leading';
} elseif ( $trailing_wild ) {
$wild = 'trailing';
} else {
$wild = false;
}
if ( $wild ) {
$search = trim( $search, '*' );
}
$search_columns = array();
if ( $qv['search_columns'] ) {
$search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename', 'display_name' ) );
}
if ( ! $search_columns ) {
if ( false !== strpos( $search, '@' ) ) {
$search_columns = array( 'user_email' );
} elseif ( is_numeric( $search ) ) {
$search_columns = array( 'user_login', 'ID' );
} elseif ( preg_match( '|^https?://|', $search ) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) ) {
$search_columns = array( 'user_url' );
} else {
$search_columns = array( 'user_login', 'user_url', 'user_email', 'user_nicename', 'display_name' );
}
}
/**
* Filters the columns to search in a WP_User_Query search.
*
* The default columns depend on the search term, and include 'ID', 'user_login',
* 'user_email', 'user_url', 'user_nicename', and 'display_name'.
*
* @since 3.6.0
*
* @param string[] $search_columns Array of column names to be searched.
* @param string $search Text being searched.
* @param WP_User_Query $query The current WP_User_Query instance.
*/
$search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
$this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
}
if ( ! empty( $include ) ) {
// Sanitized earlier.
$ids = implode( ',', $include );
$this->query_where .= " AND $wpdb->users.ID IN ($ids)";
} elseif ( ! empty( $qv['exclude'] ) ) {
$ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
$this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
}
// Date queries are allowed for the user_registered field.
if ( ! empty( $qv['date_query'] ) && is_array( $qv['date_query'] ) ) {
$date_query = new WP_Date_Query( $qv['date_query'], 'user_registered' );
$this->query_where .= $date_query->get_sql();
}
/**
* Fires after the WP_User_Query has been parsed, and before
* the query is executed.
*
* The passed WP_User_Query object contains SQL parts formed
* from parsing the given query.
*
* @since 3.1.0
*
* @param WP_User_Query $query Current instance of WP_User_Query (passed by reference).
*/
do_action_ref_array( 'pre_user_query', array( &$this ) );
}
```
[do\_action\_ref\_array( 'pre\_get\_users', WP\_User\_Query $query )](../../hooks/pre_get_users)
Fires before the [WP\_User\_Query](../wp_user_query) has been parsed.
[do\_action\_ref\_array( 'pre\_user\_query', WP\_User\_Query $query )](../../hooks/pre_user_query)
Fires after the [WP\_User\_Query](../wp_user_query) has been parsed, and before the query is executed.
[apply\_filters( 'user\_search\_columns', string[] $search\_columns, string $search, WP\_User\_Query $query )](../../hooks/user_search_columns)
Filters the columns to search in a [WP\_User\_Query](../wp_user_query) search.
| Uses | Description |
| --- | --- |
| [WP\_Roles::for\_site()](../wp_roles/for_site) wp-includes/class-wp-roles.php | Sets the site to operate on. Defaults to the current site. |
| [WP\_User\_Query::fill\_query\_vars()](fill_query_vars) wp-includes/class-wp-user-query.php | Fills in missing query variables with default values. |
| [wpdb::get\_blog\_prefix()](../wpdb/get_blog_prefix) wp-includes/class-wpdb.php | Gets blog prefix. |
| [wp\_is\_large\_network()](../../functions/wp_is_large_network) wp-includes/ms-functions.php | Determines whether or not we have a large network. |
| [WP\_User\_Query::get\_search\_sql()](get_search_sql) wp-includes/class-wp-user-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| [do\_action\_ref\_array()](../../functions/do_action_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook, specifying arguments in an array. |
| [WP\_Date\_Query::\_\_construct()](../wp_date_query/__construct) wp-includes/class-wp-date-query.php | Constructor. |
| [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) wp-includes/class-wp-meta-query.php | Constructor. |
| [wp\_parse\_id\_list()](../../functions/wp_parse_id_list) wp-includes/functions.php | Cleans up an array, comma- or space-separated list of IDs. |
| [WP\_User\_Query::parse\_orderby()](parse_orderby) wp-includes/class-wp-user-query.php | Parses and sanitizes ‘orderby’ keys passed to the user query. |
| [WP\_User\_Query::parse\_order()](parse_order) wp-includes/class-wp-user-query.php | Parses an ‘order’ query variable and casts it to ASC or DESC as necessary. |
| [\_deprecated\_argument()](../../functions/_deprecated_argument) wp-includes/functions.php | Marks a function argument as deprecated and inform when it has been used. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [sanitize\_key()](../../functions/sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Used By | Description |
| --- | --- |
| [WP\_User\_Query::\_\_construct()](__construct) wp-includes/class-wp-user-query.php | PHP5 constructor. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Added `'capability'`, `'capability__in'`, and `'capability__not_in'` parameters. |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced the `'meta_type_key'` parameter. |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Introduced the `'meta_compare_key'` parameter. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Added `'nicename'`, `'nicename__in'`, `'nicename__not_in'`, `'login'`, `'login__in'`, and `'login__not_in'` parameters. |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Added `'paged'`, `'role__in'`, and `'role__not_in'` parameters. The `'role'` parameter was updated to permit an array or comma-separated list of values. The `'number'` parameter was updated to support querying for all users with using -1. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Added `'has_published_posts'` parameter. |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Added `'meta_value_num'` support for `$orderby` parameter. Added multi-dimensional array syntax for `$orderby` parameter. |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Added the ability to order by the `include` value. |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
| programming_docs |
wordpress WP_User_Query::__unset( string $name ) WP\_User\_Query::\_\_unset( string $name )
==========================================
Makes private properties un-settable for backward compatibility.
`$name` string Required Property to unset. File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
public function __unset( $name ) {
if ( in_array( $name, $this->compat_fields, true ) ) {
unset( $this->$name );
}
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_User_Query::get_results(): array WP\_User\_Query::get\_results(): array
======================================
Returns the list of users.
array Array of results.
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
public function get_results() {
return $this->results;
}
```
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_User_Query::get_total(): int WP\_User\_Query::get\_total(): int
==================================
Returns the total number of users for the current query.
int Number of total users.
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
public function get_total() {
return $this->total_users;
}
```
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_User_Query::__call( string $name, array $arguments ): mixed WP\_User\_Query::\_\_call( string $name, array $arguments ): mixed
==================================================================
Makes private/protected methods readable for backward compatibility.
`$name` string Required Method to call. `$arguments` array Required Arguments to pass when calling. mixed Return value of the callback, false otherwise.
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
public function __call( $name, $arguments ) {
if ( 'get_search_sql' === $name ) {
return $this->get_search_sql( ...$arguments );
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_User\_Query::get\_search\_sql()](get_search_sql) wp-includes/class-wp-user-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_User_Query::parse_orderby( string $orderby ): string WP\_User\_Query::parse\_orderby( string $orderby ): string
==========================================================
Parses and sanitizes ‘orderby’ keys passed to the user query.
`$orderby` string Required Alias for the field to order by. string Value to used in the ORDER clause, if `$orderby` is valid.
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
protected function parse_orderby( $orderby ) {
global $wpdb;
$meta_query_clauses = $this->meta_query->get_clauses();
$_orderby = '';
if ( in_array( $orderby, array( 'login', 'nicename', 'email', 'url', 'registered' ), true ) ) {
$_orderby = 'user_' . $orderby;
} elseif ( in_array( $orderby, array( 'user_login', 'user_nicename', 'user_email', 'user_url', 'user_registered' ), true ) ) {
$_orderby = $orderby;
} elseif ( 'name' === $orderby || 'display_name' === $orderby ) {
$_orderby = 'display_name';
} elseif ( 'post_count' === $orderby ) {
// @todo Avoid the JOIN.
$where = get_posts_by_author_sql( 'post' );
$this->query_from .= " LEFT OUTER JOIN (
SELECT post_author, COUNT(*) as post_count
FROM $wpdb->posts
$where
GROUP BY post_author
) p ON ({$wpdb->users}.ID = p.post_author)
";
$_orderby = 'post_count';
} elseif ( 'ID' === $orderby || 'id' === $orderby ) {
$_orderby = 'ID';
} elseif ( 'meta_value' === $orderby || $this->get( 'meta_key' ) == $orderby ) {
$_orderby = "$wpdb->usermeta.meta_value";
} elseif ( 'meta_value_num' === $orderby ) {
$_orderby = "$wpdb->usermeta.meta_value+0";
} elseif ( 'include' === $orderby && ! empty( $this->query_vars['include'] ) ) {
$include = wp_parse_id_list( $this->query_vars['include'] );
$include_sql = implode( ',', $include );
$_orderby = "FIELD( $wpdb->users.ID, $include_sql )";
} elseif ( 'nicename__in' === $orderby ) {
$sanitized_nicename__in = array_map( 'esc_sql', $this->query_vars['nicename__in'] );
$nicename__in = implode( "','", $sanitized_nicename__in );
$_orderby = "FIELD( user_nicename, '$nicename__in' )";
} elseif ( 'login__in' === $orderby ) {
$sanitized_login__in = array_map( 'esc_sql', $this->query_vars['login__in'] );
$login__in = implode( "','", $sanitized_login__in );
$_orderby = "FIELD( user_login, '$login__in' )";
} elseif ( isset( $meta_query_clauses[ $orderby ] ) ) {
$meta_clause = $meta_query_clauses[ $orderby ];
$_orderby = sprintf( 'CAST(%s.meta_value AS %s)', esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
}
return $_orderby;
}
```
| Uses | Description |
| --- | --- |
| [esc\_sql()](../../functions/esc_sql) wp-includes/formatting.php | Escapes data for use in a MySQL query. |
| [wp\_parse\_id\_list()](../../functions/wp_parse_id_list) wp-includes/functions.php | Cleans up an array, comma- or space-separated list of IDs. |
| [WP\_User\_Query::get()](get) wp-includes/class-wp-user-query.php | Retrieves query variable. |
| [get\_posts\_by\_author\_sql()](../../functions/get_posts_by_author_sql) wp-includes/post.php | Retrieves the post SQL based on capability, author, and type. |
| Used By | Description |
| --- | --- |
| [WP\_User\_Query::prepare\_query()](prepare_query) wp-includes/class-wp-user-query.php | Prepares the query variables. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_User_Query::__set( string $name, mixed $value ): mixed WP\_User\_Query::\_\_set( string $name, mixed $value ): mixed
=============================================================
Makes private properties settable for backward compatibility.
`$name` string Required Property to check if set. `$value` mixed Required Property value. mixed Newly-set property.
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
public function __set( $name, $value ) {
if ( in_array( $name, $this->compat_fields, true ) ) {
return $this->$name = $value;
}
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_User_Query::__get( string $name ): mixed WP\_User\_Query::\_\_get( string $name ): mixed
===============================================
Makes private properties readable for backward compatibility.
`$name` string Required Property to get. mixed Property.
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
public function __get( $name ) {
if ( in_array( $name, $this->compat_fields, true ) ) {
return $this->$name;
}
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_User_Query::fill_query_vars( array $args ): array WP\_User\_Query::fill\_query\_vars( array $args ): array
========================================================
Fills in missing query variables with default values.
`$args` array Required Query vars, as passed to `WP_User_Query`. array Complete query variables with undefined ones filled in with defaults.
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
public static function fill_query_vars( $args ) {
$defaults = array(
'blog_id' => get_current_blog_id(),
'role' => '',
'role__in' => array(),
'role__not_in' => array(),
'capability' => '',
'capability__in' => array(),
'capability__not_in' => array(),
'meta_key' => '',
'meta_value' => '',
'meta_compare' => '',
'include' => array(),
'exclude' => array(),
'search' => '',
'search_columns' => array(),
'orderby' => 'login',
'order' => 'ASC',
'offset' => '',
'number' => '',
'paged' => 1,
'count_total' => true,
'fields' => 'all',
'who' => '',
'has_published_posts' => null,
'nicename' => '',
'nicename__in' => array(),
'nicename__not_in' => array(),
'login' => '',
'login__in' => array(),
'login__not_in' => array(),
);
return wp_parse_args( $args, $defaults );
}
```
| Uses | Description |
| --- | --- |
| [get\_current\_blog\_id()](../../functions/get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Used By | Description |
| --- | --- |
| [WP\_User\_Query::prepare\_query()](prepare_query) wp-includes/class-wp-user-query.php | Prepares the query variables. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_User_Query::__isset( string $name ): bool WP\_User\_Query::\_\_isset( string $name ): bool
================================================
Makes private properties checkable for backward compatibility.
`$name` string Required Property to check if set. bool Whether the property is set.
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
public function __isset( $name ) {
if ( in_array( $name, $this->compat_fields, true ) ) {
return isset( $this->$name );
}
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_User_Query::query() WP\_User\_Query::query()
========================
Executes the query, with the current variables.
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
public function query() {
global $wpdb;
$qv =& $this->query_vars;
/**
* Filters the users array before the query takes place.
*
* Return a non-null value to bypass WordPress' default user queries.
*
* Filtering functions that require pagination information are encouraged to set
* the `total_users` property of the WP_User_Query object, passed to the filter
* by reference. If WP_User_Query does not perform a database query, it will not
* have enough information to generate these values itself.
*
* @since 5.1.0
*
* @param array|null $results Return an array of user data to short-circuit WP's user query
* or null to allow WP to run its normal queries.
* @param WP_User_Query $query The WP_User_Query instance (passed by reference).
*/
$this->results = apply_filters_ref_array( 'users_pre_query', array( null, &$this ) );
if ( null === $this->results ) {
$this->request = "
SELECT {$this->query_fields}
{$this->query_from}
{$this->query_where}
{$this->query_orderby}
{$this->query_limit}
";
if ( is_array( $qv['fields'] ) ) {
$this->results = $wpdb->get_results( $this->request );
} else {
$this->results = $wpdb->get_col( $this->request );
}
if ( isset( $qv['count_total'] ) && $qv['count_total'] ) {
/**
* Filters SELECT FOUND_ROWS() query for the current WP_User_Query instance.
*
* @since 3.2.0
* @since 5.1.0 Added the `$this` parameter.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
* @param WP_User_Query $query The current WP_User_Query instance.
*/
$found_users_query = apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()', $this );
$this->total_users = (int) $wpdb->get_var( $found_users_query );
}
}
if ( ! $this->results ) {
return;
}
if (
is_array( $qv['fields'] ) &&
isset( $this->results[0]->ID )
) {
foreach ( $this->results as $result ) {
$result->id = $result->ID;
}
} elseif ( 'all_with_meta' === $qv['fields'] || 'all' === $qv['fields'] ) {
cache_users( $this->results );
$r = array();
foreach ( $this->results as $userid ) {
if ( 'all_with_meta' === $qv['fields'] ) {
$r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
} else {
$r[] = new WP_User( $userid, '', $qv['blog_id'] );
}
}
$this->results = $r;
}
}
```
[apply\_filters( 'found\_users\_query', string $sql, WP\_User\_Query $query )](../../hooks/found_users_query)
Filters SELECT FOUND\_ROWS() query for the current [WP\_User\_Query](../wp_user_query) instance.
[apply\_filters\_ref\_array( 'users\_pre\_query', array|null $results, WP\_User\_Query $query )](../../hooks/users_pre_query)
Filters the users array before the query takes place.
| Uses | Description |
| --- | --- |
| [WP\_User::\_\_construct()](../wp_user/__construct) wp-includes/class-wp-user.php | Constructor. |
| [cache\_users()](../../functions/cache_users) wp-includes/pluggable.php | Retrieves info for user lists to prevent multiple queries by [get\_userdata()](../../functions/get_userdata) . |
| [apply\_filters\_ref\_array()](../../functions/apply_filters_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook, specifying arguments in an array. |
| [wpdb::get\_col()](../wpdb/get_col) wp-includes/class-wpdb.php | Retrieves one column from the database. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [wpdb::get\_results()](../wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| [wpdb::get\_var()](../wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| Used By | Description |
| --- | --- |
| [WP\_User\_Query::\_\_construct()](__construct) wp-includes/class-wp-user-query.php | PHP5 constructor. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_User_Query::get_search_sql( string $search, string[] $columns, bool $wild = false ): string WP\_User\_Query::get\_search\_sql( string $search, string[] $columns, bool $wild = false ): string
==================================================================================================
Used internally to generate an SQL string for searching across multiple columns.
`$search` string Required Search string. `$columns` string[] Required Array of columns to search. `$wild` bool Optional Whether to allow wildcard searches. Default is false for Network Admin, true for single site.
Single site allows leading and trailing wildcards, Network Admin only trailing. Default: `false`
string
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
protected function get_search_sql( $search, $columns, $wild = false ) {
global $wpdb;
$searches = array();
$leading_wild = ( 'leading' === $wild || 'both' === $wild ) ? '%' : '';
$trailing_wild = ( 'trailing' === $wild || 'both' === $wild ) ? '%' : '';
$like = $leading_wild . $wpdb->esc_like( $search ) . $trailing_wild;
foreach ( $columns as $column ) {
if ( 'ID' === $column ) {
$searches[] = $wpdb->prepare( "$column = %s", $search );
} else {
$searches[] = $wpdb->prepare( "$column LIKE %s", $like );
}
}
return ' AND (' . implode( ' OR ', $searches ) . ')';
}
```
| Uses | Description |
| --- | --- |
| [wpdb::esc\_like()](../wpdb/esc_like) wp-includes/class-wpdb.php | First half of escaping for `LIKE` special characters `%` and `_` before preparing for SQL. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_User\_Query::\_\_call()](__call) wp-includes/class-wp-user-query.php | Makes private/protected methods readable for backward compatibility. |
| [WP\_User\_Query::prepare\_query()](prepare_query) wp-includes/class-wp-user-query.php | Prepares the query variables. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_User_Query::__construct( null|string|array $query = null ) WP\_User\_Query::\_\_construct( null|string|array $query = null )
=================================================================
PHP5 constructor.
`$query` null|string|array Optional The query variables. Default: `null`
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
public function __construct( $query = null ) {
if ( ! empty( $query ) ) {
$this->prepare_query( $query );
$this->query();
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_User\_Query::prepare\_query()](prepare_query) wp-includes/class-wp-user-query.php | Prepares the query variables. |
| [WP\_User\_Query::query()](query) wp-includes/class-wp-user-query.php | Executes the query, with the current variables. |
| Used By | Description |
| --- | --- |
| [WP\_Sitemaps\_Users::get\_url\_list()](../wp_sitemaps_users/get_url_list) wp-includes/sitemaps/providers/class-wp-sitemaps-users.php | Gets a URL list for a user sitemap. |
| [WP\_Sitemaps\_Users::get\_max\_num\_pages()](../wp_sitemaps_users/get_max_num_pages) wp-includes/sitemaps/providers/class-wp-sitemaps-users.php | Gets the max number of pages available for the object type. |
| [WP\_REST\_Users\_Controller::get\_items()](../wp_rest_users_controller/get_items) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Retrieves all users. |
| [WP\_MS\_Sites\_List\_Table::column\_users()](../wp_ms_sites_list_table/column_users) wp-admin/includes/class-wp-ms-sites-list-table.php | Handles the users column output. |
| [WP\_MS\_Users\_List\_Table::prepare\_items()](../wp_ms_users_list_table/prepare_items) wp-admin/includes/class-wp-ms-users-list-table.php | |
| [WP\_Users\_List\_Table::prepare\_items()](../wp_users_list_table/prepare_items) wp-admin/includes/class-wp-users-list-table.php | Prepare the users list for display. |
| [get\_users()](../../functions/get_users) wp-includes/user.php | Retrieves list of users matching criteria. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
| programming_docs |
wordpress WP_User_Query::set( string $query_var, mixed $value ) WP\_User\_Query::set( string $query\_var, mixed $value )
========================================================
Sets query variable.
`$query_var` string Required Query variable key. `$value` mixed Required Query variable value. File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
public function set( $query_var, $value ) {
$this->query_vars[ $query_var ] = $value;
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_User_Query::get( string $query_var ): mixed WP\_User\_Query::get( string $query\_var ): mixed
=================================================
Retrieves query variable.
`$query_var` string Required Query variable key. mixed
File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/)
```
public function get( $query_var ) {
if ( isset( $this->query_vars[ $query_var ] ) ) {
return $this->query_vars[ $query_var ];
}
return null;
}
```
| Used By | Description |
| --- | --- |
| [WP\_User\_Query::parse\_orderby()](parse_orderby) wp-includes/class-wp-user-query.php | Parses and sanitizes ‘orderby’ keys passed to the user query. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_REST_Term_Search_Handler::search_items( WP_REST_Request $request ): array WP\_REST\_Term\_Search\_Handler::search\_items( WP\_REST\_Request $request ): array
===================================================================================
Searches the object type content for a given search request.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full REST request. array Associative array containing found IDs and total count for the matching search results.
* `ids`int[]Found IDs.
* `total`string|int|[WP\_Error](../wp_error)Numeric string containing the number of terms in that taxonomy, 0 if there are no results, or [WP\_Error](../wp_error) if the requested taxonomy does not exist.
File: `wp-includes/rest-api/search/class-wp-rest-term-search-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/search/class-wp-rest-term-search-handler.php/)
```
public function search_items( WP_REST_Request $request ) {
$taxonomies = $request[ WP_REST_Search_Controller::PROP_SUBTYPE ];
if ( in_array( WP_REST_Search_Controller::TYPE_ANY, $taxonomies, true ) ) {
$taxonomies = $this->subtypes;
}
$page = (int) $request['page'];
$per_page = (int) $request['per_page'];
$query_args = array(
'taxonomy' => $taxonomies,
'hide_empty' => false,
'offset' => ( $page - 1 ) * $per_page,
'number' => $per_page,
);
if ( ! empty( $request['search'] ) ) {
$query_args['search'] = $request['search'];
}
if ( ! empty( $request['exclude'] ) ) {
$query_args['exclude'] = $request['exclude'];
}
if ( ! empty( $request['include'] ) ) {
$query_args['include'] = $request['include'];
}
/**
* Filters the query arguments for a REST API search request.
*
* Enables adding extra arguments or setting defaults for a term search request.
*
* @since 5.6.0
*
* @param array $query_args Key value array of query var to query value.
* @param WP_REST_Request $request The request used.
*/
$query_args = apply_filters( 'rest_term_search_query', $query_args, $request );
$query = new WP_Term_Query();
$found_terms = $query->query( $query_args );
$found_ids = wp_list_pluck( $found_terms, 'term_id' );
unset( $query_args['offset'], $query_args['number'] );
$total = wp_count_terms( $query_args );
// wp_count_terms() can return a falsey value when the term has no children.
if ( ! $total ) {
$total = 0;
}
return array(
self::RESULT_IDS => $found_ids,
self::RESULT_TOTAL => $total,
);
}
```
[apply\_filters( 'rest\_term\_search\_query', array $query\_args, WP\_REST\_Request $request )](../../hooks/rest_term_search_query)
Filters the query arguments for a REST API search request.
| Uses | Description |
| --- | --- |
| [WP\_Term\_Query::\_\_construct()](../wp_term_query/__construct) wp-includes/class-wp-term-query.php | Constructor. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [wp\_count\_terms()](../../functions/wp_count_terms) wp-includes/taxonomy.php | Counts how many terms are in taxonomy. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Term_Search_Handler::prepare_item( int $id, array $fields ): array WP\_REST\_Term\_Search\_Handler::prepare\_item( int $id, array $fields ): array
===============================================================================
Prepares the search result for a given ID.
`$id` int Required Item ID. `$fields` array Required Fields to include for the item. array Associative array containing all fields for the item.
File: `wp-includes/rest-api/search/class-wp-rest-term-search-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/search/class-wp-rest-term-search-handler.php/)
```
public function prepare_item( $id, array $fields ) {
$term = get_term( $id );
$data = array();
if ( in_array( WP_REST_Search_Controller::PROP_ID, $fields, true ) ) {
$data[ WP_REST_Search_Controller::PROP_ID ] = (int) $id;
}
if ( in_array( WP_REST_Search_Controller::PROP_TITLE, $fields, true ) ) {
$data[ WP_REST_Search_Controller::PROP_TITLE ] = $term->name;
}
if ( in_array( WP_REST_Search_Controller::PROP_URL, $fields, true ) ) {
$data[ WP_REST_Search_Controller::PROP_URL ] = get_term_link( $id );
}
if ( in_array( WP_REST_Search_Controller::PROP_TYPE, $fields, true ) ) {
$data[ WP_REST_Search_Controller::PROP_TYPE ] = $term->taxonomy;
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [get\_term\_link()](../../functions/get_term_link) wp-includes/taxonomy.php | Generates a permalink for a taxonomy term archive. |
| [get\_term()](../../functions/get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Term_Search_Handler::__construct() WP\_REST\_Term\_Search\_Handler::\_\_construct()
================================================
Constructor.
File: `wp-includes/rest-api/search/class-wp-rest-term-search-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/search/class-wp-rest-term-search-handler.php/)
```
public function __construct() {
$this->type = 'term';
$this->subtypes = array_values(
get_taxonomies(
array(
'public' => true,
'show_in_rest' => true,
),
'names'
)
);
}
```
| Uses | Description |
| --- | --- |
| [get\_taxonomies()](../../functions/get_taxonomies) wp-includes/taxonomy.php | Retrieves a list of registered taxonomy names or objects. |
| Used By | Description |
| --- | --- |
| [create\_initial\_rest\_routes()](../../functions/create_initial_rest_routes) wp-includes/rest-api.php | Registers default REST API routes. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Term_Search_Handler::prepare_item_links( int $id ): array[] WP\_REST\_Term\_Search\_Handler::prepare\_item\_links( int $id ): array[]
=========================================================================
Prepares links for the search result of a given ID.
`$id` int Required Item ID. array[] Array of link arrays for the given item.
File: `wp-includes/rest-api/search/class-wp-rest-term-search-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/search/class-wp-rest-term-search-handler.php/)
```
public function prepare_item_links( $id ) {
$term = get_term( $id );
$links = array();
$item_route = rest_get_route_for_term( $term );
if ( $item_route ) {
$links['self'] = array(
'href' => rest_url( $item_route ),
'embeddable' => true,
);
}
$links['about'] = array(
'href' => rest_url( sprintf( 'wp/v2/taxonomies/%s', $term->taxonomy ) ),
);
return $links;
}
```
| Uses | Description |
| --- | --- |
| [rest\_get\_route\_for\_term()](../../functions/rest_get_route_for_term) wp-includes/rest-api.php | Gets the REST API route for a term. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [get\_term()](../../functions/get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress Requests_Hooks::register( string $hook, callback $callback, int $priority ) Requests\_Hooks::register( string $hook, callback $callback, int $priority )
============================================================================
Register a callback for a hook
`$hook` string Required Hook name `$callback` callback Required Function/method to call on event `$priority` int Required Priority number. <0 is executed earlier, >0 is executed later File: `wp-includes/Requests/Hooks.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/hooks.php/)
```
public function register($hook, $callback, $priority = 0) {
if (!isset($this->hooks[$hook])) {
$this->hooks[$hook] = array();
}
if (!isset($this->hooks[$hook][$priority])) {
$this->hooks[$hook][$priority] = array();
}
$this->hooks[$hook][$priority][] = $callback;
}
```
wordpress Requests_Hooks::dispatch( string $hook, array $parameters = array() ): boolean Requests\_Hooks::dispatch( string $hook, array $parameters = array() ): boolean
===============================================================================
Dispatch a message
`$hook` string Required Hook name `$parameters` array Optional Parameters to pass to callbacks Default: `array()`
boolean Successfulness
File: `wp-includes/Requests/Hooks.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/hooks.php/)
```
public function dispatch($hook, $parameters = array()) {
if (empty($this->hooks[$hook])) {
return false;
}
foreach ($this->hooks[$hook] as $priority => $hooked) {
foreach ($hooked as $callback) {
call_user_func_array($callback, $parameters);
}
}
return true;
}
```
| Used By | Description |
| --- | --- |
| [WP\_HTTP\_Requests\_Hooks::dispatch()](../wp_http_requests_hooks/dispatch) wp-includes/class-wp-http-requests-hooks.php | Dispatch a Requests hook to a native WordPress action. |
wordpress Requests_Hooks::__construct() Requests\_Hooks::\_\_construct()
================================
Constructor
File: `wp-includes/Requests/Hooks.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/hooks.php/)
```
public function __construct() {
// pass
}
```
| Used By | Description |
| --- | --- |
| [Requests::set\_defaults()](../requests/set_defaults) wp-includes/class-requests.php | Set the default values |
wordpress WP_HTTP_Response::set_data( mixed $data ) WP\_HTTP\_Response::set\_data( mixed $data )
============================================
Sets the response data.
`$data` mixed Required Response data. File: `wp-includes/class-wp-http-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-response.php/)
```
public function set_data( $data ) {
$this->data = $data;
}
```
| Used By | Description |
| --- | --- |
| [WP\_HTTP\_Response::\_\_construct()](__construct) wp-includes/class-wp-http-response.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_HTTP_Response::set_status( int $code ) WP\_HTTP\_Response::set\_status( int $code )
============================================
Sets the 3-digit HTTP status code.
`$code` int Required HTTP status. File: `wp-includes/class-wp-http-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-response.php/)
```
public function set_status( $code ) {
$this->status = absint( $code );
}
```
| Uses | Description |
| --- | --- |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Used By | Description |
| --- | --- |
| [WP\_HTTP\_Response::\_\_construct()](__construct) wp-includes/class-wp-http-response.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_HTTP_Response::set_headers( array $headers ) WP\_HTTP\_Response::set\_headers( array $headers )
==================================================
Sets all header values.
`$headers` array Required Map of header name to header value. File: `wp-includes/class-wp-http-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-response.php/)
```
public function set_headers( $headers ) {
$this->headers = $headers;
}
```
| Used By | Description |
| --- | --- |
| [WP\_HTTP\_Response::\_\_construct()](__construct) wp-includes/class-wp-http-response.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_HTTP_Response::get_status(): int WP\_HTTP\_Response::get\_status(): int
======================================
Retrieves the HTTP return code for the response.
int The 3-digit HTTP status code.
File: `wp-includes/class-wp-http-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-response.php/)
```
public function get_status() {
return $this->status;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_HTTP_Response::get_data(): mixed WP\_HTTP\_Response::get\_data(): mixed
======================================
Retrieves the response data.
mixed Response data.
File: `wp-includes/class-wp-http-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-response.php/)
```
public function get_data() {
return $this->data;
}
```
| Used By | Description |
| --- | --- |
| [WP\_HTTP\_Response::jsonSerialize()](jsonserialize) wp-includes/class-wp-http-response.php | Retrieves the response data for JSON serialization. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_HTTP_Response::get_headers(): array WP\_HTTP\_Response::get\_headers(): array
=========================================
Retrieves headers associated with the response.
array Map of header name to header value.
File: `wp-includes/class-wp-http-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-response.php/)
```
public function get_headers() {
return $this->headers;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_HTTP_Response::__construct( mixed $data = null, int $status = 200, array $headers = array() ) WP\_HTTP\_Response::\_\_construct( mixed $data = null, int $status = 200, array $headers = array() )
====================================================================================================
Constructor.
`$data` mixed Optional Response data. Default: `null`
`$status` int Optional HTTP status code. Default: `200`
`$headers` array Optional HTTP header map. Default: `array()`
File: `wp-includes/class-wp-http-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-response.php/)
```
public function __construct( $data = null, $status = 200, $headers = array() ) {
$this->set_data( $data );
$this->set_status( $status );
$this->set_headers( $headers );
}
```
| Uses | Description |
| --- | --- |
| [WP\_HTTP\_Response::set\_data()](set_data) wp-includes/class-wp-http-response.php | Sets the response data. |
| [WP\_HTTP\_Response::set\_status()](set_status) wp-includes/class-wp-http-response.php | Sets the 3-digit HTTP status code. |
| [WP\_HTTP\_Response::set\_headers()](set_headers) wp-includes/class-wp-http-response.php | Sets all header values. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_HTTP_Response::jsonSerialize(): mixed WP\_HTTP\_Response::jsonSerialize(): mixed
==========================================
Retrieves the response data for JSON serialization.
It is expected that in most implementations, this will return the same as get\_data(), however this may be different if you want to do custom JSON data handling.
mixed Any JSON-serializable value.
File: `wp-includes/class-wp-http-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-response.php/)
```
public function jsonSerialize() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
return $this->get_data();
}
```
| Uses | Description |
| --- | --- |
| [WP\_HTTP\_Response::get\_data()](get_data) wp-includes/class-wp-http-response.php | Retrieves the response data. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_HTTP_Response::header( string $key, string $value, bool $replace = true ) WP\_HTTP\_Response::header( string $key, string $value, bool $replace = true )
==============================================================================
Sets a single HTTP header.
`$key` string Required Header name. `$value` string Required Header value. `$replace` bool Optional Whether to replace an existing header of the same name.
Default: `true`
File: `wp-includes/class-wp-http-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-response.php/)
```
public function header( $key, $value, $replace = true ) {
if ( $replace || ! isset( $this->headers[ $key ] ) ) {
$this->headers[ $key ] = $value;
} else {
$this->headers[ $key ] .= ', ' . $value;
}
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Http::processHeaders( string|array $headers, string $url = '' ): array WP\_Http::processHeaders( string|array $headers, string $url = '' ): array
==========================================================================
Transforms header string into an array.
`$headers` string|array Required The original headers. If a string is passed, it will be converted to an array. If an array is passed, then it is assumed to be raw header data with numeric keys with the headers as the values.
No headers must be passed that were already processed. `$url` string Optional The URL that was requested. Default: `''`
array Processed string headers. If duplicate headers are encountered, then a numbered array is returned as the value of that header-key.
* `response`array
+ `code`intThe response status code. Default 0.
+ `message`stringThe response message. Default empty.
+ `newheaders`arrayThe processed header data as a multidimensional array.
+ `cookies`[WP\_Http\_Cookie](../wp_http_cookie)[]If the original headers contain the `'Set-Cookie'` key, an array containing `WP_Http_Cookie` objects is returned. File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public static function processHeaders( $headers, $url = '' ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
// Split headers, one per array element.
if ( is_string( $headers ) ) {
// Tolerate line terminator: CRLF = LF (RFC 2616 19.3).
$headers = str_replace( "\r\n", "\n", $headers );
/*
* Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>,
* <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2).
*/
$headers = preg_replace( '/\n[ \t]/', ' ', $headers );
// Create the headers array.
$headers = explode( "\n", $headers );
}
$response = array(
'code' => 0,
'message' => '',
);
/*
* If a redirection has taken place, The headers for each page request may have been passed.
* In this case, determine the final HTTP header and parse from there.
*/
for ( $i = count( $headers ) - 1; $i >= 0; $i-- ) {
if ( ! empty( $headers[ $i ] ) && false === strpos( $headers[ $i ], ':' ) ) {
$headers = array_splice( $headers, $i );
break;
}
}
$cookies = array();
$newheaders = array();
foreach ( (array) $headers as $tempheader ) {
if ( empty( $tempheader ) ) {
continue;
}
if ( false === strpos( $tempheader, ':' ) ) {
$stack = explode( ' ', $tempheader, 3 );
$stack[] = '';
list( , $response['code'], $response['message']) = $stack;
continue;
}
list($key, $value) = explode( ':', $tempheader, 2 );
$key = strtolower( $key );
$value = trim( $value );
if ( isset( $newheaders[ $key ] ) ) {
if ( ! is_array( $newheaders[ $key ] ) ) {
$newheaders[ $key ] = array( $newheaders[ $key ] );
}
$newheaders[ $key ][] = $value;
} else {
$newheaders[ $key ] = $value;
}
if ( 'set-cookie' === $key ) {
$cookies[] = new WP_Http_Cookie( $value, $url );
}
}
// Cast the Response Code to an int.
$response['code'] = (int) $response['code'];
return array(
'response' => $response,
'headers' => $newheaders,
'cookies' => $cookies,
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Http\_Cookie::\_\_construct()](../wp_http_cookie/__construct) wp-includes/class-wp-http-cookie.php | Sets up this cookie object. |
| Used By | Description |
| --- | --- |
| [WP\_Http\_Streams::request()](../wp_http_streams/request) wp-includes/class-wp-http-streams.php | Send a HTTP request to a URI using PHP Streams. |
| [WP\_Http\_Curl::request()](../wp_http_curl/request) wp-includes/class-wp-http-curl.php | Send a HTTP request to a URI using cURL extension. |
| [WP\_Http::request()](request) wp-includes/class-wp-http.php | Send an HTTP request to a URI. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Http::post( string $url, string|array $args = array() ): array|WP_Error WP\_Http::post( string $url, string|array $args = array() ): array|WP\_Error
============================================================================
Uses the POST HTTP method.
Used for sending data that is expected to be in the body.
`$url` string Required The request URL. `$args` string|array Optional Override the defaults. Default: `array()`
array|[WP\_Error](../wp_error) Array containing `'headers'`, `'body'`, `'response'`, `'cookies'`, `'filename'`.
A [WP\_Error](../wp_error) instance upon error.
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public function post( $url, $args = array() ) {
$defaults = array( 'method' => 'POST' );
$parsed_args = wp_parse_args( $args, $defaults );
return $this->request( $url, $parsed_args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Http::request()](request) wp-includes/class-wp-http.php | Send an HTTP request to a URI. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_Http::buildCookieHeader( array $r ) WP\_Http::buildCookieHeader( array $r )
=======================================
Takes the arguments for a ::request() and checks for the cookie array.
If it’s found, then it upgrades any basic name => value pairs to [WP\_Http\_Cookie](../wp_http_cookie) instances, which are each parsed into strings and added to the Cookie: header (within the arguments array).
Edits the array by reference.
`$r` array Required Full array of args passed into ::request() File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public static function buildCookieHeader( &$r ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
if ( ! empty( $r['cookies'] ) ) {
// Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances.
foreach ( $r['cookies'] as $name => $value ) {
if ( ! is_object( $value ) ) {
$r['cookies'][ $name ] = new WP_Http_Cookie(
array(
'name' => $name,
'value' => $value,
)
);
}
}
$cookies_header = '';
foreach ( (array) $r['cookies'] as $cookie ) {
$cookies_header .= $cookie->getHeaderValue() . '; ';
}
$cookies_header = substr( $cookies_header, 0, -2 );
$r['headers']['cookie'] = $cookies_header;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Http\_Cookie::\_\_construct()](../wp_http_cookie/__construct) wp-includes/class-wp-http-cookie.php | Sets up this cookie object. |
| Used By | Description |
| --- | --- |
| [WP\_Http\_Streams::request()](../wp_http_streams/request) wp-includes/class-wp-http-streams.php | Send a HTTP request to a URI using PHP Streams. |
| [WP\_Http\_Curl::request()](../wp_http_curl/request) wp-includes/class-wp-http-curl.php | Send a HTTP request to a URI using cURL extension. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Http::_dispatch_request( string $url, array $args ): array|WP_Error WP\_Http::\_dispatch\_request( string $url, array $args ): array|WP\_Error
==========================================================================
This method has been deprecated. Use [WP\_Http::request()](../wp_http/request) instead.
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness. Use [WP\_Http::request()](../wp_http/request) instead.
Dispatches a HTTP request to a supporting transport.
Tests each transport in order to find a transport which matches the request arguments.
Also caches the transport instance to be used later.
The order for requests is cURL, and then PHP Streams.
* [WP\_Http::request()](../wp_http/request)
`$url` string Required URL to request. `$args` array Required Request arguments. array|[WP\_Error](../wp_error) Array containing `'headers'`, `'body'`, `'response'`, `'cookies'`, `'filename'`.
A [WP\_Error](../wp_error) instance upon error.
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
private function _dispatch_request( $url, $args ) {
static $transports = array();
$class = $this->_get_first_available_transport( $args, $url );
if ( ! $class ) {
return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) );
}
// Transport claims to support request, instantiate it and give it a whirl.
if ( empty( $transports[ $class ] ) ) {
$transports[ $class ] = new $class;
}
$response = $transports[ $class ]->request( $url, $args );
/** This action is documented in wp-includes/class-wp-http.php */
do_action( 'http_api_debug', $response, 'response', $class, $args, $url );
if ( is_wp_error( $response ) ) {
return $response;
}
/** This filter is documented in wp-includes/class-wp-http.php */
return apply_filters( 'http_response', $response, $args, $url );
}
```
[do\_action( 'http\_api\_debug', array|WP\_Error $response, string $context, string $class, array $parsed\_args, string $url )](../../hooks/http_api_debug)
Fires after an HTTP API response is received and before the response is returned.
[apply\_filters( 'http\_response', array $response, array $parsed\_args, string $url )](../../hooks/http_response)
Filters a successful HTTP API response immediately before the response is returned.
| Uses | Description |
| --- | --- |
| [WP\_Http::\_get\_first\_available\_transport()](_get_first_available_transport) wp-includes/class-wp-http.php | Tests which transports are capable of supporting the request. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Use [WP\_Http::request()](request) |
| [3.2.0](https://developer.wordpress.org/reference/since/3.2.0/) | Introduced. |
wordpress WP_Http::normalize_cookies( array $cookies ): Requests_Cookie_Jar WP\_Http::normalize\_cookies( array $cookies ): Requests\_Cookie\_Jar
=====================================================================
Normalizes cookies for using in Requests.
`$cookies` array Required Array of cookies to send with the request. [Requests\_Cookie\_Jar](../requests_cookie_jar) Cookie holder object.
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public static function normalize_cookies( $cookies ) {
$cookie_jar = new Requests_Cookie_Jar();
foreach ( $cookies as $name => $value ) {
if ( $value instanceof WP_Http_Cookie ) {
$attributes = array_filter(
$value->get_attributes(),
static function( $attr ) {
return null !== $attr;
}
);
$cookie_jar[ $value->name ] = new Requests_Cookie( $value->name, $value->value, $attributes, array( 'host-only' => $value->host_only ) );
} elseif ( is_scalar( $value ) ) {
$cookie_jar[ $name ] = new Requests_Cookie( $name, $value );
}
}
return $cookie_jar;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Cookie::\_\_construct()](../requests_cookie/__construct) wp-includes/Requests/Cookie.php | Create a new cookie object |
| [Requests\_Cookie\_Jar::\_\_construct()](../requests_cookie_jar/__construct) wp-includes/Requests/Cookie/Jar.php | Create a new jar |
| Used By | Description |
| --- | --- |
| [WP\_Http::request()](request) wp-includes/class-wp-http.php | Send an HTTP request to a URI. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Http::is_ip_address( string $maybe_ip ): int|false WP\_Http::is\_ip\_address( string $maybe\_ip ): int|false
=========================================================
Determines if a specified string represents an IP address or not.
This function also detects the type of the IP address, returning either ‘4’ or ‘6’ to represent a IPv4 and IPv6 address respectively.
This does not verify if the IP is a valid IP, only that it appears to be an IP address.
`$maybe_ip` string Required A suspected IP address. int|false Upon success, `'4'` or `'6'` to represent a IPv4 or IPv6 address, false upon failure
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public static function is_ip_address( $maybe_ip ) {
if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) ) {
return 4;
}
if ( false !== strpos( $maybe_ip, ':' ) && preg_match( '/^(((?=.*(::))(?!.*\3.+\3))\3?|([\dA-F]{1,4}(\3|:\b|$)|\2))(?4){5}((?4){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i', trim( $maybe_ip, ' []' ) ) ) {
return 6;
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [wp\_notify\_postauthor()](../../functions/wp_notify_postauthor) wp-includes/pluggable.php | Notifies an author (and/or others) of a comment/trackback/pingback on a post. |
| [wp\_notify\_moderator()](../../functions/wp_notify_moderator) wp-includes/pluggable.php | Notifies the moderator of the site about a new comment that is awaiting approval. |
| [WP\_Http\_Streams::verify\_ssl\_certificate()](../wp_http_streams/verify_ssl_certificate) wp-includes/class-wp-http-streams.php | Verifies the received SSL certificate against its Common Names and subjectAltName fields. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Http::_get_first_available_transport( array $args, string $url = null ): string|false WP\_Http::\_get\_first\_available\_transport( array $args, string $url = null ): string|false
=============================================================================================
Tests which transports are capable of supporting the request.
`$args` array Required Request arguments. `$url` string Optional URL to request. Default: `null`
string|false Class name for the first transport that claims to support the request.
False if no transport claims to support the request.
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public function _get_first_available_transport( $args, $url = null ) {
$transports = array( 'curl', 'streams' );
/**
* Filters which HTTP transports are available and in what order.
*
* @since 3.7.0
*
* @param string[] $transports Array of HTTP transports to check. Default array contains
* 'curl' and 'streams', in that order.
* @param array $args HTTP request arguments.
* @param string $url The URL to request.
*/
$request_order = apply_filters( 'http_api_transports', $transports, $args, $url );
// Loop over each transport on each HTTP request looking for one which will serve this request's needs.
foreach ( $request_order as $transport ) {
if ( in_array( $transport, $transports, true ) ) {
$transport = ucfirst( $transport );
}
$class = 'WP_Http_' . $transport;
// Check to see if this transport is a possibility, calls the transport statically.
if ( ! call_user_func( array( $class, 'test' ), $args, $url ) ) {
continue;
}
return $class;
}
return false;
}
```
[apply\_filters( 'http\_api\_transports', string[] $transports, array $args, string $url )](../../hooks/http_api_transports)
Filters which HTTP transports are available and in what order.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Http::\_dispatch\_request()](_dispatch_request) wp-includes/class-wp-http.php | Dispatches a HTTP request to a supporting transport. |
| Version | Description |
| --- | --- |
| [3.2.0](https://developer.wordpress.org/reference/since/3.2.0/) | Introduced. |
wordpress WP_Http::make_absolute_url( string $maybe_relative_path, string $url ): string WP\_Http::make\_absolute\_url( string $maybe\_relative\_path, string $url ): string
===================================================================================
Converts a relative URL to an absolute URL relative to a given URL.
If an Absolute URL is provided, no processing of that URL is done.
`$maybe_relative_path` string Required The URL which might be relative. `$url` string Required The URL which $maybe\_relative\_path is relative to. string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public static function make_absolute_url( $maybe_relative_path, $url ) {
if ( empty( $url ) ) {
return $maybe_relative_path;
}
$url_parts = wp_parse_url( $url );
if ( ! $url_parts ) {
return $maybe_relative_path;
}
$relative_url_parts = wp_parse_url( $maybe_relative_path );
if ( ! $relative_url_parts ) {
return $maybe_relative_path;
}
// Check for a scheme on the 'relative' URL.
if ( ! empty( $relative_url_parts['scheme'] ) ) {
return $maybe_relative_path;
}
$absolute_path = $url_parts['scheme'] . '://';
// Schemeless URLs will make it this far, so we check for a host in the relative URL
// and convert it to a protocol-URL.
if ( isset( $relative_url_parts['host'] ) ) {
$absolute_path .= $relative_url_parts['host'];
if ( isset( $relative_url_parts['port'] ) ) {
$absolute_path .= ':' . $relative_url_parts['port'];
}
} else {
$absolute_path .= $url_parts['host'];
if ( isset( $url_parts['port'] ) ) {
$absolute_path .= ':' . $url_parts['port'];
}
}
// Start off with the absolute URL path.
$path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/';
// If it's a root-relative path, then great.
if ( ! empty( $relative_url_parts['path'] ) && '/' === $relative_url_parts['path'][0] ) {
$path = $relative_url_parts['path'];
// Else it's a relative path.
} elseif ( ! empty( $relative_url_parts['path'] ) ) {
// Strip off any file components from the absolute path.
$path = substr( $path, 0, strrpos( $path, '/' ) + 1 );
// Build the new path.
$path .= $relative_url_parts['path'];
// Strip all /path/../ out of the path.
while ( strpos( $path, '../' ) > 1 ) {
$path = preg_replace( '![^/]+/\.\./!', '', $path );
}
// Strip any final leading ../ from the path.
$path = preg_replace( '!^/(\.\./)+!', '', $path );
}
// Add the query string.
if ( ! empty( $relative_url_parts['query'] ) ) {
$path .= '?' . $relative_url_parts['query'];
}
return $absolute_path . '/' . ltrim( $path, '/' );
}
```
| Uses | Description |
| --- | --- |
| [wp\_parse\_url()](../../functions/wp_parse_url) wp-includes/http.php | A wrapper for PHP’s parse\_url() function that handles consistency in the return values across PHP versions. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_URL\_Details\_Controller::get\_icon()](../wp_rest_url_details_controller/get_icon) wp-includes/rest-api/endpoints/class-wp-rest-url-details-controller.php | Parses the site icon from the provided HTML. |
| [WP\_REST\_URL\_Details\_Controller::get\_image()](../wp_rest_url_details_controller/get_image) wp-includes/rest-api/endpoints/class-wp-rest-url-details-controller.php | Parses the Open Graph (OG) Image from the provided HTML. |
| [\_links\_add\_base()](../../functions/_links_add_base) wp-includes/formatting.php | Callback to add a base URL to relative links in passed content. |
| [WP\_Http::handle\_redirects()](handle_redirects) wp-includes/class-wp-http.php | Handles an HTTP redirect and follows it if appropriate. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Http::block_request( string $uri ): bool WP\_Http::block\_request( string $uri ): bool
=============================================
Determines whether an HTTP API request to the given URL should be blocked.
Those who are behind a proxy and want to prevent access to certain hosts may do so. This will prevent plugins from working and core functionality, if you don’t include `api.wordpress.org`.
You block external URL requests by defining `WP_HTTP_BLOCK_EXTERNAL` as true in your `wp-config.php` file and this will only allow localhost and your site to make requests. The constant `WP_ACCESSIBLE_HOSTS` will allow additional hosts to go through for requests. The format of the `WP_ACCESSIBLE_HOSTS` constant is a comma separated list of hostnames to allow, wildcard domains are supported, eg `*.wordpress.org` will allow for all subdomains of `wordpress.org` to be contacted.
`$uri` string Required URI of url. bool True to block, false to allow.
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public function block_request( $uri ) {
// We don't need to block requests, because nothing is blocked.
if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL ) {
return false;
}
$check = parse_url( $uri );
if ( ! $check ) {
return true;
}
$home = parse_url( get_option( 'siteurl' ) );
// Don't block requests back to ourselves by default.
if ( 'localhost' === $check['host'] || ( isset( $home['host'] ) && $home['host'] === $check['host'] ) ) {
/**
* Filters whether to block local HTTP API requests.
*
* A local request is one to `localhost` or to the same host as the site itself.
*
* @since 2.8.0
*
* @param bool $block Whether to block local requests. Default false.
*/
return apply_filters( 'block_local_requests', false );
}
if ( ! defined( 'WP_ACCESSIBLE_HOSTS' ) ) {
return true;
}
static $accessible_hosts = null;
static $wildcard_regex = array();
if ( null === $accessible_hosts ) {
$accessible_hosts = preg_split( '|,\s*|', WP_ACCESSIBLE_HOSTS );
if ( false !== strpos( WP_ACCESSIBLE_HOSTS, '*' ) ) {
$wildcard_regex = array();
foreach ( $accessible_hosts as $host ) {
$wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
}
$wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i';
}
}
if ( ! empty( $wildcard_regex ) ) {
return ! preg_match( $wildcard_regex, $check['host'] );
} else {
return ! in_array( $check['host'], $accessible_hosts, true ); // Inverse logic, if it's in the array, then don't block it.
}
}
```
[apply\_filters( 'block\_local\_requests', bool $block )](../../hooks/block_local_requests)
Filters whether to block local HTTP API requests.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Http::request()](request) wp-includes/class-wp-http.php | Send an HTTP request to a URI. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Http::chunkTransferDecode( string $body ): string WP\_Http::chunkTransferDecode( string $body ): string
=====================================================
Decodes chunk transfer-encoding, based off the HTTP 1.1 specification.
Based off the HTTP http\_encoding\_dechunk function.
`$body` string Required Body content. string Chunked decoded body on success or raw body on failure.
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public static function chunkTransferDecode( $body ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
// The body is not chunked encoded or is malformed.
if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) ) {
return $body;
}
$parsed_body = '';
// We'll be altering $body, so need a backup in case of error.
$body_original = $body;
while ( true ) {
$has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match );
if ( ! $has_chunk || empty( $match[1] ) ) {
return $body_original;
}
$length = hexdec( $match[1] );
$chunk_length = strlen( $match[0] );
// Parse out the chunk of data.
$parsed_body .= substr( $body, $chunk_length, $length );
// Remove the chunk from the raw data.
$body = substr( $body, $length + $chunk_length );
// End of the document.
if ( '0' === trim( $body ) ) {
return $parsed_body;
}
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Http\_Streams::request()](../wp_http_streams/request) wp-includes/class-wp-http-streams.php | Send a HTTP request to a URI using PHP Streams. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_Http::handle_redirects( string $url, array $args, array $response ): array|false|WP_Error WP\_Http::handle\_redirects( string $url, array $args, array $response ): array|false|WP\_Error
===============================================================================================
Handles an HTTP redirect and follows it if appropriate.
`$url` string Required The URL which was requested. `$args` array Required The arguments which were used to make the request. `$response` array Required The response of the HTTP request. array|false|[WP\_Error](../wp_error) An HTTP API response array if the redirect is successfully followed, false if no redirect is present, or a [WP\_Error](../wp_error) object if there's an error.
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public static function handle_redirects( $url, $args, $response ) {
// If no redirects are present, or, redirects were not requested, perform no action.
if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] ) {
return false;
}
// Only perform redirections on redirection http codes.
if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 ) {
return false;
}
// Don't redirect if we've run out of redirects.
if ( $args['redirection']-- <= 0 ) {
return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
}
$redirect_location = $response['headers']['location'];
// If there were multiple Location headers, use the last header specified.
if ( is_array( $redirect_location ) ) {
$redirect_location = array_pop( $redirect_location );
}
$redirect_location = WP_Http::make_absolute_url( $redirect_location, $url );
// POST requests should not POST to a redirected location.
if ( 'POST' === $args['method'] ) {
if ( in_array( $response['response']['code'], array( 302, 303 ), true ) ) {
$args['method'] = 'GET';
}
}
// Include valid cookies in the redirect process.
if ( ! empty( $response['cookies'] ) ) {
foreach ( $response['cookies'] as $cookie ) {
if ( $cookie->test( $redirect_location ) ) {
$args['cookies'][] = $cookie;
}
}
}
return wp_remote_request( $redirect_location, $args );
}
```
| Uses | Description |
| --- | --- |
| [wp\_remote\_request()](../../functions/wp_remote_request) wp-includes/http.php | Performs an HTTP request and returns its response. |
| [WP\_Http::make\_absolute\_url()](make_absolute_url) wp-includes/class-wp-http.php | Converts a relative URL to an absolute URL relative to a given URL. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Http\_Streams::request()](../wp_http_streams/request) wp-includes/class-wp-http-streams.php | Send a HTTP request to a URI using PHP Streams. |
| [WP\_Http\_Curl::request()](../wp_http_curl/request) wp-includes/class-wp-http-curl.php | Send a HTTP request to a URI using cURL extension. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Http::parse_url( string $url ): bool|array WP\_Http::parse\_url( string $url ): bool|array
===============================================
This method has been deprecated. Use [wp\_parse\_url()](../../functions/wp_parse_url) instead.
Used as a wrapper for PHP’s parse\_url() function that handles edgecases in < PHP 5.4.7.
* [wp\_parse\_url()](../../functions/wp_parse_url)
`$url` string Required The URL to parse. bool|array False on failure; Array of URL components on success; See parse\_url()'s return values.
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
protected static function parse_url( $url ) {
_deprecated_function( __METHOD__, '4.4.0', 'wp_parse_url()' );
return wp_parse_url( $url );
}
```
| Uses | Description |
| --- | --- |
| [wp\_parse\_url()](../../functions/wp_parse_url) wp-includes/http.php | A wrapper for PHP’s parse\_url() function that handles consistency in the return values across PHP versions. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Http::validate_redirects( string $location ) WP\_Http::validate\_redirects( string $location )
=================================================
Validate redirected URLs.
`$location` string Required URL to redirect to. File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public static function validate_redirects( $location ) {
if ( ! wp_http_validate_url( $location ) ) {
throw new Requests_Exception( __( 'A valid URL was not provided.' ), 'wp_http.redirect_failed_validation' );
}
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
| [wp\_http\_validate\_url()](../../functions/wp_http_validate_url) wp-includes/http.php | Validate a URL for safe use in the HTTP API. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [4.7.5](https://developer.wordpress.org/reference/since/4.7.5/) | Introduced. |
wordpress WP_Http::browser_redirect_compatibility( string $location, array $headers, string|array $data, array $options, Requests_Response $original ) WP\_Http::browser\_redirect\_compatibility( string $location, array $headers, string|array $data, array $options, Requests\_Response $original )
================================================================================================================================================
Match redirect behaviour to browser handling.
Changes 302 redirects from POST to GET to match browser handling. Per RFC 7231, user agents can deviate from the strict reading of the specification for compatibility purposes.
`$location` string Required URL to redirect to. `$headers` array Required Headers for the redirect. `$data` string|array Required Body to send with the request. `$options` array Required Redirect request options. `$original` [Requests\_Response](../requests_response) Required Response object. File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public static function browser_redirect_compatibility( $location, $headers, $data, &$options, $original ) {
// Browser compatibility.
if ( 302 === $original->status_code ) {
$options['type'] = Requests::GET;
}
}
```
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Http::head( string $url, string|array $args = array() ): array|WP_Error WP\_Http::head( string $url, string|array $args = array() ): array|WP\_Error
============================================================================
Uses the HEAD HTTP method.
Used for sending data that is expected to be in the body.
`$url` string Required The request URL. `$args` string|array Optional Override the defaults. Default: `array()`
array|[WP\_Error](../wp_error) Array containing `'headers'`, `'body'`, `'response'`, `'cookies'`, `'filename'`.
A [WP\_Error](../wp_error) instance upon error.
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public function head( $url, $args = array() ) {
$defaults = array( 'method' => 'HEAD' );
$parsed_args = wp_parse_args( $args, $defaults );
return $this->request( $url, $parsed_args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Http::request()](request) wp-includes/class-wp-http.php | Send an HTTP request to a URI. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_Http::get( string $url, string|array $args = array() ): array|WP_Error WP\_Http::get( string $url, string|array $args = array() ): array|WP\_Error
===========================================================================
Uses the GET HTTP method.
Used for sending data that is expected to be in the body.
`$url` string Required The request URL. `$args` string|array Optional Override the defaults. Default: `array()`
array|[WP\_Error](../wp_error) Array containing `'headers'`, `'body'`, `'response'`, `'cookies'`, `'filename'`.
A [WP\_Error](../wp_error) instance upon error.
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public function get( $url, $args = array() ) {
$defaults = array( 'method' => 'GET' );
$parsed_args = wp_parse_args( $args, $defaults );
return $this->request( $url, $parsed_args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Http::request()](request) wp-includes/class-wp-http.php | Send an HTTP request to a URI. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_Http::processResponse( string $response ): array WP\_Http::processResponse( string $response ): array
====================================================
Parses the responses and splits the parts into headers and body.
`$response` string Required The full response string. array Array with response headers and body.
* `headers`stringHTTP response headers.
* `body`stringHTTP response body.
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public static function processResponse( $response ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
$response = explode( "\r\n\r\n", $response, 2 );
return array(
'headers' => $response[0],
'body' => isset( $response[1] ) ? $response[1] : '',
);
}
```
| Used By | Description |
| --- | --- |
| [WP\_Http\_Streams::request()](../wp_http_streams/request) wp-includes/class-wp-http-streams.php | Send a HTTP request to a URI using PHP Streams. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_Http::request( string $url, string|array $args = array() ): array|WP_Error WP\_Http::request( string $url, string|array $args = array() ): array|WP\_Error
===============================================================================
Send an HTTP request to a URI.
Please note: The only URI that are supported in the HTTP Transport implementation are the HTTP and HTTPS protocols.
`$url` string Required The request URL. `$args` string|array Optional Array or string of HTTP request arguments.
* `method`stringRequest method. Accepts `'GET'`, `'POST'`, `'HEAD'`, `'PUT'`, `'DELETE'`, `'TRACE'`, `'OPTIONS'`, or `'PATCH'`.
Some transports technically allow others, but should not be assumed. Default `'GET'`.
* `timeout`floatHow long the connection should stay open in seconds. Default 5.
* `redirection`intNumber of allowed redirects. Not supported by all transports.
Default 5.
* `httpversion`stringVersion of the HTTP protocol to use. Accepts `'1.0'` and `'1.1'`.
Default `'1.0'`.
* `user-agent`stringUser-agent value sent.
Default `'WordPress/'` . get\_bloginfo( `'version'` ) . '; ' . get\_bloginfo( `'url'` ).
* `reject_unsafe_urls`boolWhether to pass URLs through [wp\_http\_validate\_url()](../../functions/wp_http_validate_url) .
Default false.
* `blocking`boolWhether the calling code requires the result of the request.
If set to false, the request will be sent to the remote server, and processing returned to the calling code immediately, the caller will know if the request succeeded or failed, but will not receive any response from the remote server. Default true.
* `headers`string|arrayArray or string of headers to send with the request.
* `cookies`arrayList of cookies to send with the request.
* `body`string|arrayBody to send with the request. Default null.
* `compress`boolWhether to compress the $body when sending the request.
Default false.
* `decompress`boolWhether to decompress a compressed response. If set to false and compressed content is returned in the response anyway, it will need to be separately decompressed. Default true.
* `sslverify`boolWhether to verify SSL for the request. Default true.
* `sslcertificates`stringAbsolute path to an SSL certificate .crt file.
Default ABSPATH . WPINC . `'/certificates/ca-bundle.crt'`.
* `stream`boolWhether to stream to a file. If set to true and no filename was given, it will be dropped it in the WP temp dir and its name will be set using the basename of the URL. Default false.
* `filename`stringFilename of the file to write to when streaming. $stream must be set to true. Default null.
* `limit_response_size`intSize in bytes to limit the response to. Default null.
Default: `array()`
array|[WP\_Error](../wp_error) Array containing `'headers'`, `'body'`, `'response'`, `'cookies'`, `'filename'`.
A [WP\_Error](../wp_error) instance upon error.
File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/)
```
public function request( $url, $args = array() ) {
$defaults = array(
'method' => 'GET',
/**
* Filters the timeout value for an HTTP request.
*
* @since 2.7.0
* @since 5.1.0 The `$url` parameter was added.
*
* @param float $timeout_value Time in seconds until a request times out. Default 5.
* @param string $url The request URL.
*/
'timeout' => apply_filters( 'http_request_timeout', 5, $url ),
/**
* Filters the number of redirects allowed during an HTTP request.
*
* @since 2.7.0
* @since 5.1.0 The `$url` parameter was added.
*
* @param int $redirect_count Number of redirects allowed. Default 5.
* @param string $url The request URL.
*/
'redirection' => apply_filters( 'http_request_redirection_count', 5, $url ),
/**
* Filters the version of the HTTP protocol used in a request.
*
* @since 2.7.0
* @since 5.1.0 The `$url` parameter was added.
*
* @param string $version Version of HTTP used. Accepts '1.0' and '1.1'. Default '1.0'.
* @param string $url The request URL.
*/
'httpversion' => apply_filters( 'http_request_version', '1.0', $url ),
/**
* Filters the user agent value sent with an HTTP request.
*
* @since 2.7.0
* @since 5.1.0 The `$url` parameter was added.
*
* @param string $user_agent WordPress user agent string.
* @param string $url The request URL.
*/
'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ), $url ),
/**
* Filters whether to pass URLs through wp_http_validate_url() in an HTTP request.
*
* @since 3.6.0
* @since 5.1.0 The `$url` parameter was added.
*
* @param bool $pass_url Whether to pass URLs through wp_http_validate_url(). Default false.
* @param string $url The request URL.
*/
'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false, $url ),
'blocking' => true,
'headers' => array(),
'cookies' => array(),
'body' => null,
'compress' => false,
'decompress' => true,
'sslverify' => true,
'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
'stream' => false,
'filename' => null,
'limit_response_size' => null,
);
// Pre-parse for the HEAD checks.
$args = wp_parse_args( $args );
// By default, HEAD requests do not cause redirections.
if ( isset( $args['method'] ) && 'HEAD' === $args['method'] ) {
$defaults['redirection'] = 0;
}
$parsed_args = wp_parse_args( $args, $defaults );
/**
* Filters the arguments used in an HTTP request.
*
* @since 2.7.0
*
* @param array $parsed_args An array of HTTP request arguments.
* @param string $url The request URL.
*/
$parsed_args = apply_filters( 'http_request_args', $parsed_args, $url );
// The transports decrement this, store a copy of the original value for loop purposes.
if ( ! isset( $parsed_args['_redirection'] ) ) {
$parsed_args['_redirection'] = $parsed_args['redirection'];
}
/**
* Filters the preemptive return value of an HTTP request.
*
* Returning a non-false value from the filter will short-circuit the HTTP request and return
* early with that value. A filter should return one of:
*
* - An array containing 'headers', 'body', 'response', 'cookies', and 'filename' elements
* - A WP_Error instance
* - boolean false to avoid short-circuiting the response
*
* Returning any other value may result in unexpected behaviour.
*
* @since 2.9.0
*
* @param false|array|WP_Error $preempt A preemptive return value of an HTTP request. Default false.
* @param array $parsed_args HTTP request arguments.
* @param string $url The request URL.
*/
$pre = apply_filters( 'pre_http_request', false, $parsed_args, $url );
if ( false !== $pre ) {
return $pre;
}
if ( function_exists( 'wp_kses_bad_protocol' ) ) {
if ( $parsed_args['reject_unsafe_urls'] ) {
$url = wp_http_validate_url( $url );
}
if ( $url ) {
$url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) );
}
}
$parsed_url = parse_url( $url );
if ( empty( $url ) || empty( $parsed_url['scheme'] ) ) {
$response = new WP_Error( 'http_request_failed', __( 'A valid URL was not provided.' ) );
/** This action is documented in wp-includes/class-wp-http.php */
do_action( 'http_api_debug', $response, 'response', 'Requests', $parsed_args, $url );
return $response;
}
if ( $this->block_request( $url ) ) {
$response = new WP_Error( 'http_request_not_executed', __( 'User has blocked requests through HTTP.' ) );
/** This action is documented in wp-includes/class-wp-http.php */
do_action( 'http_api_debug', $response, 'response', 'Requests', $parsed_args, $url );
return $response;
}
// If we are streaming to a file but no filename was given drop it in the WP temp dir
// and pick its name using the basename of the $url.
if ( $parsed_args['stream'] ) {
if ( empty( $parsed_args['filename'] ) ) {
$parsed_args['filename'] = get_temp_dir() . basename( $url );
}
// Force some settings if we are streaming to a file and check for existence
// and perms of destination directory.
$parsed_args['blocking'] = true;
if ( ! wp_is_writable( dirname( $parsed_args['filename'] ) ) ) {
$response = new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) );
/** This action is documented in wp-includes/class-wp-http.php */
do_action( 'http_api_debug', $response, 'response', 'Requests', $parsed_args, $url );
return $response;
}
}
if ( is_null( $parsed_args['headers'] ) ) {
$parsed_args['headers'] = array();
}
// WP allows passing in headers as a string, weirdly.
if ( ! is_array( $parsed_args['headers'] ) ) {
$processed_headers = WP_Http::processHeaders( $parsed_args['headers'] );
$parsed_args['headers'] = $processed_headers['headers'];
}
// Setup arguments.
$headers = $parsed_args['headers'];
$data = $parsed_args['body'];
$type = $parsed_args['method'];
$options = array(
'timeout' => $parsed_args['timeout'],
'useragent' => $parsed_args['user-agent'],
'blocking' => $parsed_args['blocking'],
'hooks' => new WP_HTTP_Requests_Hooks( $url, $parsed_args ),
);
// Ensure redirects follow browser behaviour.
$options['hooks']->register( 'requests.before_redirect', array( get_class(), 'browser_redirect_compatibility' ) );
// Validate redirected URLs.
if ( function_exists( 'wp_kses_bad_protocol' ) && $parsed_args['reject_unsafe_urls'] ) {
$options['hooks']->register( 'requests.before_redirect', array( get_class(), 'validate_redirects' ) );
}
if ( $parsed_args['stream'] ) {
$options['filename'] = $parsed_args['filename'];
}
if ( empty( $parsed_args['redirection'] ) ) {
$options['follow_redirects'] = false;
} else {
$options['redirects'] = $parsed_args['redirection'];
}
// Use byte limit, if we can.
if ( isset( $parsed_args['limit_response_size'] ) ) {
$options['max_bytes'] = $parsed_args['limit_response_size'];
}
// If we've got cookies, use and convert them to Requests_Cookie.
if ( ! empty( $parsed_args['cookies'] ) ) {
$options['cookies'] = WP_Http::normalize_cookies( $parsed_args['cookies'] );
}
// SSL certificate handling.
if ( ! $parsed_args['sslverify'] ) {
$options['verify'] = false;
$options['verifyname'] = false;
} else {
$options['verify'] = $parsed_args['sslcertificates'];
}
// All non-GET/HEAD requests should put the arguments in the form body.
if ( 'HEAD' !== $type && 'GET' !== $type ) {
$options['data_format'] = 'body';
}
/**
* Filters whether SSL should be verified for non-local requests.
*
* @since 2.8.0
* @since 5.1.0 The `$url` parameter was added.
*
* @param bool $ssl_verify Whether to verify the SSL connection. Default true.
* @param string $url The request URL.
*/
$options['verify'] = apply_filters( 'https_ssl_verify', $options['verify'], $url );
// Check for proxies.
$proxy = new WP_HTTP_Proxy();
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
$options['proxy'] = new Requests_Proxy_HTTP( $proxy->host() . ':' . $proxy->port() );
if ( $proxy->use_authentication() ) {
$options['proxy']->use_authentication = true;
$options['proxy']->user = $proxy->username();
$options['proxy']->pass = $proxy->password();
}
}
// Avoid issues where mbstring.func_overload is enabled.
mbstring_binary_safe_encoding();
try {
$requests_response = Requests::request( $url, $headers, $data, $type, $options );
// Convert the response into an array.
$http_response = new WP_HTTP_Requests_Response( $requests_response, $parsed_args['filename'] );
$response = $http_response->to_array();
// Add the original object to the array.
$response['http_response'] = $http_response;
} catch ( Requests_Exception $e ) {
$response = new WP_Error( 'http_request_failed', $e->getMessage() );
}
reset_mbstring_encoding();
/**
* Fires after an HTTP API response is received and before the response is returned.
*
* @since 2.8.0
*
* @param array|WP_Error $response HTTP response or WP_Error object.
* @param string $context Context under which the hook is fired.
* @param string $class HTTP transport used.
* @param array $parsed_args HTTP request arguments.
* @param string $url The request URL.
*/
do_action( 'http_api_debug', $response, 'response', 'Requests', $parsed_args, $url );
if ( is_wp_error( $response ) ) {
return $response;
}
if ( ! $parsed_args['blocking'] ) {
return array(
'headers' => array(),
'body' => '',
'response' => array(
'code' => false,
'message' => false,
),
'cookies' => array(),
'http_response' => null,
);
}
/**
* Filters a successful HTTP API response immediately before the response is returned.
*
* @since 2.9.0
*
* @param array $response HTTP response.
* @param array $parsed_args HTTP request arguments.
* @param string $url The request URL.
*/
return apply_filters( 'http_response', $response, $parsed_args, $url );
}
```
[apply\_filters( 'https\_ssl\_verify', bool $ssl\_verify, string $url )](../../hooks/https_ssl_verify)
Filters whether SSL should be verified for non-local requests.
[do\_action( 'http\_api\_debug', array|WP\_Error $response, string $context, string $class, array $parsed\_args, string $url )](../../hooks/http_api_debug)
Fires after an HTTP API response is received and before the response is returned.
[apply\_filters( 'http\_headers\_useragent', string $user\_agent, string $url )](../../hooks/http_headers_useragent)
Filters the user agent value sent with an HTTP request.
[apply\_filters( 'http\_request\_args', array $parsed\_args, string $url )](../../hooks/http_request_args)
Filters the arguments used in an HTTP request.
[apply\_filters( 'http\_request\_redirection\_count', int $redirect\_count, string $url )](../../hooks/http_request_redirection_count)
Filters the number of redirects allowed during an HTTP request.
[apply\_filters( 'http\_request\_reject\_unsafe\_urls', bool $pass\_url, string $url )](../../hooks/http_request_reject_unsafe_urls)
Filters whether to pass URLs through [wp\_http\_validate\_url()](../../functions/wp_http_validate_url) in an HTTP request.
[apply\_filters( 'http\_request\_timeout', float $timeout\_value, string $url )](../../hooks/http_request_timeout)
Filters the timeout value for an HTTP request.
[apply\_filters( 'http\_request\_version', string $version, string $url )](../../hooks/http_request_version)
Filters the version of the HTTP protocol used in a request.
[apply\_filters( 'http\_response', array $response, array $parsed\_args, string $url )](../../hooks/http_response)
Filters a successful HTTP API response immediately before the response is returned.
[apply\_filters( 'pre\_http\_request', false|array|WP\_Error $preempt, array $parsed\_args, string $url )](../../hooks/pre_http_request)
Filters the preemptive return value of an HTTP request.
| Uses | Description |
| --- | --- |
| [WP\_HTTP\_Requests\_Hooks::\_\_construct()](../wp_http_requests_hooks/__construct) wp-includes/class-wp-http-requests-hooks.php | Constructor. |
| [WP\_Http::processHeaders()](processheaders) wp-includes/class-wp-http.php | Transforms header string into an array. |
| [wp\_http\_validate\_url()](../../functions/wp_http_validate_url) wp-includes/http.php | Validate a URL for safe use in the HTTP API. |
| [wp\_is\_writable()](../../functions/wp_is_writable) wp-includes/functions.php | Determines if a directory is writable. |
| [get\_temp\_dir()](../../functions/get_temp_dir) wp-includes/functions.php | Determines a writable directory for temporary files. |
| [mbstring\_binary\_safe\_encoding()](../../functions/mbstring_binary_safe_encoding) wp-includes/functions.php | Sets the mbstring internal encoding to a binary safe encoding when func\_overload is enabled. |
| [Requests::request()](../requests/request) wp-includes/class-requests.php | Main interface for HTTP requests |
| [reset\_mbstring\_encoding()](../../functions/reset_mbstring_encoding) wp-includes/functions.php | Resets the mbstring internal encoding to a users previously set encoding. |
| [WP\_Http::block\_request()](block_request) wp-includes/class-wp-http.php | Determines whether an HTTP API request to the given URL should be blocked. |
| [wp\_kses\_bad\_protocol()](../../functions/wp_kses_bad_protocol) wp-includes/kses.php | Sanitizes a string and removed disallowed URL protocols. |
| [WP\_Http::normalize\_cookies()](normalize_cookies) wp-includes/class-wp-http.php | Normalizes cookies for using in Requests. |
| [WP\_HTTP\_Requests\_Response::\_\_construct()](../wp_http_requests_response/__construct) wp-includes/class-wp-http-requests-response.php | Constructor. |
| [Requests\_Proxy\_HTTP::\_\_construct()](../requests_proxy_http/__construct) wp-includes/Requests/Proxy/HTTP.php | Constructor |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Http::post()](post) wp-includes/class-wp-http.php | Uses the POST HTTP method. |
| [WP\_Http::get()](get) wp-includes/class-wp-http.php | Uses the GET HTTP method. |
| [WP\_Http::head()](head) wp-includes/class-wp-http.php | Uses the HEAD HTTP method. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Taxonomies_Controller::get_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Taxonomies\_Controller::get\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=======================================================================================================
Retrieves a specific taxonomy.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php/)
```
public function get_item( $request ) {
$tax_obj = get_taxonomy( $request['taxonomy'] );
if ( empty( $tax_obj ) ) {
return new WP_Error(
'rest_taxonomy_invalid',
__( 'Invalid taxonomy.' ),
array( 'status' => 404 )
);
}
$data = $this->prepare_item_for_response( $tax_obj, $request );
return rest_ensure_response( $data );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Taxonomies\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Prepares a taxonomy object for serialization. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_taxonomy()](../../functions/get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Taxonomies_Controller::prepare_item_for_response( WP_Taxonomy $item, WP_REST_Request $request ): WP_REST_Response WP\_REST\_Taxonomies\_Controller::prepare\_item\_for\_response( WP\_Taxonomy $item, WP\_REST\_Request $request ): WP\_REST\_Response
====================================================================================================================================
Prepares a taxonomy object for serialization.
`$item` [WP\_Taxonomy](../wp_taxonomy) Required Taxonomy data. `$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response) Response object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php/)
```
public function prepare_item_for_response( $item, $request ) {
// Restores the more descriptive, specific name for use within this method.
$taxonomy = $item;
$base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
$fields = $this->get_fields_for_response( $request );
$data = array();
if ( in_array( 'name', $fields, true ) ) {
$data['name'] = $taxonomy->label;
}
if ( in_array( 'slug', $fields, true ) ) {
$data['slug'] = $taxonomy->name;
}
if ( in_array( 'capabilities', $fields, true ) ) {
$data['capabilities'] = $taxonomy->cap;
}
if ( in_array( 'description', $fields, true ) ) {
$data['description'] = $taxonomy->description;
}
if ( in_array( 'labels', $fields, true ) ) {
$data['labels'] = $taxonomy->labels;
}
if ( in_array( 'types', $fields, true ) ) {
$data['types'] = array_values( $taxonomy->object_type );
}
if ( in_array( 'show_cloud', $fields, true ) ) {
$data['show_cloud'] = $taxonomy->show_tagcloud;
}
if ( in_array( 'hierarchical', $fields, true ) ) {
$data['hierarchical'] = $taxonomy->hierarchical;
}
if ( in_array( 'rest_base', $fields, true ) ) {
$data['rest_base'] = $base;
}
if ( in_array( 'rest_namespace', $fields, true ) ) {
$data['rest_namespace'] = $taxonomy->rest_namespace;
}
if ( in_array( 'visibility', $fields, true ) ) {
$data['visibility'] = array(
'public' => (bool) $taxonomy->public,
'publicly_queryable' => (bool) $taxonomy->publicly_queryable,
'show_admin_column' => (bool) $taxonomy->show_admin_column,
'show_in_nav_menus' => (bool) $taxonomy->show_in_nav_menus,
'show_in_quick_edit' => (bool) $taxonomy->show_in_quick_edit,
'show_ui' => (bool) $taxonomy->show_ui,
);
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
// Wrap the data in a response object.
$response = rest_ensure_response( $data );
if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
$response->add_links( $this->prepare_links( $taxonomy ) );
}
/**
* Filters a taxonomy returned from the REST API.
*
* Allows modification of the taxonomy data right before it is returned.
*
* @since 4.7.0
*
* @param WP_REST_Response $response The response object.
* @param WP_Taxonomy $item The original taxonomy object.
* @param WP_REST_Request $request Request used to generate the response.
*/
return apply_filters( 'rest_prepare_taxonomy', $response, $taxonomy, $request );
}
```
[apply\_filters( 'rest\_prepare\_taxonomy', WP\_REST\_Response $response, WP\_Taxonomy $item, WP\_REST\_Request $request )](../../hooks/rest_prepare_taxonomy)
Filters a taxonomy returned from the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Taxonomies\_Controller::prepare\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Prepares links for the request. |
| [rest\_is\_field\_included()](../../functions/rest_is_field_included) wp-includes/rest-api.php | Given an array of fields to include in a response, some of which may be `nested.fields`, determine whether the provided field should be included in the response body. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Taxonomies\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Retrieves a specific taxonomy. |
| [WP\_REST\_Taxonomies\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Retrieves all public taxonomies. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$taxonomy` to `$item` to match parent class for PHP 8 named parameter support. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Taxonomies_Controller::prepare_links( WP_Taxonomy $taxonomy ): array WP\_REST\_Taxonomies\_Controller::prepare\_links( WP\_Taxonomy $taxonomy ): array
=================================================================================
Prepares links for the request.
`$taxonomy` [WP\_Taxonomy](../wp_taxonomy) Required The taxonomy. array Links for the given taxonomy.
File: `wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php/)
```
protected function prepare_links( $taxonomy ) {
return array(
'collection' => array(
'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
),
'https://api.w.org/items' => array(
'href' => rest_url( rest_get_route_for_taxonomy_items( $taxonomy->name ) ),
),
);
}
```
| Uses | Description |
| --- | --- |
| [rest\_get\_route\_for\_taxonomy\_items()](../../functions/rest_get_route_for_taxonomy_items) wp-includes/rest-api.php | Gets the REST API route for a taxonomy. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Taxonomies\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Prepares a taxonomy object for serialization. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_REST_Taxonomies_Controller::get_items( WP_REST_Request $request ): WP_REST_Response WP\_REST\_Taxonomies\_Controller::get\_items( WP\_REST\_Request $request ): WP\_REST\_Response
==============================================================================================
Retrieves all public taxonomies.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php/)
```
public function get_items( $request ) {
// Retrieve the list of registered collection query parameters.
$registered = $this->get_collection_params();
if ( isset( $registered['type'] ) && ! empty( $request['type'] ) ) {
$taxonomies = get_object_taxonomies( $request['type'], 'objects' );
} else {
$taxonomies = get_taxonomies( '', 'objects' );
}
$data = array();
foreach ( $taxonomies as $tax_type => $value ) {
if ( empty( $value->show_in_rest ) || ( 'edit' === $request['context'] && ! current_user_can( $value->cap->assign_terms ) ) ) {
continue;
}
$tax = $this->prepare_item_for_response( $value, $request );
$tax = $this->prepare_response_for_collection( $tax );
$data[ $tax_type ] = $tax;
}
if ( empty( $data ) ) {
// Response should still be returned as a JSON object when it is empty.
$data = (object) $data;
}
return rest_ensure_response( $data );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Taxonomies\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Retrieves the query params for collections. |
| [WP\_REST\_Taxonomies\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Prepares a taxonomy object for serialization. |
| [get\_object\_taxonomies()](../../functions/get_object_taxonomies) wp-includes/taxonomy.php | Returns the names or objects of the taxonomies which are registered for the requested object or object type, such as a post object or post type name. |
| [get\_taxonomies()](../../functions/get_taxonomies) wp-includes/taxonomy.php | Retrieves a list of registered taxonomy names or objects. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Taxonomies_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Taxonomies\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
==============================================================================================================
Checks whether a given request has permission to read taxonomies.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php/)
```
public function get_items_permissions_check( $request ) {
if ( 'edit' === $request['context'] ) {
if ( ! empty( $request['type'] ) ) {
$taxonomies = get_object_taxonomies( $request['type'], 'objects' );
} else {
$taxonomies = get_taxonomies( '', 'objects' );
}
foreach ( $taxonomies as $taxonomy ) {
if ( ! empty( $taxonomy->show_in_rest ) && current_user_can( $taxonomy->cap->assign_terms ) ) {
return true;
}
}
return new WP_Error(
'rest_cannot_view',
__( 'Sorry, you are not allowed to manage terms in this taxonomy.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [get\_object\_taxonomies()](../../functions/get_object_taxonomies) wp-includes/taxonomy.php | Returns the names or objects of the taxonomies which are registered for the requested object or object type, such as a post object or post type name. |
| [get\_taxonomies()](../../functions/get_taxonomies) wp-includes/taxonomy.php | Retrieves a list of registered taxonomy names or objects. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Taxonomies_Controller::register_routes() WP\_REST\_Taxonomies\_Controller::register\_routes()
====================================================
Registers the routes for taxonomies.
* [register\_rest\_route()](../../functions/register_rest_route)
File: `wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php/)
```
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base,
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => $this->get_collection_params(),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/(?P<taxonomy>[\w-]+)',
array(
'args' => array(
'taxonomy' => array(
'description' => __( 'An alphanumeric identifier for the taxonomy.' ),
'type' => 'string',
),
),
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this, 'get_item_permissions_check' ),
'args' => array(
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Taxonomies\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Retrieves the query params for collections. |
| [register\_rest\_route()](../../functions/register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Taxonomies_Controller::get_collection_params(): array WP\_REST\_Taxonomies\_Controller::get\_collection\_params(): array
==================================================================
Retrieves the query params for collections.
array Collection parameters.
File: `wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php/)
```
public function get_collection_params() {
$new_params = array();
$new_params['context'] = $this->get_context_param( array( 'default' => 'view' ) );
$new_params['type'] = array(
'description' => __( 'Limit results to taxonomies associated with a specific post type.' ),
'type' => 'string',
);
return $new_params;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Taxonomies\_Controller::register\_routes()](register_routes) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Registers the routes for taxonomies. |
| [WP\_REST\_Taxonomies\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Retrieves all public taxonomies. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Taxonomies_Controller::__construct() WP\_REST\_Taxonomies\_Controller::\_\_construct()
=================================================
Constructor.
File: `wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php/)
```
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'taxonomies';
}
```
| Used By | Description |
| --- | --- |
| [create\_initial\_rest\_routes()](../../functions/create_initial_rest_routes) wp-includes/rest-api.php | Registers default REST API routes. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Taxonomies_Controller::get_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Taxonomies\_Controller::get\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=============================================================================================================
Checks if a given request has access to a taxonomy.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access for the item, otherwise false or [WP\_Error](../wp_error) object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php/)
```
public function get_item_permissions_check( $request ) {
$tax_obj = get_taxonomy( $request['taxonomy'] );
if ( $tax_obj ) {
if ( empty( $tax_obj->show_in_rest ) ) {
return false;
}
if ( 'edit' === $request['context'] && ! current_user_can( $tax_obj->cap->assign_terms ) ) {
return new WP_Error(
'rest_forbidden_context',
__( 'Sorry, you are not allowed to manage terms in this taxonomy.' ),
array( 'status' => rest_authorization_required_code() )
);
}
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_taxonomy()](../../functions/get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Taxonomies_Controller::get_item_schema(): array WP\_REST\_Taxonomies\_Controller::get\_item\_schema(): array
============================================================
Retrieves the taxonomy’s schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php/)
```
public function get_item_schema() {
if ( $this->schema ) {
return $this->add_additional_fields_schema( $this->schema );
}
$schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'taxonomy',
'type' => 'object',
'properties' => array(
'capabilities' => array(
'description' => __( 'All capabilities used by the taxonomy.' ),
'type' => 'object',
'context' => array( 'edit' ),
'readonly' => true,
),
'description' => array(
'description' => __( 'A human-readable description of the taxonomy.' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'hierarchical' => array(
'description' => __( 'Whether or not the taxonomy should have children.' ),
'type' => 'boolean',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'labels' => array(
'description' => __( 'Human-readable labels for the taxonomy for various contexts.' ),
'type' => 'object',
'context' => array( 'edit' ),
'readonly' => true,
),
'name' => array(
'description' => __( 'The title for the taxonomy.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
),
'slug' => array(
'description' => __( 'An alphanumeric identifier for the taxonomy.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
),
'show_cloud' => array(
'description' => __( 'Whether or not the term cloud should be displayed.' ),
'type' => 'boolean',
'context' => array( 'edit' ),
'readonly' => true,
),
'types' => array(
'description' => __( 'Types associated with the taxonomy.' ),
'type' => 'array',
'items' => array(
'type' => 'string',
),
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'rest_base' => array(
'description' => __( 'REST base route for the taxonomy.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
),
'rest_namespace' => array(
'description' => __( 'REST namespace route for the taxonomy.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
),
'visibility' => array(
'description' => __( 'The visibility settings for the taxonomy.' ),
'type' => 'object',
'context' => array( 'edit' ),
'readonly' => true,
'properties' => array(
'public' => array(
'description' => __( 'Whether a taxonomy is intended for use publicly either via the admin interface or by front-end users.' ),
'type' => 'boolean',
),
'publicly_queryable' => array(
'description' => __( 'Whether the taxonomy is publicly queryable.' ),
'type' => 'boolean',
),
'show_ui' => array(
'description' => __( 'Whether to generate a default UI for managing this taxonomy.' ),
'type' => 'boolean',
),
'show_admin_column' => array(
'description' => __( 'Whether to allow automatic creation of taxonomy columns on associated post-types table.' ),
'type' => 'boolean',
),
'show_in_nav_menus' => array(
'description' => __( 'Whether to make the taxonomy available for selection in navigation menus.' ),
'type' => 'boolean',
),
'show_in_quick_edit' => array(
'description' => __( 'Whether to show the taxonomy in the quick/bulk edit panel.' ),
'type' => 'boolean',
),
),
),
),
);
$this->schema = $schema;
return $this->add_additional_fields_schema( $this->schema );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | The `rest_namespace` property was added. |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | The `visibility` property was added. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress POMO_StringReader::read( string $bytes ): string POMO\_StringReader::read( string $bytes ): string
=================================================
`$bytes` string Required string
File: `wp-includes/pomo/streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/streams.php/)
```
public function read( $bytes ) {
$data = $this->substr( $this->_str, $this->_pos, $bytes );
$this->_pos += $bytes;
if ( $this->strlen( $this->_str ) < $this->_pos ) {
$this->_pos = $this->strlen( $this->_str );
}
return $data;
}
```
wordpress POMO_StringReader::seekto( int $pos ): int POMO\_StringReader::seekto( int $pos ): int
===========================================
`$pos` int Required int
File: `wp-includes/pomo/streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/streams.php/)
```
public function seekto( $pos ) {
$this->_pos = $pos;
if ( $this->strlen( $this->_str ) < $this->_pos ) {
$this->_pos = $this->strlen( $this->_str );
}
return $this->_pos;
}
```
wordpress POMO_StringReader::read_all(): string POMO\_StringReader::read\_all(): string
=======================================
string
File: `wp-includes/pomo/streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/streams.php/)
```
public function read_all() {
return $this->substr( $this->_str, $this->_pos, $this->strlen( $this->_str ) );
}
```
wordpress POMO_StringReader::length(): int POMO\_StringReader::length(): int
=================================
int
File: `wp-includes/pomo/streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/streams.php/)
```
public function length() {
return $this->strlen( $this->_str );
}
```
wordpress POMO_StringReader::__construct( $str = '' ) POMO\_StringReader::\_\_construct( $str = '' )
==============================================
PHP5 constructor.
File: `wp-includes/pomo/streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/streams.php/)
```
public function __construct( $str = '' ) {
parent::__construct();
$this->_str = $str;
$this->_pos = 0;
}
```
| Uses | Description |
| --- | --- |
| [POMO\_Reader::\_\_construct()](../pomo_reader/__construct) wp-includes/pomo/streams.php | PHP5 constructor. |
| Used By | Description |
| --- | --- |
| [POMO\_CachedFileReader::\_\_construct()](../pomo_cachedfilereader/__construct) wp-includes/pomo/streams.php | PHP5 constructor. |
| [POMO\_StringReader::POMO\_StringReader()](pomo_stringreader) wp-includes/pomo/streams.php | PHP4 constructor. |
wordpress POMO_StringReader::POMO_StringReader( $str = '' ) POMO\_StringReader::POMO\_StringReader( $str = '' )
===================================================
This method has been deprecated. Use [POMO\_StringReader::\_\_construct()](../pomo_stringreader/__construct) instead.
PHP4 constructor.
* [POMO\_StringReader::\_\_construct()](../pomo_stringreader/__construct)
File: `wp-includes/pomo/streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/streams.php/)
```
public function POMO_StringReader( $str = '' ) {
_deprecated_constructor( self::class, '5.4.0', static::class );
self::__construct( $str );
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_constructor()](../../functions/_deprecated_constructor) wp-includes/functions.php | Marks a constructor as deprecated and informs when it has been used. |
| [POMO\_StringReader::\_\_construct()](__construct) wp-includes/pomo/streams.php | PHP5 constructor. |
| Version | Description |
| --- | --- |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | Introduced. |
wordpress Requests_Exception_HTTP::getReason() Requests\_Exception\_HTTP::getReason()
======================================
Get the status message
File: `wp-includes/Requests/Exception/HTTP.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http.php/)
```
public function getReason() {
return $this->reason;
}
```
wordpress Requests_Exception_HTTP::__construct( string|null $reason = null, mixed $data = null ) Requests\_Exception\_HTTP::\_\_construct( string|null $reason = null, mixed $data = null )
==========================================================================================
Create a new exception
There is no mechanism to pass in the status code, as this is set by the subclass used. Reason phrases can vary, however.
`$reason` string|null Optional Reason phrase Default: `null`
`$data` mixed Optional Associated data Default: `null`
File: `wp-includes/Requests/Exception/HTTP.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http.php/)
```
public function __construct($reason = null, $data = null) {
if ($reason !== null) {
$this->reason = $reason;
}
$message = sprintf('%d %s', $this->code, $this->reason);
parent::__construct($message, 'httpresponse', $data, $this->code);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
| Used By | Description |
| --- | --- |
| [Requests\_Exception\_HTTP\_Unknown::\_\_construct()](../requests_exception_http_unknown/__construct) wp-includes/Requests/Exception/HTTP/Unknown.php | Create a new exception |
wordpress Requests_Exception_HTTP::get_class( int|bool $code ): string Requests\_Exception\_HTTP::get\_class( int|bool $code ): string
===============================================================
Get the correct exception class for a given error code
`$code` int|bool Required HTTP status code, or false if unavailable string Exception class name to use
File: `wp-includes/Requests/Exception/HTTP.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http.php/)
```
public static function get_class($code) {
if (!$code) {
return 'Requests_Exception_HTTP_Unknown';
}
$class = sprintf('Requests_Exception_HTTP_%d', $code);
if (class_exists($class)) {
return $class;
}
return 'Requests_Exception_HTTP_Unknown';
}
```
| Used By | Description |
| --- | --- |
| [Requests\_Response::throw\_for\_status()](../requests_response/throw_for_status) wp-includes/Requests/Response.php | Throws an exception if the request was not successful |
wordpress WP_Recovery_Mode_Link_Service::generate_url(): string WP\_Recovery\_Mode\_Link\_Service::generate\_url(): string
==========================================================
Generates a URL to begin recovery mode.
Only one recovery mode URL can may be valid at the same time.
string Generated URL.
File: `wp-includes/class-wp-recovery-mode-link-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-link-service.php/)
```
public function generate_url() {
$token = $this->key_service->generate_recovery_mode_token();
$key = $this->key_service->generate_and_store_recovery_mode_key( $token );
return $this->get_recovery_mode_begin_url( $token, $key );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Link\_Service::get\_recovery\_mode\_begin\_url()](get_recovery_mode_begin_url) wp-includes/class-wp-recovery-mode-link-service.php | Gets a URL to begin recovery mode. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Recovery_Mode_Link_Service::get_recovery_mode_begin_url( string $token, string $key ): string WP\_Recovery\_Mode\_Link\_Service::get\_recovery\_mode\_begin\_url( string $token, string $key ): string
========================================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Gets a URL to begin recovery mode.
`$token` string Required Recovery Mode token created by [generate\_recovery\_mode\_token()](../../functions/generate_recovery_mode_token). `$key` string Required Recovery Mode key created by [generate\_and\_store\_recovery\_mode\_key()](../../functions/generate_and_store_recovery_mode_key). string Recovery mode begin URL.
File: `wp-includes/class-wp-recovery-mode-link-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-link-service.php/)
```
private function get_recovery_mode_begin_url( $token, $key ) {
$url = add_query_arg(
array(
'action' => self::LOGIN_ACTION_ENTER,
'rm_token' => $token,
'rm_key' => $key,
),
wp_login_url()
);
/**
* Filters the URL to begin recovery mode.
*
* @since 5.2.0
*
* @param string $url The generated recovery mode begin URL.
* @param string $token The token used to identify the key.
* @param string $key The recovery mode key.
*/
return apply_filters( 'recovery_mode_begin_url', $url, $token, $key );
}
```
[apply\_filters( 'recovery\_mode\_begin\_url', string $url, string $token, string $key )](../../hooks/recovery_mode_begin_url)
Filters the URL to begin recovery mode.
| Uses | Description |
| --- | --- |
| [wp\_login\_url()](../../functions/wp_login_url) wp-includes/general-template.php | Retrieves the login URL. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Recovery\_Mode\_Link\_Service::generate\_url()](generate_url) wp-includes/class-wp-recovery-mode-link-service.php | Generates a URL to begin recovery mode. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Recovery_Mode_Link_Service::__construct( WP_Recovery_Mode_Cookie_Service $cookie_service, WP_Recovery_Mode_Key_Service $key_service ) WP\_Recovery\_Mode\_Link\_Service::\_\_construct( WP\_Recovery\_Mode\_Cookie\_Service $cookie\_service, WP\_Recovery\_Mode\_Key\_Service $key\_service )
========================================================================================================================================================
[WP\_Recovery\_Mode\_Link\_Service](../wp_recovery_mode_link_service) constructor.
`$cookie_service` [WP\_Recovery\_Mode\_Cookie\_Service](../wp_recovery_mode_cookie_service) Required Service to handle setting the recovery mode cookie. `$key_service` [WP\_Recovery\_Mode\_Key\_Service](../wp_recovery_mode_key_service) Required Service to handle generating recovery mode keys. File: `wp-includes/class-wp-recovery-mode-link-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-link-service.php/)
```
public function __construct( WP_Recovery_Mode_Cookie_Service $cookie_service, WP_Recovery_Mode_Key_Service $key_service ) {
$this->cookie_service = $cookie_service;
$this->key_service = $key_service;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Recovery\_Mode::\_\_construct()](../wp_recovery_mode/__construct) wp-includes/class-wp-recovery-mode.php | [WP\_Recovery\_Mode](../wp_recovery_mode) constructor. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Recovery_Mode_Link_Service::handle_begin_link( int $ttl ) WP\_Recovery\_Mode\_Link\_Service::handle\_begin\_link( int $ttl )
==================================================================
Enters recovery mode when the user hits wp-login.php with a valid recovery mode link.
`$ttl` int Required Number of seconds the link should be valid for. File: `wp-includes/class-wp-recovery-mode-link-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-link-service.php/)
```
public function handle_begin_link( $ttl ) {
if ( ! isset( $GLOBALS['pagenow'] ) || 'wp-login.php' !== $GLOBALS['pagenow'] ) {
return;
}
if ( ! isset( $_GET['action'], $_GET['rm_token'], $_GET['rm_key'] ) || self::LOGIN_ACTION_ENTER !== $_GET['action'] ) {
return;
}
if ( ! function_exists( 'wp_generate_password' ) ) {
require_once ABSPATH . WPINC . '/pluggable.php';
}
$validated = $this->key_service->validate_recovery_mode_key( $_GET['rm_token'], $_GET['rm_key'], $ttl );
if ( is_wp_error( $validated ) ) {
wp_die( $validated, '' );
}
$this->cookie_service->set_cookie();
$url = add_query_arg( 'action', self::LOGIN_ACTION_ENTERED, wp_login_url() );
wp_redirect( $url );
die;
}
```
| Uses | Description |
| --- | --- |
| [wp\_redirect()](../../functions/wp_redirect) wp-includes/pluggable.php | Redirects to another page. |
| [wp\_login\_url()](../../functions/wp_login_url) wp-includes/general-template.php | Retrieves the login URL. |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress Walker_PageDropdown::start_el( string $output, WP_Post $data_object, int $depth, array $args = array(), int $current_object_id ) Walker\_PageDropdown::start\_el( string $output, WP\_Post $data\_object, int $depth, array $args = array(), int $current\_object\_id )
======================================================================================================================================
Starts the element output.
* [Walker::start\_el()](../walker/start_el)
`$output` string Required Used to append additional content. Passed by reference. `$data_object` [WP\_Post](../wp_post) Required Page data object. `$depth` int Optional Depth of page in reference to parent pages.
Used for padding. Default 0. `$args` array Optional Uses `'selected'` argument for selected page to set selected HTML attribute for option element. Uses `'value_field'` argument to fill "value" attribute.
See [wp\_dropdown\_pages()](../../functions/wp_dropdown_pages) . More Arguments from wp\_dropdown\_pages( ... $args ) Array or string of arguments to retrieve pages.
* `child_of`intPage ID to return child and grandchild pages of. Note: The value of `$hierarchical` has no bearing on whether `$child_of` returns hierarchical results. Default 0, or no restriction.
* `sort_order`stringHow to sort retrieved pages. Accepts `'ASC'`, `'DESC'`. Default `'ASC'`.
* `sort_column`stringWhat columns to sort pages by, comma-separated. Accepts `'post_author'`, `'post_date'`, `'post_title'`, `'post_name'`, `'post_modified'`, `'menu_order'`, `'post_modified_gmt'`, `'post_parent'`, `'ID'`, `'rand'`, `'comment*count'`.
`'post*'` can be omitted for any values that start with it.
Default `'post_title'`.
* `hierarchical`boolWhether to return pages hierarchically. If false in conjunction with `$child_of` also being false, both arguments will be disregarded.
Default true.
* `exclude`int[]Array of page IDs to exclude.
* `include`int[]Array of page IDs to include. Cannot be used with `$child_of`, `$parent`, `$exclude`, `$meta_key`, `$meta_value`, or `$hierarchical`.
* `meta_key`stringOnly include pages with this meta key.
* `meta_value`stringOnly include pages with this meta value. Requires `$meta_key`.
* `authors`stringA comma-separated list of author IDs.
* `parent`intPage ID to return direct children of. Default -1, or no restriction.
* `exclude_tree`string|int[]Comma-separated string or array of page IDs to exclude.
* `number`intThe number of pages to return. Default 0, or all pages.
* `offset`intThe number of pages to skip before returning. Requires `$number`.
Default 0.
* `post_type`stringThe post type to query. Default `'page'`.
* `post_status`string|arrayA comma-separated list or array of post statuses to include.
Default `'publish'`.
Default: `array()`
`$current_object_id` int Optional ID of the current page. Default 0. File: `wp-includes/class-walker-page-dropdown.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-page-dropdown.php/)
```
public function start_el( &$output, $data_object, $depth = 0, $args = array(), $current_object_id = 0 ) {
// Restores the more descriptive, specific name for use within this method.
$page = $data_object;
$pad = str_repeat( ' ', $depth * 3 );
if ( ! isset( $args['value_field'] ) || ! isset( $page->{$args['value_field']} ) ) {
$args['value_field'] = 'ID';
}
$output .= "\t<option class=\"level-$depth\" value=\"" . esc_attr( $page->{$args['value_field']} ) . '"';
if ( $page->ID == $args['selected'] ) {
$output .= ' selected="selected"';
}
$output .= '>';
$title = $page->post_title;
if ( '' === $title ) {
/* translators: %d: ID of a post. */
$title = sprintf( __( '#%d (no title)' ), $page->ID );
}
/**
* Filters the page title when creating an HTML drop-down list of pages.
*
* @since 3.1.0
*
* @param string $title Page title.
* @param WP_Post $page Page data object.
*/
$title = apply_filters( 'list_pages', $title, $page );
$output .= $pad . esc_html( $title );
$output .= "</option>\n";
}
```
[apply\_filters( 'list\_pages', string $title, WP\_Post $page )](../../hooks/list_pages)
Filters the page title when creating an HTML drop-down list of pages.
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$page` to `$data_object` and `$id` to `$current_object_id` to match parent class for PHP 8 named parameter support. |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Panel::content_template() WP\_Customize\_Panel::content\_template()
=========================================
An Underscore (JS) template for this panel’s content (but not its container).
Class variables for this panel class are available in the `data` JS object; export custom variables by overriding [WP\_Customize\_Panel::json()](json).
* [WP\_Customize\_Panel::print\_template()](../wp_customize_panel/print_template)
File: `wp-includes/class-wp-customize-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-panel.php/)
```
protected function content_template() {
?>
<li class="panel-meta customize-info accordion-section <# if ( ! data.description ) { #> cannot-expand<# } #>">
<button class="customize-panel-back" tabindex="-1"><span class="screen-reader-text"><?php _e( 'Back' ); ?></span></button>
<div class="accordion-section-title">
<span class="preview-notice">
<?php
/* translators: %s: The site/panel title in the Customizer. */
printf( __( 'You are customizing %s' ), '<strong class="panel-title">{{ data.title }}</strong>' );
?>
</span>
<# if ( data.description ) { #>
<button type="button" class="customize-help-toggle dashicons dashicons-editor-help" aria-expanded="false"><span class="screen-reader-text"><?php _e( 'Help' ); ?></span></button>
<# } #>
</div>
<# if ( data.description ) { #>
<div class="description customize-panel-description">
{{{ data.description }}}
</div>
<# } #>
<div class="customize-control-notifications-container"></div>
</li>
<?php
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Panel::print\_template()](print_template) wp-includes/class-wp-customize-panel.php | Render the panel’s JS templates. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Panel::get_content(): string WP\_Customize\_Panel::get\_content(): string
============================================
Get the panel’s content template for insertion into the Customizer pane.
string Content for the panel.
File: `wp-includes/class-wp-customize-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-panel.php/)
```
final public function get_content() {
ob_start();
$this->maybe_render();
return trim( ob_get_clean() );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Panel::maybe\_render()](maybe_render) wp-includes/class-wp-customize-panel.php | Check capabilities and render the panel. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Panel::json()](json) wp-includes/class-wp-customize-panel.php | Gather the parameters passed to client JavaScript via JSON. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Panel::json(): array WP\_Customize\_Panel::json(): array
===================================
Gather the parameters passed to client JavaScript via JSON.
array The array to be exported to the client as JSON.
File: `wp-includes/class-wp-customize-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-panel.php/)
```
public function json() {
$array = wp_array_slice_assoc( (array) $this, array( 'id', 'description', 'priority', 'type' ) );
$array['title'] = html_entity_decode( $this->title, ENT_QUOTES, get_bloginfo( 'charset' ) );
$array['content'] = $this->get_content();
$array['active'] = $this->active();
$array['instanceNumber'] = $this->instance_number;
$array['autoExpandSoleSection'] = $this->auto_expand_sole_section;
return $array;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Panel::get\_content()](get_content) wp-includes/class-wp-customize-panel.php | Get the panel’s content template for insertion into the Customizer pane. |
| [WP\_Customize\_Panel::active()](active) wp-includes/class-wp-customize-panel.php | Check whether panel is active to current Customizer preview. |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Panel::active_callback(): bool WP\_Customize\_Panel::active\_callback(): bool
==============================================
Default callback used when invoking [WP\_Customize\_Panel::active()](active).
Subclasses can override this with their specific logic, or they may provide an ‘active\_callback’ argument to the constructor.
bool Always true.
File: `wp-includes/class-wp-customize-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-panel.php/)
```
public function active_callback() {
return true;
}
```
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Panel::render_template() WP\_Customize\_Panel::render\_template()
========================================
An Underscore (JS) template for rendering this panel’s container.
Class variables for this panel class are available in the `data` JS object; export custom variables by overriding [WP\_Customize\_Panel::json()](json).
* [WP\_Customize\_Panel::print\_template()](../wp_customize_panel/print_template)
File: `wp-includes/class-wp-customize-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-panel.php/)
```
protected function render_template() {
?>
<li id="accordion-panel-{{ data.id }}" class="accordion-section control-section control-panel control-panel-{{ data.type }}">
<h3 class="accordion-section-title" tabindex="0">
{{ data.title }}
<span class="screen-reader-text"><?php _e( 'Press return or enter to open this panel' ); ?></span>
</h3>
<ul class="accordion-sub-container control-panel-content"></ul>
</li>
<?php
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Panel::print\_template()](print_template) wp-includes/class-wp-customize-panel.php | Render the panel’s JS templates. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Panel::active(): bool WP\_Customize\_Panel::active(): bool
====================================
Check whether panel is active to current Customizer preview.
bool Whether the panel is active to the current preview.
File: `wp-includes/class-wp-customize-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-panel.php/)
```
final public function active() {
$panel = $this;
$active = call_user_func( $this->active_callback, $this );
/**
* Filters response of WP_Customize_Panel::active().
*
* @since 4.1.0
*
* @param bool $active Whether the Customizer panel is active.
* @param WP_Customize_Panel $panel WP_Customize_Panel instance.
*/
$active = apply_filters( 'customize_panel_active', $active, $panel );
return $active;
}
```
[apply\_filters( 'customize\_panel\_active', bool $active, WP\_Customize\_Panel $panel )](../../hooks/customize_panel_active)
Filters response of [WP\_Customize\_Panel::active()](active).
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Panel::json()](json) wp-includes/class-wp-customize-panel.php | Gather the parameters passed to client JavaScript via JSON. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Panel::print_template() WP\_Customize\_Panel::print\_template()
=======================================
Render the panel’s JS templates.
This function is only run for panel types that have been registered with [WP\_Customize\_Manager::register\_panel\_type()](../wp_customize_manager/register_panel_type).
* [WP\_Customize\_Manager::register\_panel\_type()](../wp_customize_manager/register_panel_type)
File: `wp-includes/class-wp-customize-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-panel.php/)
```
public function print_template() {
?>
<script type="text/html" id="tmpl-customize-panel-<?php echo esc_attr( $this->type ); ?>-content">
<?php $this->content_template(); ?>
</script>
<script type="text/html" id="tmpl-customize-panel-<?php echo esc_attr( $this->type ); ?>">
<?php $this->render_template(); ?>
</script>
<?php
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Panel::content\_template()](content_template) wp-includes/class-wp-customize-panel.php | An Underscore (JS) template for this panel’s content (but not its container). |
| [WP\_Customize\_Panel::render\_template()](render_template) wp-includes/class-wp-customize-panel.php | An Underscore (JS) template for rendering this panel’s container. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Panel::__construct( WP_Customize_Manager $manager, string $id, array $args = array() ) WP\_Customize\_Panel::\_\_construct( WP\_Customize\_Manager $manager, string $id, array $args = array() )
=========================================================================================================
Constructor.
Any supplied $args override class property defaults.
`$manager` [WP\_Customize\_Manager](../wp_customize_manager) Required Customizer bootstrap instance. `$id` string Required A specific ID for the panel. `$args` array Optional Array of properties for the new Panel object.
* `priority`intPriority of the panel, defining the display order of panels and sections. Default 160.
* `capability`stringCapability required for the panel.
Default `edit_theme_options`.
* `theme_supports`mixed[]Theme features required to support the panel.
* `title`stringTitle of the panel to show in UI.
* `description`stringDescription to show in the UI.
* `type`stringType of the panel.
* `active_callback`callableActive callback.
Default: `array()`
File: `wp-includes/class-wp-customize-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-panel.php/)
```
public function __construct( $manager, $id, $args = array() ) {
$keys = array_keys( get_object_vars( $this ) );
foreach ( $keys as $key ) {
if ( isset( $args[ $key ] ) ) {
$this->$key = $args[ $key ];
}
}
$this->manager = $manager;
$this->id = $id;
if ( empty( $this->active_callback ) ) {
$this->active_callback = array( $this, 'active_callback' );
}
self::$instance_count += 1;
$this->instance_number = self::$instance_count;
$this->sections = array(); // Users cannot customize the $sections array.
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::add\_panel()](../wp_customize_manager/add_panel) wp-includes/class-wp-customize-manager.php | Adds a customize panel. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Panel::render() WP\_Customize\_Panel::render()
==============================
Render the panel container, and then its contents (via `this->render_content()`) in a subclass.
Panel containers are now rendered in JS by default, see [WP\_Customize\_Panel::print\_template()](print_template).
File: `wp-includes/class-wp-customize-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-panel.php/)
```
protected function render() {}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Panel::maybe\_render()](maybe_render) wp-includes/class-wp-customize-panel.php | Check capabilities and render the panel. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Panel::check_capabilities(): bool WP\_Customize\_Panel::check\_capabilities(): bool
=================================================
Checks required user capabilities and whether the theme has the feature support required by the panel.
bool False if theme doesn't support the panel or the user doesn't have the capability.
File: `wp-includes/class-wp-customize-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-panel.php/)
```
public function check_capabilities() {
if ( $this->capability && ! current_user_can( $this->capability ) ) {
return false;
}
if ( $this->theme_supports && ! current_theme_supports( ... (array) $this->theme_supports ) ) {
return false;
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Panel::maybe\_render()](maybe_render) wp-includes/class-wp-customize-panel.php | Check capabilities and render the panel. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Method was marked non-final. |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Panel::render_content() WP\_Customize\_Panel::render\_content()
=======================================
Render the panel UI in a subclass.
Panel contents are now rendered in JS by default, see [WP\_Customize\_Panel::print\_template()](print_template).
File: `wp-includes/class-wp-customize-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-panel.php/)
```
protected function render_content() {}
```
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Panel::maybe_render() WP\_Customize\_Panel::maybe\_render()
=====================================
Check capabilities and render the panel.
File: `wp-includes/class-wp-customize-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-panel.php/)
```
final public function maybe_render() {
if ( ! $this->check_capabilities() ) {
return;
}
/**
* Fires before rendering a Customizer panel.
*
* @since 4.0.0
*
* @param WP_Customize_Panel $panel WP_Customize_Panel instance.
*/
do_action( 'customize_render_panel', $this );
/**
* Fires before rendering a specific Customizer panel.
*
* The dynamic portion of the hook name, `$this->id`, refers to
* the ID of the specific Customizer panel to be rendered.
*
* @since 4.0.0
*/
do_action( "customize_render_panel_{$this->id}" );
$this->render();
}
```
[do\_action( 'customize\_render\_panel', WP\_Customize\_Panel $panel )](../../hooks/customize_render_panel)
Fires before rendering a Customizer panel.
[do\_action( "customize\_render\_panel\_{$this->id}" )](../../hooks/customize_render_panel_this-id)
Fires before rendering a specific Customizer panel.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Panel::render()](render) wp-includes/class-wp-customize-panel.php | Render the panel container, and then its contents (via `this->render_content()`) in a subclass. |
| [WP\_Customize\_Panel::check\_capabilities()](check_capabilities) wp-includes/class-wp-customize-panel.php | Checks required user capabilities and whether the theme has the feature support required by the panel. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Panel::get\_content()](get_content) wp-includes/class-wp-customize-panel.php | Get the panel’s content template for insertion into the Customizer pane. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_REST_Menus_Controller::prepare_item_for_response( WP_Term $term, WP_REST_Request $request ): WP_REST_Response WP\_REST\_Menus\_Controller::prepare\_item\_for\_response( WP\_Term $term, WP\_REST\_Request $request ): WP\_REST\_Response
===========================================================================================================================
Prepares a single term output for response.
`$term` [WP\_Term](../wp_term) Required Term object. `$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. [WP\_REST\_Response](../wp_rest_response) Response object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
public function prepare_item_for_response( $term, $request ) {
$nav_menu = wp_get_nav_menu_object( $term );
$response = parent::prepare_item_for_response( $nav_menu, $request );
$fields = $this->get_fields_for_response( $request );
$data = $response->get_data();
if ( rest_is_field_included( 'locations', $fields ) ) {
$data['locations'] = $this->get_menu_locations( $nav_menu->term_id );
}
if ( rest_is_field_included( 'auto_add', $fields ) ) {
$data['auto_add'] = $this->get_menu_auto_add( $nav_menu->term_id );
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
$response = rest_ensure_response( $data );
if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
$response->add_links( $this->prepare_links( $term ) );
}
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
return apply_filters( "rest_prepare_{$this->taxonomy}", $response, $term, $request );
}
```
[apply\_filters( "rest\_prepare\_{$this->taxonomy}", WP\_REST\_Response $response, WP\_Term $item, WP\_REST\_Request $request )](../../hooks/rest_prepare_this-taxonomy)
Filters the term data for a REST API response.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::get\_menu\_locations()](get_menu_locations) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Returns the names of the locations assigned to the menu. |
| [WP\_REST\_Menus\_Controller::get\_menu\_auto\_add()](get_menu_auto_add) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Returns the value of a menu’s auto\_add setting. |
| [WP\_REST\_Menus\_Controller::prepare\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Prepares links for the request. |
| [rest\_is\_field\_included()](../../functions/rest_is_field_included) wp-includes/rest-api.php | Given an array of fields to include in a response, some of which may be `nested.fields`, determine whether the provided field should be included in the response body. |
| [WP\_REST\_Terms\_Controller::prepare\_item\_for\_response()](../wp_rest_terms_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares a single term output for response. |
| [wp\_get\_nav\_menu\_object()](../../functions/wp_get_nav_menu_object) wp-includes/nav-menu.php | Returns a navigation menu object. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Creates a single term in a taxonomy. |
| [WP\_REST\_Menus\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Updates a single term from a taxonomy. |
| [WP\_REST\_Menus\_Controller::delete\_item()](delete_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Deletes a single term from a taxonomy. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Menus_Controller::prepare_links( WP_Term $term ): array WP\_REST\_Menus\_Controller::prepare\_links( WP\_Term $term ): array
====================================================================
Prepares links for the request.
`$term` [WP\_Term](../wp_term) Required Term object. array Links for the given term.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
protected function prepare_links( $term ) {
$links = parent::prepare_links( $term );
$locations = $this->get_menu_locations( $term->term_id );
foreach ( $locations as $location ) {
$url = rest_url( sprintf( 'wp/v2/menu-locations/%s', $location ) );
$links['https://api.w.org/menu-location'][] = array(
'href' => $url,
'embeddable' => true,
);
}
return $links;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::get\_menu\_locations()](get_menu_locations) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Returns the names of the locations assigned to the menu. |
| [WP\_REST\_Terms\_Controller::prepare\_links()](../wp_rest_terms_controller/prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares links for the request. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Prepares a single term output for response. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menus_Controller::get_term( int $id ): WP_Term|WP_Error WP\_REST\_Menus\_Controller::get\_term( int $id ): WP\_Term|WP\_Error
=====================================================================
Gets the term, if the ID is valid.
`$id` int Required Supplied ID. [WP\_Term](../wp_term)|[WP\_Error](../wp_error) Term object if ID is valid, [WP\_Error](../wp_error) otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
protected function get_term( $id ) {
$term = parent::get_term( $id );
if ( is_wp_error( $term ) ) {
return $term;
}
$nav_term = wp_get_nav_menu_object( $term );
$nav_term->auto_add = $this->get_menu_auto_add( $nav_term->term_id );
return $nav_term;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::get\_menu\_auto\_add()](get_menu_auto_add) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Returns the value of a menu’s auto\_add setting. |
| [WP\_REST\_Terms\_Controller::get\_term()](../wp_rest_terms_controller/get_term) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Get the term, if the ID is valid. |
| [wp\_get\_nav\_menu\_object()](../../functions/wp_get_nav_menu_object) wp-includes/nav-menu.php | Returns a navigation menu object. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Creates a single term in a taxonomy. |
| [WP\_REST\_Menus\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Updates a single term from a taxonomy. |
| [WP\_REST\_Menus\_Controller::delete\_item()](delete_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Deletes a single term from a taxonomy. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menus_Controller::get_menu_auto_add( int $menu_id ): bool WP\_REST\_Menus\_Controller::get\_menu\_auto\_add( int $menu\_id ): bool
========================================================================
Returns the value of a menu’s auto\_add setting.
`$menu_id` int Required The menu id to query. bool The value of auto\_add.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
protected function get_menu_auto_add( $menu_id ) {
$nav_menu_option = (array) get_option( 'nav_menu_options', array( 'auto_add' => array() ) );
return in_array( $menu_id, $nav_menu_option['auto_add'], true );
}
```
| Uses | Description |
| --- | --- |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::get\_term()](get_term) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Gets the term, if the ID is valid. |
| [WP\_REST\_Menus\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Prepares a single term output for response. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menus_Controller::create_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Menus\_Controller::create\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=====================================================================================================
Creates a single term in a taxonomy.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
public function create_item( $request ) {
if ( isset( $request['parent'] ) ) {
if ( ! is_taxonomy_hierarchical( $this->taxonomy ) ) {
return new WP_Error( 'rest_taxonomy_not_hierarchical', __( 'Cannot set parent term, taxonomy is not hierarchical.' ), array( 'status' => 400 ) );
}
$parent = wp_get_nav_menu_object( (int) $request['parent'] );
if ( ! $parent ) {
return new WP_Error( 'rest_term_invalid', __( 'Parent term does not exist.' ), array( 'status' => 400 ) );
}
}
$prepared_term = $this->prepare_item_for_database( $request );
$term = wp_update_nav_menu_object( 0, wp_slash( (array) $prepared_term ) );
if ( is_wp_error( $term ) ) {
/*
* If we're going to inform the client that the term already exists,
* give them the identifier for future use.
*/
if ( in_array( 'menu_exists', $term->get_error_codes(), true ) ) {
$existing_term = get_term_by( 'name', $prepared_term->{'menu-name'}, $this->taxonomy );
$term->add_data( $existing_term->term_id, 'menu_exists' );
$term->add_data(
array(
'status' => 400,
'term_id' => $existing_term->term_id,
)
);
} else {
$term->add_data( array( 'status' => 400 ) );
}
return $term;
}
$term = $this->get_term( $term );
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
do_action( "rest_insert_{$this->taxonomy}", $term, $request, true );
$schema = $this->get_item_schema();
if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
$meta_update = $this->meta->update_value( $request['meta'], $term->term_id );
if ( is_wp_error( $meta_update ) ) {
return $meta_update;
}
}
$locations_update = $this->handle_locations( $term->term_id, $request );
if ( is_wp_error( $locations_update ) ) {
return $locations_update;
}
$this->handle_auto_add( $term->term_id, $request );
$fields_update = $this->update_additional_fields_for_object( $term, $request );
if ( is_wp_error( $fields_update ) ) {
return $fields_update;
}
$request->set_param( 'context', 'view' );
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
do_action( "rest_after_insert_{$this->taxonomy}", $term, $request, true );
$response = $this->prepare_item_for_response( $term, $request );
$response = rest_ensure_response( $response );
$response->set_status( 201 );
$response->header( 'Location', rest_url( $this->namespace . '/' . $this->rest_base . '/' . $term->term_id ) );
return $response;
}
```
[do\_action( "rest\_after\_insert\_{$this->taxonomy}", WP\_Term $term, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_after_insert_this-taxonomy)
Fires after a single term is completely created or updated via the REST API.
[do\_action( "rest\_insert\_{$this->taxonomy}", WP\_Term $term, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_insert_this-taxonomy)
Fires after a single term is created or updated via the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Prepares a single term for create or update. |
| [is\_taxonomy\_hierarchical()](../../functions/is_taxonomy_hierarchical) wp-includes/taxonomy.php | Determines whether the taxonomy object is hierarchical. |
| [WP\_REST\_Menus\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Retrieves the term’s schema, conforming to JSON Schema. |
| [WP\_REST\_Menus\_Controller::handle\_locations()](handle_locations) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Updates the menu’s locations from a REST request. |
| [WP\_REST\_Menus\_Controller::handle\_auto\_add()](handle_auto_add) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Updates the menu’s auto add from a REST request. |
| [WP\_REST\_Menus\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Prepares a single term output for response. |
| [wp\_get\_nav\_menu\_object()](../../functions/wp_get_nav_menu_object) wp-includes/nav-menu.php | Returns a navigation menu object. |
| [WP\_REST\_Menus\_Controller::get\_term()](get_term) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Gets the term, if the ID is valid. |
| [wp\_update\_nav\_menu\_object()](../../functions/wp_update_nav_menu_object) wp-includes/nav-menu.php | Saves the properties of a menu or create a new menu with those properties. |
| [get\_term\_by()](../../functions/get_term_by) wp-includes/taxonomy.php | Gets all term data from database by term field and data. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menus_Controller::update_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Menus\_Controller::update\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=====================================================================================================
Updates a single term from a taxonomy.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
public function update_item( $request ) {
$term = $this->get_term( $request['id'] );
if ( is_wp_error( $term ) ) {
return $term;
}
if ( isset( $request['parent'] ) ) {
if ( ! is_taxonomy_hierarchical( $this->taxonomy ) ) {
return new WP_Error( 'rest_taxonomy_not_hierarchical', __( 'Cannot set parent term, taxonomy is not hierarchical.' ), array( 'status' => 400 ) );
}
$parent = get_term( (int) $request['parent'], $this->taxonomy );
if ( ! $parent ) {
return new WP_Error( 'rest_term_invalid', __( 'Parent term does not exist.' ), array( 'status' => 400 ) );
}
}
$prepared_term = $this->prepare_item_for_database( $request );
// Only update the term if we have something to update.
if ( ! empty( $prepared_term ) ) {
if ( ! isset( $prepared_term->{'menu-name'} ) ) {
// wp_update_nav_menu_object() requires that the menu-name is always passed.
$prepared_term->{'menu-name'} = $term->name;
}
$update = wp_update_nav_menu_object( $term->term_id, wp_slash( (array) $prepared_term ) );
if ( is_wp_error( $update ) ) {
return $update;
}
}
$term = get_term( $term->term_id, $this->taxonomy );
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
do_action( "rest_insert_{$this->taxonomy}", $term, $request, false );
$schema = $this->get_item_schema();
if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
$meta_update = $this->meta->update_value( $request['meta'], $term->term_id );
if ( is_wp_error( $meta_update ) ) {
return $meta_update;
}
}
$locations_update = $this->handle_locations( $term->term_id, $request );
if ( is_wp_error( $locations_update ) ) {
return $locations_update;
}
$this->handle_auto_add( $term->term_id, $request );
$fields_update = $this->update_additional_fields_for_object( $term, $request );
if ( is_wp_error( $fields_update ) ) {
return $fields_update;
}
$request->set_param( 'context', 'view' );
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
do_action( "rest_after_insert_{$this->taxonomy}", $term, $request, false );
$response = $this->prepare_item_for_response( $term, $request );
return rest_ensure_response( $response );
}
```
[do\_action( "rest\_after\_insert\_{$this->taxonomy}", WP\_Term $term, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_after_insert_this-taxonomy)
Fires after a single term is completely created or updated via the REST API.
[do\_action( "rest\_insert\_{$this->taxonomy}", WP\_Term $term, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_insert_this-taxonomy)
Fires after a single term is created or updated via the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::get\_term()](get_term) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Gets the term, if the ID is valid. |
| [WP\_REST\_Menus\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Prepares a single term for create or update. |
| [WP\_REST\_Menus\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Retrieves the term’s schema, conforming to JSON Schema. |
| [WP\_REST\_Menus\_Controller::handle\_locations()](handle_locations) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Updates the menu’s locations from a REST request. |
| [WP\_REST\_Menus\_Controller::handle\_auto\_add()](handle_auto_add) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Updates the menu’s auto add from a REST request. |
| [WP\_REST\_Menus\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Prepares a single term output for response. |
| [is\_taxonomy\_hierarchical()](../../functions/is_taxonomy_hierarchical) wp-includes/taxonomy.php | Determines whether the taxonomy object is hierarchical. |
| [wp\_update\_nav\_menu\_object()](../../functions/wp_update_nav_menu_object) wp-includes/nav-menu.php | Saves the properties of a menu or create a new menu with those properties. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [get\_term()](../../functions/get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menus_Controller::handle_locations( int $menu_id, WP_REST_Request $request ): true|WP_Error WP\_REST\_Menus\_Controller::handle\_locations( int $menu\_id, WP\_REST\_Request $request ): true|WP\_Error
===========================================================================================================
Updates the menu’s locations from a REST request.
`$menu_id` int Required The menu id to update. `$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True on success, a [WP\_Error](../wp_error) on an error updating any of the locations.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
protected function handle_locations( $menu_id, $request ) {
if ( ! isset( $request['locations'] ) ) {
return true;
}
$menu_locations = get_registered_nav_menus();
$menu_locations = array_keys( $menu_locations );
$new_locations = array();
foreach ( $request['locations'] as $location ) {
if ( ! in_array( $location, $menu_locations, true ) ) {
return new WP_Error(
'rest_invalid_menu_location',
__( 'Invalid menu location.' ),
array(
'status' => 400,
'location' => $location,
)
);
}
$new_locations[ $location ] = $menu_id;
}
$assigned_menu = get_nav_menu_locations();
foreach ( $assigned_menu as $location => $term_id ) {
if ( $term_id === $menu_id ) {
unset( $assigned_menu[ $location ] );
}
}
$new_assignments = array_merge( $assigned_menu, $new_locations );
set_theme_mod( 'nav_menu_locations', $new_assignments );
return true;
}
```
| Uses | Description |
| --- | --- |
| [set\_theme\_mod()](../../functions/set_theme_mod) wp-includes/theme.php | Updates theme modification value for the active theme. |
| [get\_registered\_nav\_menus()](../../functions/get_registered_nav_menus) wp-includes/nav-menu.php | Retrieves all registered navigation menu locations in a theme. |
| [get\_nav\_menu\_locations()](../../functions/get_nav_menu_locations) wp-includes/nav-menu.php | Retrieves all registered navigation menu locations and the menus assigned to them. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Creates a single term in a taxonomy. |
| [WP\_REST\_Menus\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Updates a single term from a taxonomy. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Menus_Controller::check_has_read_only_access( WP_REST_Request $request ): bool|WP_Error WP\_REST\_Menus\_Controller::check\_has\_read\_only\_access( WP\_REST\_Request $request ): bool|WP\_Error
=========================================================================================================
Checks whether the current user has read permission for the endpoint.
This allows for any user that can `edit_theme_options` or edit any REST API available post type.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. bool|[WP\_Error](../wp_error) Whether the current user has permission.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
protected function check_has_read_only_access( $request ) {
if ( current_user_can( 'edit_theme_options' ) ) {
return true;
}
if ( current_user_can( 'edit_posts' ) ) {
return true;
}
foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
if ( current_user_can( $post_type->cap->edit_posts ) ) {
return true;
}
}
return new WP_Error(
'rest_cannot_view',
__( 'Sorry, you are not allowed to view menus.' ),
array( 'status' => rest_authorization_required_code() )
);
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::get\_items\_permissions\_check()](get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Checks if a request has access to read menus. |
| [WP\_REST\_Menus\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Checks if a request has access to read or edit the specified menu. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menus_Controller::prepare_item_for_database( WP_REST_Request $request ): object WP\_REST\_Menus\_Controller::prepare\_item\_for\_database( WP\_REST\_Request $request ): object
===============================================================================================
Prepares a single term for create or update.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. object Prepared term data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
public function prepare_item_for_database( $request ) {
$prepared_term = parent::prepare_item_for_database( $request );
$schema = $this->get_item_schema();
if ( isset( $request['name'] ) && ! empty( $schema['properties']['name'] ) ) {
$prepared_term->{'menu-name'} = $request['name'];
}
return $prepared_term;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Retrieves the term’s schema, conforming to JSON Schema. |
| [WP\_REST\_Terms\_Controller::prepare\_item\_for\_database()](../wp_rest_terms_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares a single term for create or update. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Creates a single term in a taxonomy. |
| [WP\_REST\_Menus\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Updates a single term from a taxonomy. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menus_Controller::get_items_permissions_check( WP_REST_Request $request ): bool|WP_Error WP\_REST\_Menus\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): bool|WP\_Error
=========================================================================================================
Checks if a request has access to read menus.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. bool|[WP\_Error](../wp_error) True if the request has read access, otherwise false or [WP\_Error](../wp_error) object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
public function get_items_permissions_check( $request ) {
$has_permission = parent::get_items_permissions_check( $request );
if ( true !== $has_permission ) {
return $has_permission;
}
return $this->check_has_read_only_access( $request );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::check\_has\_read\_only\_access()](check_has_read_only_access) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Checks whether the current user has read permission for the endpoint. |
| [WP\_REST\_Terms\_Controller::get\_items\_permissions\_check()](../wp_rest_terms_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if a request has access to read terms in the specified taxonomy. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menus_Controller::handle_auto_add( int $menu_id, WP_REST_Request $request ): bool WP\_REST\_Menus\_Controller::handle\_auto\_add( int $menu\_id, WP\_REST\_Request $request ): bool
=================================================================================================
Updates the menu’s auto add from a REST request.
`$menu_id` int Required The menu id to update. `$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. bool True if the auto add setting was successfully updated.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
protected function handle_auto_add( $menu_id, $request ) {
if ( ! isset( $request['auto_add'] ) ) {
return true;
}
$nav_menu_option = (array) get_option( 'nav_menu_options', array( 'auto_add' => array() ) );
if ( ! isset( $nav_menu_option['auto_add'] ) ) {
$nav_menu_option['auto_add'] = array();
}
$auto_add = $request['auto_add'];
$i = array_search( $menu_id, $nav_menu_option['auto_add'], true );
if ( $auto_add && false === $i ) {
$nav_menu_option['auto_add'][] = $menu_id;
} elseif ( ! $auto_add && false !== $i ) {
array_splice( $nav_menu_option['auto_add'], $i, 1 );
}
$update = update_option( 'nav_menu_options', $nav_menu_option );
/** This action is documented in wp-includes/nav-menu.php */
do_action( 'wp_update_nav_menu', $menu_id );
return $update;
}
```
[do\_action( 'wp\_update\_nav\_menu', int $menu\_id, array $menu\_data )](../../hooks/wp_update_nav_menu)
Fires after a navigation menu has been successfully updated.
| Uses | Description |
| --- | --- |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Creates a single term in a taxonomy. |
| [WP\_REST\_Menus\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Updates a single term from a taxonomy. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menus_Controller::get_menu_locations( int $menu_id ): string[] WP\_REST\_Menus\_Controller::get\_menu\_locations( int $menu\_id ): string[]
============================================================================
Returns the names of the locations assigned to the menu.
`$menu_id` int Required The menu id. string[] The locations assigned to the menu.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
protected function get_menu_locations( $menu_id ) {
$locations = get_nav_menu_locations();
$menu_locations = array();
foreach ( $locations as $location => $assigned_menu_id ) {
if ( $menu_id === $assigned_menu_id ) {
$menu_locations[] = $location;
}
}
return $menu_locations;
}
```
| Uses | Description |
| --- | --- |
| [get\_nav\_menu\_locations()](../../functions/get_nav_menu_locations) wp-includes/nav-menu.php | Retrieves all registered navigation menu locations and the menus assigned to them. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Prepares a single term output for response. |
| [WP\_REST\_Menus\_Controller::prepare\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Prepares links for the request. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menus_Controller::get_item_permissions_check( WP_REST_Request $request ): bool|WP_Error WP\_REST\_Menus\_Controller::get\_item\_permissions\_check( WP\_REST\_Request $request ): bool|WP\_Error
========================================================================================================
Checks if a request has access to read or edit the specified menu.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. bool|[WP\_Error](../wp_error) True if the request has read access for the item, otherwise false or [WP\_Error](../wp_error) object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
public function get_item_permissions_check( $request ) {
$has_permission = parent::get_item_permissions_check( $request );
if ( true !== $has_permission ) {
return $has_permission;
}
return $this->check_has_read_only_access( $request );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::check\_has\_read\_only\_access()](check_has_read_only_access) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Checks whether the current user has read permission for the endpoint. |
| [WP\_REST\_Terms\_Controller::get\_item\_permissions\_check()](../wp_rest_terms_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if a request has access to read or edit the specified term. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menus_Controller::delete_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Menus\_Controller::delete\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=====================================================================================================
Deletes a single term from a taxonomy.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
public function delete_item( $request ) {
$term = $this->get_term( $request['id'] );
if ( is_wp_error( $term ) ) {
return $term;
}
// We don't support trashing for terms.
if ( ! $request['force'] ) {
/* translators: %s: force=true */
return new WP_Error( 'rest_trash_not_supported', sprintf( __( "Menus do not support trashing. Set '%s' to delete." ), 'force=true' ), array( 'status' => 501 ) );
}
$request->set_param( 'context', 'view' );
$previous = $this->prepare_item_for_response( $term, $request );
$result = wp_delete_nav_menu( $term );
if ( ! $result || is_wp_error( $result ) ) {
return new WP_Error( 'rest_cannot_delete', __( 'The menu cannot be deleted.' ), array( 'status' => 500 ) );
}
$response = new WP_REST_Response();
$response->set_data(
array(
'deleted' => true,
'previous' => $previous->get_data(),
)
);
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
do_action( "rest_delete_{$this->taxonomy}", $term, $response, $request );
return $response;
}
```
[do\_action( "rest\_delete\_{$this->taxonomy}", WP\_Term $term, WP\_REST\_Response $response, WP\_REST\_Request $request )](../../hooks/rest_delete_this-taxonomy)
Fires after a single term is deleted via the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::get\_term()](get_term) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Gets the term, if the ID is valid. |
| [WP\_REST\_Menus\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Prepares a single term output for response. |
| [wp\_delete\_nav\_menu()](../../functions/wp_delete_nav_menu) wp-includes/nav-menu.php | Deletes a navigation menu. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menus_Controller::get_item_schema(): array WP\_REST\_Menus\_Controller::get\_item\_schema(): array
=======================================================
Retrieves the term’s schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
public function get_item_schema() {
$schema = parent::get_item_schema();
unset( $schema['properties']['count'], $schema['properties']['link'], $schema['properties']['taxonomy'] );
$schema['properties']['locations'] = array(
'description' => __( 'The locations assigned to the menu.' ),
'type' => 'array',
'items' => array(
'type' => 'string',
),
'context' => array( 'view', 'edit' ),
'arg_options' => array(
'validate_callback' => function ( $locations, $request, $param ) {
$valid = rest_validate_request_arg( $locations, $request, $param );
if ( true !== $valid ) {
return $valid;
}
$locations = rest_sanitize_request_arg( $locations, $request, $param );
foreach ( $locations as $location ) {
if ( ! array_key_exists( $location, get_registered_nav_menus() ) ) {
return new WP_Error(
'rest_invalid_menu_location',
__( 'Invalid menu location.' ),
array(
'location' => $location,
)
);
}
}
return true;
},
),
);
$schema['properties']['auto_add'] = array(
'description' => __( 'Whether to automatically add top level pages to this menu.' ),
'context' => array( 'view', 'edit' ),
'type' => 'boolean',
);
return $schema;
}
```
| Uses | Description |
| --- | --- |
| [rest\_validate\_request\_arg()](../../functions/rest_validate_request_arg) wp-includes/rest-api.php | Validate a request argument based on details registered to the route. |
| [rest\_sanitize\_request\_arg()](../../functions/rest_sanitize_request_arg) wp-includes/rest-api.php | Sanitize a request argument based on details registered to the route. |
| [WP\_REST\_Terms\_Controller::get\_item\_schema()](../wp_rest_terms_controller/get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Retrieves the term’s schema, conforming to JSON Schema. |
| [get\_registered\_nav\_menus()](../../functions/get_registered_nav_menus) wp-includes/nav-menu.php | Retrieves all registered navigation menu locations in a theme. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Prepares a single term for create or update. |
| [WP\_REST\_Menus\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Creates a single term in a taxonomy. |
| [WP\_REST\_Menus\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Updates a single term from a taxonomy. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Widget_Media_Video::get_instance_schema(): array WP\_Widget\_Media\_Video::get\_instance\_schema(): array
========================================================
Get schema for properties of a widget instance (item).
* [WP\_REST\_Controller::get\_item\_schema()](../wp_rest_controller/get_item_schema)
* [WP\_REST\_Controller::get\_additional\_fields()](../wp_rest_controller/get_additional_fields)
array Schema for properties.
File: `wp-includes/widgets/class-wp-widget-media-video.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-video.php/)
```
public function get_instance_schema() {
$schema = array(
'preload' => array(
'type' => 'string',
'enum' => array( 'none', 'auto', 'metadata' ),
'default' => 'metadata',
'description' => __( 'Preload' ),
'should_preview_update' => false,
),
'loop' => array(
'type' => 'boolean',
'default' => false,
'description' => __( 'Loop' ),
'should_preview_update' => false,
),
'content' => array(
'type' => 'string',
'default' => '',
'sanitize_callback' => 'wp_kses_post',
'description' => __( 'Tracks (subtitles, captions, descriptions, chapters, or metadata)' ),
'should_preview_update' => false,
),
);
foreach ( wp_get_video_extensions() as $video_extension ) {
$schema[ $video_extension ] = array(
'type' => 'string',
'default' => '',
'format' => 'uri',
/* translators: %s: Video extension. */
'description' => sprintf( __( 'URL to the %s video source file' ), $video_extension ),
);
}
return array_merge( $schema, parent::get_instance_schema() );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Media::get\_instance\_schema()](../wp_widget_media/get_instance_schema) wp-includes/widgets/class-wp-widget-media.php | Get schema for properties of a widget instance (item). |
| [wp\_get\_video\_extensions()](../../functions/wp_get_video_extensions) wp-includes/media.php | Returns a filtered list of supported video formats. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Media\_Video::enqueue\_admin\_scripts()](enqueue_admin_scripts) wp-includes/widgets/class-wp-widget-media-video.php | Loads the required scripts and styles for the widget control. |
| [WP\_Widget\_Media\_Video::render\_media()](render_media) wp-includes/widgets/class-wp-widget-media-video.php | Render the media on the frontend. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Widget_Media_Video::enqueue_admin_scripts() WP\_Widget\_Media\_Video::enqueue\_admin\_scripts()
===================================================
Loads the required scripts and styles for the widget control.
File: `wp-includes/widgets/class-wp-widget-media-video.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-video.php/)
```
public function enqueue_admin_scripts() {
parent::enqueue_admin_scripts();
$handle = 'media-video-widget';
wp_enqueue_script( $handle );
$exported_schema = array();
foreach ( $this->get_instance_schema() as $field => $field_schema ) {
$exported_schema[ $field ] = wp_array_slice_assoc( $field_schema, array( 'type', 'default', 'enum', 'minimum', 'format', 'media_prop', 'should_preview_update' ) );
}
wp_add_inline_script(
$handle,
sprintf(
'wp.mediaWidgets.modelConstructors[ %s ].prototype.schema = %s;',
wp_json_encode( $this->id_base ),
wp_json_encode( $exported_schema )
)
);
wp_add_inline_script(
$handle,
sprintf(
'
wp.mediaWidgets.controlConstructors[ %1$s ].prototype.mime_type = %2$s;
wp.mediaWidgets.controlConstructors[ %1$s ].prototype.l10n = _.extend( {}, wp.mediaWidgets.controlConstructors[ %1$s ].prototype.l10n, %3$s );
',
wp_json_encode( $this->id_base ),
wp_json_encode( $this->widget_options['mime_type'] ),
wp_json_encode( $this->l10n )
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Media\_Video::get\_instance\_schema()](get_instance_schema) wp-includes/widgets/class-wp-widget-media-video.php | Get schema for properties of a widget instance (item). |
| [WP\_Widget\_Media::enqueue\_admin\_scripts()](../wp_widget_media/enqueue_admin_scripts) wp-includes/widgets/class-wp-widget-media.php | Loads the required scripts and styles for the widget control. |
| [wp\_add\_inline\_script()](../../functions/wp_add_inline_script) wp-includes/functions.wp-scripts.php | Adds extra code to a registered script. |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media_Video::render_media( array $instance ) WP\_Widget\_Media\_Video::render\_media( array $instance )
==========================================================
Render the media on the frontend.
`$instance` array Required Widget instance props. File: `wp-includes/widgets/class-wp-widget-media-video.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-video.php/)
```
public function render_media( $instance ) {
$instance = array_merge( wp_list_pluck( $this->get_instance_schema(), 'default' ), $instance );
$attachment = null;
if ( $this->is_attachment_with_mime_type( $instance['attachment_id'], $this->widget_options['mime_type'] ) ) {
$attachment = get_post( $instance['attachment_id'] );
}
$src = $instance['url'];
if ( $attachment ) {
$src = wp_get_attachment_url( $attachment->ID );
}
if ( empty( $src ) ) {
return;
}
$youtube_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
$vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
if ( $attachment || preg_match( $youtube_pattern, $src ) || preg_match( $vimeo_pattern, $src ) ) {
add_filter( 'wp_video_shortcode', array( $this, 'inject_video_max_width_style' ) );
echo wp_video_shortcode(
array_merge(
$instance,
compact( 'src' )
),
$instance['content']
);
remove_filter( 'wp_video_shortcode', array( $this, 'inject_video_max_width_style' ) );
} else {
echo $this->inject_video_max_width_style( wp_oembed_get( $src ) );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Media\_Video::get\_instance\_schema()](get_instance_schema) wp-includes/widgets/class-wp-widget-media-video.php | Get schema for properties of a widget instance (item). |
| [WP\_Widget\_Media\_Video::inject\_video\_max\_width\_style()](inject_video_max_width_style) wp-includes/widgets/class-wp-widget-media-video.php | Inject max-width and remove height for videos too constrained to fit inside sidebars on frontend. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| [wp\_oembed\_get()](../../functions/wp_oembed_get) wp-includes/embed.php | Attempts to fetch the embed HTML for a provided URL using oEmbed. |
| [wp\_video\_shortcode()](../../functions/wp_video_shortcode) wp-includes/media.php | Builds the Video shortcode output. |
| [wp\_get\_attachment\_url()](../../functions/wp_get_attachment_url) wp-includes/post.php | Retrieves the URL for an attachment. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media_Video::render_control_template_scripts() WP\_Widget\_Media\_Video::render\_control\_template\_scripts()
==============================================================
Render form template scripts.
File: `wp-includes/widgets/class-wp-widget-media-video.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-video.php/)
```
public function render_control_template_scripts() {
parent::render_control_template_scripts()
?>
<script type="text/html" id="tmpl-wp-media-widget-video-preview">
<# if ( data.error && 'missing_attachment' === data.error ) { #>
<div class="notice notice-error notice-alt notice-missing-attachment">
<p><?php echo $this->l10n['missing_attachment']; ?></p>
</div>
<# } else if ( data.error && 'unsupported_file_type' === data.error ) { #>
<div class="notice notice-error notice-alt notice-missing-attachment">
<p><?php echo $this->l10n['unsupported_file_type']; ?></p>
</div>
<# } else if ( data.error ) { #>
<div class="notice notice-error notice-alt">
<p><?php _e( 'Unable to preview media due to an unknown error.' ); ?></p>
</div>
<# } else if ( data.is_oembed && data.model.poster ) { #>
<a href="{{ data.model.src }}" target="_blank" class="media-widget-video-link">
<img src="{{ data.model.poster }}" />
</a>
<# } else if ( data.is_oembed ) { #>
<a href="{{ data.model.src }}" target="_blank" class="media-widget-video-link no-poster">
<span class="dashicons dashicons-format-video"></span>
</a>
<# } else if ( data.model.src ) { #>
<?php wp_underscore_video_template(); ?>
<# } #>
</script>
<?php
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Media::render\_control\_template\_scripts()](../wp_widget_media/render_control_template_scripts) wp-includes/widgets/class-wp-widget-media.php | Render form template scripts. |
| [wp\_underscore\_video\_template()](../../functions/wp_underscore_video_template) wp-includes/media-template.php | Outputs the markup for a video tag to be used in an Underscore template when data.model is passed. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media_Video::__construct() WP\_Widget\_Media\_Video::\_\_construct()
=========================================
Constructor.
File: `wp-includes/widgets/class-wp-widget-media-video.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-video.php/)
```
public function __construct() {
parent::__construct(
'media_video',
__( 'Video' ),
array(
'description' => __( 'Displays a video from the media library or from YouTube, Vimeo, or another provider.' ),
'mime_type' => 'video',
)
);
$this->l10n = array_merge(
$this->l10n,
array(
'no_media_selected' => __( 'No video selected' ),
'add_media' => _x( 'Add Video', 'label for button in the video widget' ),
'replace_media' => _x( 'Replace Video', 'label for button in the video widget; should preferably not be longer than ~13 characters long' ),
'edit_media' => _x( 'Edit Video', 'label for button in the video widget; should preferably not be longer than ~13 characters long' ),
'missing_attachment' => sprintf(
/* translators: %s: URL to media library. */
__( 'That video cannot be found. Check your <a href="%s">media library</a> and make sure it was not deleted.' ),
esc_url( admin_url( 'upload.php' ) )
),
/* translators: %d: Widget count. */
'media_library_state_multi' => _n_noop( 'Video Widget (%d)', 'Video Widget (%d)' ),
'media_library_state_single' => __( 'Video Widget' ),
/* translators: %s: A list of valid video file extensions. */
'unsupported_file_type' => sprintf( __( 'Sorry, the video at the supplied URL cannot be loaded. Please check that the URL is for a supported video file (%s) or stream (e.g. YouTube and Vimeo).' ), '<code>.' . implode( '</code>, <code>.', wp_get_video_extensions() ) . '</code>' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Media::\_\_construct()](../wp_widget_media/__construct) wp-includes/widgets/class-wp-widget-media.php | Constructor. |
| [\_n\_noop()](../../functions/_n_noop) wp-includes/l10n.php | Registers plural strings in POT file, but does not translate them. |
| [wp\_get\_video\_extensions()](../../functions/wp_get_video_extensions) wp-includes/media.php | Returns a filtered list of supported video formats. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media_Video::enqueue_preview_scripts() WP\_Widget\_Media\_Video::enqueue\_preview\_scripts()
=====================================================
Enqueue preview scripts.
These scripts normally are enqueued just-in-time when a video shortcode is used.
In the customizer, however, widgets can be dynamically added and rendered via selective refresh, and so it is important to unconditionally enqueue them in case a widget does get added.
File: `wp-includes/widgets/class-wp-widget-media-video.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-video.php/)
```
public function enqueue_preview_scripts() {
/** This filter is documented in wp-includes/media.php */
if ( 'mediaelement' === apply_filters( 'wp_video_shortcode_library', 'mediaelement' ) ) {
wp_enqueue_style( 'wp-mediaelement' );
wp_enqueue_script( 'mediaelement-vimeo' );
wp_enqueue_script( 'wp-mediaelement' );
}
}
```
[apply\_filters( 'wp\_video\_shortcode\_library', string $library )](../../hooks/wp_video_shortcode_library)
Filters the media library used for the video shortcode.
| Uses | Description |
| --- | --- |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [wp\_enqueue\_style()](../../functions/wp_enqueue_style) wp-includes/functions.wp-styles.php | Enqueue a CSS stylesheet. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media_Video::inject_video_max_width_style( string $html ): string WP\_Widget\_Media\_Video::inject\_video\_max\_width\_style( string $html ): string
==================================================================================
Inject max-width and remove height for videos too constrained to fit inside sidebars on frontend.
`$html` string Required Video shortcode HTML output. string HTML Output.
File: `wp-includes/widgets/class-wp-widget-media-video.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-video.php/)
```
public function inject_video_max_width_style( $html ) {
$html = preg_replace( '/\sheight="\d+"/', '', $html );
$html = preg_replace( '/\swidth="\d+"/', '', $html );
$html = preg_replace( '/(?<=width:)\s*\d+px(?=;?)/', '100%', $html );
return $html;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Media\_Video::render\_media()](render_media) wp-includes/widgets/class-wp-widget-media-video.php | Render the media on the frontend. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_HTTP_Requests_Hooks::dispatch( string $hook, array $parameters = array() ): bool WP\_HTTP\_Requests\_Hooks::dispatch( string $hook, array $parameters = array() ): bool
======================================================================================
Dispatch a Requests hook to a native WordPress action.
`$hook` string Required Hook name. `$parameters` array Optional Parameters to pass to callbacks. Default: `array()`
bool True if hooks were run, false if nothing was hooked.
File: `wp-includes/class-wp-http-requests-hooks.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-hooks.php/)
```
public function dispatch( $hook, $parameters = array() ) {
$result = parent::dispatch( $hook, $parameters );
// Handle back-compat actions.
switch ( $hook ) {
case 'curl.before_send':
/** This action is documented in wp-includes/class-wp-http-curl.php */
do_action_ref_array( 'http_api_curl', array( &$parameters[0], $this->request, $this->url ) );
break;
}
/**
* Transforms a native Request hook to a WordPress action.
*
* This action maps Requests internal hook to a native WordPress action.
*
* @see https://github.com/WordPress/Requests/blob/master/docs/hooks.md
*
* @since 4.7.0
*
* @param array $parameters Parameters from Requests internal hook.
* @param array $request Request data in WP_Http format.
* @param string $url URL to request.
*/
do_action_ref_array( "requests-{$hook}", $parameters, $this->request, $this->url ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
return $result;
}
```
[do\_action\_ref\_array( 'http\_api\_curl', resource $handle, array $parsed\_args, string $url )](../../hooks/http_api_curl)
Fires before the cURL request is executed.
[do\_action\_ref\_array( "requests-{$hook}", array $parameters, array $request, string $url )](../../hooks/requests-hook)
Transforms a native Request hook to a WordPress action.
| Uses | Description |
| --- | --- |
| [Requests\_Hooks::dispatch()](../requests_hooks/dispatch) wp-includes/Requests/Hooks.php | Dispatch a message |
| [do\_action\_ref\_array()](../../functions/do_action_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook, specifying arguments in an array. |
wordpress WP_HTTP_Requests_Hooks::__construct( string $url, array $request ) WP\_HTTP\_Requests\_Hooks::\_\_construct( string $url, array $request )
=======================================================================
Constructor.
`$url` string Required URL to request. `$request` array Required Request data in [WP\_Http](../wp_http) format. File: `wp-includes/class-wp-http-requests-hooks.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-hooks.php/)
```
public function __construct( $url, $request ) {
$this->url = $url;
$this->request = $request;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Http::request()](../wp_http/request) wp-includes/class-wp-http.php | Send an HTTP request to a URI. |
wordpress WP_Widget_Area_Customize_Control::to_json() WP\_Widget\_Area\_Customize\_Control::to\_json()
================================================
Refreshes the parameters passed to the JavaScript via JSON.
File: `wp-includes/customize/class-wp-widget-area-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-widget-area-customize-control.php/)
```
public function to_json() {
parent::to_json();
$exported_properties = array( 'sidebar_id' );
foreach ( $exported_properties as $key ) {
$this->json[ $key ] = $this->$key;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::to\_json()](../wp_customize_control/to_json) wp-includes/class-wp-customize-control.php | Refresh the parameters passed to the JavaScript via JSON. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Widget_Area_Customize_Control::render_content() WP\_Widget\_Area\_Customize\_Control::render\_content()
=======================================================
Renders the control’s content.
File: `wp-includes/customize/class-wp-widget-area-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-widget-area-customize-control.php/)
```
public function render_content() {
$id = 'reorder-widgets-desc-' . str_replace( array( '[', ']' ), array( '-', '' ), $this->id );
?>
<button type="button" class="button add-new-widget" aria-expanded="false" aria-controls="available-widgets">
<?php _e( 'Add a Widget' ); ?>
</button>
<button type="button" class="button-link reorder-toggle" aria-label="<?php esc_attr_e( 'Reorder widgets' ); ?>" aria-describedby="<?php echo esc_attr( $id ); ?>">
<span class="reorder"><?php _e( 'Reorder' ); ?></span>
<span class="reorder-done"><?php _e( 'Done' ); ?></span>
</button>
<p class="screen-reader-text" id="<?php echo esc_attr( $id ); ?>"><?php _e( 'When in reorder mode, additional controls to reorder widgets will be available in the widgets list above.' ); ?></p>
<?php
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr\_e()](../../functions/esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress IXR_Value::calculateType() IXR\_Value::calculateType()
===========================
File: `wp-includes/IXR/class-IXR-value.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-value.php/)
```
function calculateType()
{
if ($this->data === true || $this->data === false) {
return 'boolean';
}
if (is_integer($this->data)) {
return 'int';
}
if (is_double($this->data)) {
return 'double';
}
// Deal with IXR object types base64 and date
if (is_object($this->data) && is_a($this->data, 'IXR_Date')) {
return 'date';
}
if (is_object($this->data) && is_a($this->data, 'IXR_Base64')) {
return 'base64';
}
// If it is a normal PHP object convert it in to a struct
if (is_object($this->data)) {
$this->data = get_object_vars($this->data);
return 'struct';
}
if (!is_array($this->data)) {
return 'string';
}
// We have an array - is it an array or a struct?
if ($this->isStruct($this->data)) {
return 'struct';
} else {
return 'array';
}
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Value::isStruct()](isstruct) wp-includes/IXR/class-IXR-value.php | Checks whether or not the supplied array is a struct or not |
| Used By | Description |
| --- | --- |
| [IXR\_Value::\_\_construct()](__construct) wp-includes/IXR/class-IXR-value.php | PHP5 constructor. |
| programming_docs |
wordpress IXR_Value::getXml() IXR\_Value::getXml()
====================
File: `wp-includes/IXR/class-IXR-value.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-value.php/)
```
function getXml()
{
// Return XML for this value
switch ($this->type) {
case 'boolean':
return '<boolean>'.(($this->data) ? '1' : '0').'</boolean>';
break;
case 'int':
return '<int>'.$this->data.'</int>';
break;
case 'double':
return '<double>'.$this->data.'</double>';
break;
case 'string':
return '<string>'.htmlspecialchars($this->data).'</string>';
break;
case 'array':
$return = '<array><data>'."\n";
foreach ($this->data as $item) {
$return .= ' <value>'.$item->getXml()."</value>\n";
}
$return .= '</data></array>';
return $return;
break;
case 'struct':
$return = '<struct>'."\n";
foreach ($this->data as $name => $value) {
$name = htmlspecialchars($name);
$return .= " <member><name>$name</name><value>";
$return .= $value->getXml()."</value></member>\n";
}
$return .= '</struct>';
return $return;
break;
case 'date':
case 'base64':
return $this->data->getXml();
break;
}
return false;
}
```
wordpress IXR_Value::IXR_Value( $data, $type = false ) IXR\_Value::IXR\_Value( $data, $type = false )
==============================================
PHP4 constructor.
File: `wp-includes/IXR/class-IXR-value.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-value.php/)
```
public function IXR_Value( $data, $type = false ) {
self::__construct( $data, $type );
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Value::\_\_construct()](__construct) wp-includes/IXR/class-IXR-value.php | PHP5 constructor. |
wordpress IXR_Value::__construct( $data, $type = false ) IXR\_Value::\_\_construct( $data, $type = false )
=================================================
PHP5 constructor.
File: `wp-includes/IXR/class-IXR-value.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-value.php/)
```
function __construct( $data, $type = false )
{
$this->data = $data;
if (!$type) {
$type = $this->calculateType();
}
$this->type = $type;
if ($type == 'struct') {
// Turn all the values in the array in to new IXR_Value objects
foreach ($this->data as $key => $value) {
$this->data[$key] = new IXR_Value($value);
}
}
if ($type == 'array') {
for ($i = 0, $j = count($this->data); $i < $j; $i++) {
$this->data[$i] = new IXR_Value($this->data[$i]);
}
}
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Value::calculateType()](calculatetype) wp-includes/IXR/class-IXR-value.php | |
| [IXR\_Value::\_\_construct()](__construct) wp-includes/IXR/class-IXR-value.php | PHP5 constructor. |
| Used By | Description |
| --- | --- |
| [IXR\_Server::serve()](../ixr_server/serve) wp-includes/IXR/class-IXR-server.php | |
| [IXR\_Request::\_\_construct()](../ixr_request/__construct) wp-includes/IXR/class-IXR-request.php | PHP5 constructor. |
| [IXR\_Value::\_\_construct()](__construct) wp-includes/IXR/class-IXR-value.php | PHP5 constructor. |
| [IXR\_Value::IXR\_Value()](ixr_value) wp-includes/IXR/class-IXR-value.php | PHP4 constructor. |
wordpress IXR_Value::isStruct( array $array ): bool IXR\_Value::isStruct( array $array ): bool
==========================================
Checks whether or not the supplied array is a struct or not
`$array` array Required bool
File: `wp-includes/IXR/class-IXR-value.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-value.php/)
```
function isStruct($array)
{
$expected = 0;
foreach ($array as $key => $value) {
if ((string)$key !== (string)$expected) {
return true;
}
$expected++;
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [IXR\_Value::calculateType()](calculatetype) wp-includes/IXR/class-IXR-value.php | |
wordpress Custom_Image_Header::ajax_header_crop() Custom\_Image\_Header::ajax\_header\_crop()
===========================================
Gets attachment uploaded by Media Manager, crops it, then saves it as a new object. Returns JSON-encoded object details.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function ajax_header_crop() {
check_ajax_referer( 'image_editor-' . $_POST['id'], 'nonce' );
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_send_json_error();
}
if ( ! current_theme_supports( 'custom-header', 'uploads' ) ) {
wp_send_json_error();
}
$crop_details = $_POST['cropDetails'];
$dimensions = $this->get_header_dimensions(
array(
'height' => $crop_details['height'],
'width' => $crop_details['width'],
)
);
$attachment_id = absint( $_POST['id'] );
$cropped = wp_crop_image(
$attachment_id,
(int) $crop_details['x1'],
(int) $crop_details['y1'],
(int) $crop_details['width'],
(int) $crop_details['height'],
(int) $dimensions['dst_width'],
(int) $dimensions['dst_height']
);
if ( ! $cropped || is_wp_error( $cropped ) ) {
wp_send_json_error( array( 'message' => __( 'Image could not be processed. Please go back and try again.' ) ) );
}
/** This filter is documented in wp-admin/includes/class-custom-image-header.php */
$cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication.
$attachment = $this->create_attachment_object( $cropped, $attachment_id );
$previous = $this->get_previous_crop( $attachment );
if ( $previous ) {
$attachment['ID'] = $previous;
} else {
unset( $attachment['ID'] );
}
$new_attachment_id = $this->insert_attachment( $attachment, $cropped );
$attachment['attachment_id'] = $new_attachment_id;
$attachment['url'] = wp_get_attachment_url( $new_attachment_id );
$attachment['width'] = $dimensions['dst_width'];
$attachment['height'] = $dimensions['dst_height'];
wp_send_json_success( $attachment );
}
```
[do\_action( 'wp\_create\_file\_in\_uploads', string $file, int $attachment\_id )](../../hooks/wp_create_file_in_uploads)
Fires after the header image is set or an error is returned.
| Uses | Description |
| --- | --- |
| [Custom\_Image\_Header::get\_previous\_crop()](get_previous_crop) wp-admin/includes/class-custom-image-header.php | Get the ID of a previous crop from the same base image. |
| [wp\_crop\_image()](../../functions/wp_crop_image) wp-admin/includes/image.php | Crops an image to a given size. |
| [Custom\_Image\_Header::get\_header\_dimensions()](get_header_dimensions) wp-admin/includes/class-custom-image-header.php | Calculate width and height based on what the currently selected theme supports. |
| [Custom\_Image\_Header::create\_attachment\_object()](create_attachment_object) wp-admin/includes/class-custom-image-header.php | Create an attachment ‘object’. |
| [Custom\_Image\_Header::insert\_attachment()](insert_attachment) wp-admin/includes/class-custom-image-header.php | Insert an attachment and its metadata. |
| [wp\_get\_attachment\_url()](../../functions/wp_get_attachment_url) wp-includes/post.php | Retrieves the URL for an attachment. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [check\_ajax\_referer()](../../functions/check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [wp\_send\_json\_error()](../../functions/wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [wp\_send\_json\_success()](../../functions/wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress Custom_Image_Header::finished() Custom\_Image\_Header::finished()
=================================
Display last step of custom header image page.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function finished() {
$this->updated = true;
$this->step_1();
}
```
| Uses | Description |
| --- | --- |
| [Custom\_Image\_Header::step\_1()](step_1) wp-admin/includes/class-custom-image-header.php | Display first step of custom header image page. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::step\_2()](step_2) wp-admin/includes/class-custom-image-header.php | Display second step of custom header image page. |
| [Custom\_Image\_Header::step\_3()](step_3) wp-admin/includes/class-custom-image-header.php | Display third step of custom header image page. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Custom_Image_Header::ajax_header_add() Custom\_Image\_Header::ajax\_header\_add()
==========================================
Given an attachment ID for a header image, updates its “last used” timestamp to now.
Triggered when the user tries adds a new header image from the Media Manager, even if s/he doesn’t save that change.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function ajax_header_add() {
check_ajax_referer( 'header-add', 'nonce' );
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_send_json_error();
}
$attachment_id = absint( $_POST['attachment_id'] );
if ( $attachment_id < 1 ) {
wp_send_json_error();
}
$key = '_wp_attachment_custom_header_last_used_' . get_stylesheet();
update_post_meta( $attachment_id, $key, time() );
update_post_meta( $attachment_id, '_wp_attachment_is_custom_header', get_stylesheet() );
wp_send_json_success();
}
```
| Uses | Description |
| --- | --- |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| [get\_stylesheet()](../../functions/get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [check\_ajax\_referer()](../../functions/check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [wp\_send\_json\_error()](../../functions/wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [wp\_send\_json\_success()](../../functions/wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress Custom_Image_Header::help() Custom\_Image\_Header::help()
=============================
Adds contextual help.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function help() {
get_current_screen()->add_help_tab(
array(
'id' => 'overview',
'title' => __( 'Overview' ),
'content' =>
'<p>' . __( 'This screen is used to customize the header section of your theme.' ) . '</p>' .
'<p>' . __( 'You can choose from the theme’s default header images, or use one of your own. You can also customize how your Site Title and Tagline are displayed.' ) . '<p>',
)
);
get_current_screen()->add_help_tab(
array(
'id' => 'set-header-image',
'title' => __( 'Header Image' ),
'content' =>
'<p>' . __( 'You can set a custom image header for your site. Simply upload the image and crop it, and the new header will go live immediately. Alternatively, you can use an image that has already been uploaded to your Media Library by clicking the “Choose Image” button.' ) . '</p>' .
'<p>' . __( 'Some themes come with additional header images bundled. If you see multiple images displayed, select the one you would like and click the “Save Changes” button.' ) . '</p>' .
'<p>' . __( 'If your theme has more than one default header image, or you have uploaded more than one custom header image, you have the option of having WordPress display a randomly different image on each page of your site. Click the “Random” radio button next to the Uploaded Images or Default Images section to enable this feature.' ) . '</p>' .
'<p>' . __( 'If you do not want a header image to be displayed on your site at all, click the “Remove Header Image” button at the bottom of the Header Image section of this page. If you want to re-enable the header image later, you just have to select one of the other image options and click “Save Changes”.' ) . '</p>',
)
);
get_current_screen()->add_help_tab(
array(
'id' => 'set-header-text',
'title' => __( 'Header Text' ),
'content' =>
'<p>' . sprintf(
/* translators: %s: URL to General Settings screen. */
__( 'For most themes, the header text is your Site Title and Tagline, as defined in the <a href="%s">General Settings</a> section.' ),
admin_url( 'options-general.php' )
) .
'</p>' .
'<p>' . __( 'In the Header Text section of this page, you can choose whether to display this text or hide it. You can also choose a color for the text by clicking the Select Color button and either typing in a legitimate HTML hex value, e.g. “#ff0000” for red, or by choosing a color using the color picker.' ) . '</p>' .
'<p>' . __( 'Do not forget to click “Save Changes” when you are done!' ) . '</p>',
)
);
get_current_screen()->set_help_sidebar(
'<p><strong>' . __( 'For more information:' ) . '</strong></p>' .
'<p>' . __( '<a href="https://codex.wordpress.org/Appearance_Header_Screen">Documentation on Custom Header</a>' ) . '</p>' .
'<p>' . __( '<a href="https://wordpress.org/support/">Support</a>' ) . '</p>'
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Screen::add\_help\_tab()](../wp_screen/add_help_tab) wp-admin/includes/class-wp-screen.php | Adds a help tab to the contextual help for the screen. |
| [WP\_Screen::set\_help\_sidebar()](../wp_screen/set_help_sidebar) wp-admin/includes/class-wp-screen.php | Adds a sidebar to the contextual help for the screen. |
| [get\_current\_screen()](../../functions/get_current_screen) wp-admin/includes/screen.php | Get the current screen object |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress Custom_Image_Header::get_uploaded_header_images(): array Custom\_Image\_Header::get\_uploaded\_header\_images(): array
=============================================================
Gets the previously uploaded header images.
array Uploaded header images.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function get_uploaded_header_images() {
$header_images = get_uploaded_header_images();
$timestamp_key = '_wp_attachment_custom_header_last_used_' . get_stylesheet();
$alt_text_key = '_wp_attachment_image_alt';
foreach ( $header_images as &$header_image ) {
$header_meta = get_post_meta( $header_image['attachment_id'] );
$header_image['timestamp'] = isset( $header_meta[ $timestamp_key ] ) ? $header_meta[ $timestamp_key ] : '';
$header_image['alt_text'] = isset( $header_meta[ $alt_text_key ] ) ? $header_meta[ $alt_text_key ] : '';
}
return $header_images;
}
```
| Uses | Description |
| --- | --- |
| [get\_uploaded\_header\_images()](../../functions/get_uploaded_header_images) wp-includes/theme.php | Gets the header images uploaded for the active theme. |
| [get\_stylesheet()](../../functions/get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [get\_post\_meta()](../../functions/get_post_meta) wp-includes/post.php | Retrieves a post meta field for the given post ID. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::get\_previous\_crop()](get_previous_crop) wp-admin/includes/class-custom-image-header.php | Get the ID of a previous crop from the same base image. |
| [WP\_Customize\_Header\_Image\_Control::prepare\_control()](../wp_customize_header_image_control/prepare_control) wp-includes/customize/class-wp-customize-header-image-control.php | |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress Custom_Image_Header::init() Custom\_Image\_Header::init()
=============================
Set up the hooks for the Custom Header admin page.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function init() {
$page = add_theme_page( __( 'Header' ), __( 'Header' ), 'edit_theme_options', 'custom-header', array( $this, 'admin_page' ) );
if ( ! $page ) {
return;
}
add_action( "admin_print_scripts-{$page}", array( $this, 'js_includes' ) );
add_action( "admin_print_styles-{$page}", array( $this, 'css_includes' ) );
add_action( "admin_head-{$page}", array( $this, 'help' ) );
add_action( "admin_head-{$page}", array( $this, 'take_action' ), 50 );
add_action( "admin_head-{$page}", array( $this, 'js' ), 50 );
if ( $this->admin_header_callback ) {
add_action( "admin_head-{$page}", $this->admin_header_callback, 51 );
}
}
```
| Uses | Description |
| --- | --- |
| [add\_theme\_page()](../../functions/add_theme_page) wp-admin/includes/plugin.php | Adds a submenu page to the Appearance main menu. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
| programming_docs |
wordpress Custom_Image_Header::js_1() Custom\_Image\_Header::js\_1()
==============================
Display JavaScript based on Step 1 and 3.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function js_1() {
$default_color = '';
if ( current_theme_supports( 'custom-header', 'default-text-color' ) ) {
$default_color = get_theme_support( 'custom-header', 'default-text-color' );
if ( $default_color && false === strpos( $default_color, '#' ) ) {
$default_color = '#' . $default_color;
}
}
?>
<script type="text/javascript">
(function($){
var default_color = '<?php echo esc_js( $default_color ); ?>',
header_text_fields;
function pickColor(color) {
$('#name').css('color', color);
$('#desc').css('color', color);
$('#text-color').val(color);
}
function toggle_text() {
var checked = $('#display-header-text').prop('checked'),
text_color;
header_text_fields.toggle( checked );
if ( ! checked )
return;
text_color = $('#text-color');
if ( '' === text_color.val().replace('#', '') ) {
text_color.val( default_color );
pickColor( default_color );
} else {
pickColor( text_color.val() );
}
}
$( function() {
var text_color = $('#text-color');
header_text_fields = $('.displaying-header-text');
text_color.wpColorPicker({
change: function( event, ui ) {
pickColor( text_color.wpColorPicker('color') );
},
clear: function() {
pickColor( '' );
}
});
$('#display-header-text').click( toggle_text );
<?php if ( ! display_header_text() ) : ?>
toggle_text();
<?php endif; ?>
} );
})(jQuery);
</script>
<?php
}
```
| Uses | Description |
| --- | --- |
| [display\_header\_text()](../../functions/display_header_text) wp-includes/theme.php | Whether to display the header text. |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [esc\_js()](../../functions/esc_js) wp-includes/formatting.php | Escapes single quotes, `"`, , `&`, and fixes line endings. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::js()](js) wp-admin/includes/class-custom-image-header.php | Execute JavaScript depending on step. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress Custom_Image_Header::step_1() Custom\_Image\_Header::step\_1()
================================
Display first step of custom header image page.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function step_1() {
$this->process_default_headers();
?>
<div class="wrap">
<h1><?php _e( 'Custom Header' ); ?></h1>
<?php if ( current_user_can( 'customize' ) ) { ?>
<div class="notice notice-info hide-if-no-customize">
<p>
<?php
printf(
/* translators: %s: URL to header image configuration in Customizer. */
__( 'You can now manage and live-preview Custom Header in the <a href="%s">Customizer</a>.' ),
admin_url( 'customize.php?autofocus[control]=header_image' )
);
?>
</p>
</div>
<?php } ?>
<?php if ( ! empty( $this->updated ) ) { ?>
<div id="message" class="updated">
<p>
<?php
/* translators: %s: Home URL. */
printf( __( 'Header updated. <a href="%s">Visit your site</a> to see how it looks.' ), esc_url( home_url( '/' ) ) );
?>
</p>
</div>
<?php } ?>
<h2><?php _e( 'Header Image' ); ?></h2>
<table class="form-table" role="presentation">
<tbody>
<?php if ( get_custom_header() || display_header_text() ) : ?>
<tr>
<th scope="row"><?php _e( 'Preview' ); ?></th>
<td>
<?php
if ( $this->admin_image_div_callback ) {
call_user_func( $this->admin_image_div_callback );
} else {
$custom_header = get_custom_header();
$header_image = get_header_image();
if ( $header_image ) {
$header_image_style = 'background-image:url(' . esc_url( $header_image ) . ');';
} else {
$header_image_style = '';
}
if ( $custom_header->width ) {
$header_image_style .= 'max-width:' . $custom_header->width . 'px;';
}
if ( $custom_header->height ) {
$header_image_style .= 'height:' . $custom_header->height . 'px;';
}
?>
<div id="headimg" style="<?php echo $header_image_style; ?>">
<?php
if ( display_header_text() ) {
$style = ' style="color:#' . get_header_textcolor() . ';"';
} else {
$style = ' style="display:none;"';
}
?>
<h1><a id="name" class="displaying-header-text" <?php echo $style; ?> onclick="return false;" href="<?php bloginfo( 'url' ); ?>" tabindex="-1"><?php bloginfo( 'name' ); ?></a></h1>
<div id="desc" class="displaying-header-text" <?php echo $style; ?>><?php bloginfo( 'description' ); ?></div>
</div>
<?php } ?>
</td>
</tr>
<?php endif; ?>
<?php if ( current_user_can( 'upload_files' ) && current_theme_supports( 'custom-header', 'uploads' ) ) : ?>
<tr>
<th scope="row"><?php _e( 'Select Image' ); ?></th>
<td>
<p><?php _e( 'You can select an image to be shown at the top of your site by uploading from your computer or choosing from your media library. After selecting an image you will be able to crop it.' ); ?><br />
<?php
if ( ! current_theme_supports( 'custom-header', 'flex-height' )
&& ! current_theme_supports( 'custom-header', 'flex-width' )
) {
printf(
/* translators: 1: Image width in pixels, 2: Image height in pixels. */
__( 'Images of exactly <strong>%1$d × %2$d pixels</strong> will be used as-is.' ) . '<br />',
get_theme_support( 'custom-header', 'width' ),
get_theme_support( 'custom-header', 'height' )
);
} elseif ( current_theme_supports( 'custom-header', 'flex-height' ) ) {
if ( ! current_theme_supports( 'custom-header', 'flex-width' ) ) {
printf(
/* translators: %s: Size in pixels. */
__( 'Images should be at least %s wide.' ) . ' ',
sprintf(
/* translators: %d: Custom header width. */
'<strong>' . __( '%d pixels' ) . '</strong>',
get_theme_support( 'custom-header', 'width' )
)
);
}
} elseif ( current_theme_supports( 'custom-header', 'flex-width' ) ) {
if ( ! current_theme_supports( 'custom-header', 'flex-height' ) ) {
printf(
/* translators: %s: Size in pixels. */
__( 'Images should be at least %s tall.' ) . ' ',
sprintf(
/* translators: %d: Custom header height. */
'<strong>' . __( '%d pixels' ) . '</strong>',
get_theme_support( 'custom-header', 'height' )
)
);
}
}
if ( current_theme_supports( 'custom-header', 'flex-height' )
|| current_theme_supports( 'custom-header', 'flex-width' )
) {
if ( current_theme_supports( 'custom-header', 'width' ) ) {
printf(
/* translators: %s: Size in pixels. */
__( 'Suggested width is %s.' ) . ' ',
sprintf(
/* translators: %d: Custom header width. */
'<strong>' . __( '%d pixels' ) . '</strong>',
get_theme_support( 'custom-header', 'width' )
)
);
}
if ( current_theme_supports( 'custom-header', 'height' ) ) {
printf(
/* translators: %s: Size in pixels. */
__( 'Suggested height is %s.' ) . ' ',
sprintf(
/* translators: %d: Custom header height. */
'<strong>' . __( '%d pixels' ) . '</strong>',
get_theme_support( 'custom-header', 'height' )
)
);
}
}
?>
</p>
<form enctype="multipart/form-data" id="upload-form" class="wp-upload-form" method="post" action="<?php echo esc_url( add_query_arg( 'step', 2 ) ); ?>">
<p>
<label for="upload"><?php _e( 'Choose an image from your computer:' ); ?></label><br />
<input type="file" id="upload" name="import" />
<input type="hidden" name="action" value="save" />
<?php wp_nonce_field( 'custom-header-upload', '_wpnonce-custom-header-upload' ); ?>
<?php submit_button( __( 'Upload' ), '', 'submit', false ); ?>
</p>
<?php
$modal_update_href = add_query_arg(
array(
'page' => 'custom-header',
'step' => 2,
'_wpnonce-custom-header-upload' => wp_create_nonce( 'custom-header-upload' ),
),
admin_url( 'themes.php' )
);
?>
<p>
<label for="choose-from-library-link"><?php _e( 'Or choose an image from your media library:' ); ?></label><br />
<button id="choose-from-library-link" class="button"
data-update-link="<?php echo esc_url( $modal_update_href ); ?>"
data-choose="<?php esc_attr_e( 'Choose a Custom Header' ); ?>"
data-update="<?php esc_attr_e( 'Set as header' ); ?>"><?php _e( 'Choose Image' ); ?></button>
</p>
</form>
</td>
</tr>
<?php endif; ?>
</tbody>
</table>
<form method="post" action="<?php echo esc_url( add_query_arg( 'step', 1 ) ); ?>">
<?php submit_button( null, 'screen-reader-text', 'save-header-options', false ); ?>
<table class="form-table" role="presentation">
<tbody>
<?php if ( get_uploaded_header_images() ) : ?>
<tr>
<th scope="row"><?php _e( 'Uploaded Images' ); ?></th>
<td>
<p><?php _e( 'You can choose one of your previously uploaded headers, or show a random one.' ); ?></p>
<?php
$this->show_header_selector( 'uploaded' );
?>
</td>
</tr>
<?php
endif;
if ( ! empty( $this->default_headers ) ) :
?>
<tr>
<th scope="row"><?php _e( 'Default Images' ); ?></th>
<td>
<?php if ( current_theme_supports( 'custom-header', 'uploads' ) ) : ?>
<p><?php _e( 'If you don‘t want to upload your own image, you can use one of these cool headers, or show a random one.' ); ?></p>
<?php else : ?>
<p><?php _e( 'You can use one of these cool headers or show a random one on each page.' ); ?></p>
<?php endif; ?>
<?php
$this->show_header_selector( 'default' );
?>
</td>
</tr>
<?php
endif;
if ( get_header_image() ) :
?>
<tr>
<th scope="row"><?php _e( 'Remove Image' ); ?></th>
<td>
<p><?php _e( 'This will remove the header image. You will not be able to restore any customizations.' ); ?></p>
<?php submit_button( __( 'Remove Header Image' ), '', 'removeheader', false ); ?>
</td>
</tr>
<?php
endif;
$default_image = sprintf(
get_theme_support( 'custom-header', 'default-image' ),
get_template_directory_uri(),
get_stylesheet_directory_uri()
);
if ( $default_image && get_header_image() !== $default_image ) :
?>
<tr>
<th scope="row"><?php _e( 'Reset Image' ); ?></th>
<td>
<p><?php _e( 'This will restore the original header image. You will not be able to restore any customizations.' ); ?></p>
<?php submit_button( __( 'Restore Original Header Image' ), '', 'resetheader', false ); ?>
</td>
</tr>
<?php endif; ?>
</tbody>
</table>
<?php if ( current_theme_supports( 'custom-header', 'header-text' ) ) : ?>
<h2><?php _e( 'Header Text' ); ?></h2>
<table class="form-table" role="presentation">
<tbody>
<tr>
<th scope="row"><?php _e( 'Header Text' ); ?></th>
<td>
<p>
<label><input type="checkbox" name="display-header-text" id="display-header-text"<?php checked( display_header_text() ); ?> /> <?php _e( 'Show header text with your image.' ); ?></label>
</p>
</td>
</tr>
<tr class="displaying-header-text">
<th scope="row"><?php _e( 'Text Color' ); ?></th>
<td>
<p>
<?php
$default_color = '';
if ( current_theme_supports( 'custom-header', 'default-text-color' ) ) {
$default_color = get_theme_support( 'custom-header', 'default-text-color' );
if ( $default_color && false === strpos( $default_color, '#' ) ) {
$default_color = '#' . $default_color;
}
}
$default_color_attr = $default_color ? ' data-default-color="' . esc_attr( $default_color ) . '"' : '';
$header_textcolor = display_header_text() ? get_header_textcolor() : get_theme_support( 'custom-header', 'default-text-color' );
if ( $header_textcolor && false === strpos( $header_textcolor, '#' ) ) {
$header_textcolor = '#' . $header_textcolor;
}
echo '<input type="text" name="text-color" id="text-color" value="' . esc_attr( $header_textcolor ) . '"' . $default_color_attr . ' />';
if ( $default_color ) {
/* translators: %s: Default text color. */
echo ' <span class="description hide-if-js">' . sprintf( _x( 'Default: %s', 'color' ), esc_html( $default_color ) ) . '</span>';
}
?>
</p>
</td>
</tr>
</tbody>
</table>
<?php
endif;
/**
* Fires just before the submit button in the custom header options form.
*
* @since 3.1.0
*/
do_action( 'custom_header_options' );
wp_nonce_field( 'custom-header-options', '_wpnonce-custom-header-options' );
?>
<?php submit_button( null, 'primary', 'save-header-options' ); ?>
</form>
</div>
<?php
}
```
[do\_action( 'custom\_header\_options' )](../../hooks/custom_header_options)
Fires just before the submit button in the custom header options form.
| Uses | Description |
| --- | --- |
| [submit\_button()](../../functions/submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [get\_uploaded\_header\_images()](../../functions/get_uploaded_header_images) wp-includes/theme.php | Gets the header images uploaded for the active theme. |
| [bloginfo()](../../functions/bloginfo) wp-includes/general-template.php | Displays information about the current site. |
| [wp\_nonce\_field()](../../functions/wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [esc\_attr\_e()](../../functions/esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [Custom\_Image\_Header::process\_default\_headers()](process_default_headers) wp-admin/includes/class-custom-image-header.php | Process the default headers |
| [get\_stylesheet\_directory\_uri()](../../functions/get_stylesheet_directory_uri) wp-includes/theme.php | Retrieves stylesheet directory URI for the active theme. |
| [get\_template\_directory\_uri()](../../functions/get_template_directory_uri) wp-includes/theme.php | Retrieves template directory URI for the active theme. |
| [get\_header\_textcolor()](../../functions/get_header_textcolor) wp-includes/theme.php | Retrieves the custom header text color in 3- or 6-digit hexadecimal form. |
| [wp\_create\_nonce()](../../functions/wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| [get\_header\_image()](../../functions/get_header_image) wp-includes/theme.php | Retrieves header image for custom header. |
| [display\_header\_text()](../../functions/display_header_text) wp-includes/theme.php | Whether to display the header text. |
| [get\_custom\_header()](../../functions/get_custom_header) wp-includes/theme.php | Gets the header image data. |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [Custom\_Image\_Header::show\_header\_selector()](show_header_selector) wp-admin/includes/class-custom-image-header.php | Display UI for selecting one of several default headers. |
| [checked()](../../functions/checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::finished()](finished) wp-admin/includes/class-custom-image-header.php | Display last step of custom header image page. |
| [Custom\_Image\_Header::admin\_page()](admin_page) wp-admin/includes/class-custom-image-header.php | Display the page based on the current step. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Custom_Image_Header::customize_set_last_used( WP_Customize_Manager $wp_customize ) Custom\_Image\_Header::customize\_set\_last\_used( WP\_Customize\_Manager $wp\_customize )
==========================================================================================
Updates the last-used postmeta on a header image attachment after saving a new header image via the Customizer.
`$wp_customize` [WP\_Customize\_Manager](../wp_customize_manager) Required Customize manager. File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function customize_set_last_used( $wp_customize ) {
$header_image_data_setting = $wp_customize->get_setting( 'header_image_data' );
if ( ! $header_image_data_setting ) {
return;
}
$data = $header_image_data_setting->post_value();
if ( ! isset( $data['attachment_id'] ) ) {
return;
}
$attachment_id = $data['attachment_id'];
$key = '_wp_attachment_custom_header_last_used_' . get_stylesheet();
update_post_meta( $attachment_id, $key, time() );
}
```
| Uses | Description |
| --- | --- |
| [get\_stylesheet()](../../functions/get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress Custom_Image_Header::create_attachment_object( string $cropped, int $parent_attachment_id ): array Custom\_Image\_Header::create\_attachment\_object( string $cropped, int $parent\_attachment\_id ): array
========================================================================================================
Create an attachment ‘object’.
`$cropped` string Required Cropped image URL. `$parent_attachment_id` int Required Attachment ID of parent image. array An array with attachment object data.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
final public function create_attachment_object( $cropped, $parent_attachment_id ) {
$parent = get_post( $parent_attachment_id );
$parent_url = wp_get_attachment_url( $parent->ID );
$url = str_replace( wp_basename( $parent_url ), wp_basename( $cropped ), $parent_url );
$size = wp_getimagesize( $cropped );
$image_type = ( $size ) ? $size['mime'] : 'image/jpeg';
$attachment = array(
'ID' => $parent_attachment_id,
'post_title' => wp_basename( $cropped ),
'post_mime_type' => $image_type,
'guid' => $url,
'context' => 'custom-header',
'post_parent' => $parent_attachment_id,
);
return $attachment;
}
```
| Uses | Description |
| --- | --- |
| [wp\_getimagesize()](../../functions/wp_getimagesize) wp-includes/media.php | Allows PHP’s getimagesize() to be debuggable when necessary. |
| [wp\_get\_attachment\_url()](../../functions/wp_get_attachment_url) wp-includes/post.php | Retrieves the URL for an attachment. |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::ajax\_header\_crop()](ajax_header_crop) wp-admin/includes/class-custom-image-header.php | Gets attachment uploaded by Media Manager, crops it, then saves it as a new object. Returns JSON-encoded object details. |
| [Custom\_Image\_Header::step\_3()](step_3) wp-admin/includes/class-custom-image-header.php | Display third step of custom header image page. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
| programming_docs |
wordpress Custom_Image_Header::take_action() Custom\_Image\_Header::take\_action()
=====================================
Execute custom header modification.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function take_action() {
if ( ! current_user_can( 'edit_theme_options' ) ) {
return;
}
if ( empty( $_POST ) ) {
return;
}
$this->updated = true;
if ( isset( $_POST['resetheader'] ) ) {
check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' );
$this->reset_header_image();
return;
}
if ( isset( $_POST['removeheader'] ) ) {
check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' );
$this->remove_header_image();
return;
}
if ( isset( $_POST['text-color'] ) && ! isset( $_POST['display-header-text'] ) ) {
check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' );
set_theme_mod( 'header_textcolor', 'blank' );
} elseif ( isset( $_POST['text-color'] ) ) {
check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' );
$_POST['text-color'] = str_replace( '#', '', $_POST['text-color'] );
$color = preg_replace( '/[^0-9a-fA-F]/', '', $_POST['text-color'] );
if ( strlen( $color ) === 6 || strlen( $color ) === 3 ) {
set_theme_mod( 'header_textcolor', $color );
} elseif ( ! $color ) {
set_theme_mod( 'header_textcolor', 'blank' );
}
}
if ( isset( $_POST['default-header'] ) ) {
check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' );
$this->set_header_image( $_POST['default-header'] );
return;
}
}
```
| Uses | Description |
| --- | --- |
| [Custom\_Image\_Header::reset\_header\_image()](reset_header_image) wp-admin/includes/class-custom-image-header.php | Reset a header image to the default image for the theme. |
| [Custom\_Image\_Header::remove\_header\_image()](remove_header_image) wp-admin/includes/class-custom-image-header.php | Remove a header image. |
| [Custom\_Image\_Header::set\_header\_image()](set_header_image) wp-admin/includes/class-custom-image-header.php | Choose a header image, selected from existing uploaded and default headers, or provide an array of uploaded header data (either new, or from media library). |
| [set\_theme\_mod()](../../functions/set_theme_mod) wp-includes/theme.php | Updates theme modification value for the active theme. |
| [check\_admin\_referer()](../../functions/check_admin_referer) wp-includes/pluggable.php | Ensures intent by verifying that a user was referred from another admin page with the correct security nonce. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress Custom_Image_Header::ajax_header_remove() Custom\_Image\_Header::ajax\_header\_remove()
=============================================
Given an attachment ID for a header image, unsets it as a user-uploaded header image for the active theme.
Triggered when the user clicks the overlay "X" button next to each image choice in the Customizer’s Header tool.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function ajax_header_remove() {
check_ajax_referer( 'header-remove', 'nonce' );
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_send_json_error();
}
$attachment_id = absint( $_POST['attachment_id'] );
if ( $attachment_id < 1 ) {
wp_send_json_error();
}
$key = '_wp_attachment_custom_header_last_used_' . get_stylesheet();
delete_post_meta( $attachment_id, $key );
delete_post_meta( $attachment_id, '_wp_attachment_is_custom_header', get_stylesheet() );
wp_send_json_success();
}
```
| Uses | Description |
| --- | --- |
| [delete\_post\_meta()](../../functions/delete_post_meta) wp-includes/post.php | Deletes a post meta field for the given post ID. |
| [get\_stylesheet()](../../functions/get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [check\_ajax\_referer()](../../functions/check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [wp\_send\_json\_error()](../../functions/wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [wp\_send\_json\_success()](../../functions/wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress Custom_Image_Header::reset_header_image() Custom\_Image\_Header::reset\_header\_image()
=============================================
Reset a header image to the default image for the theme.
This method does not do anything if the theme does not have a default header image.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
final public function reset_header_image() {
$this->process_default_headers();
$default = get_theme_support( 'custom-header', 'default-image' );
if ( ! $default ) {
$this->remove_header_image();
return;
}
$default = sprintf( $default, get_template_directory_uri(), get_stylesheet_directory_uri() );
$default_data = array();
foreach ( $this->default_headers as $header => $details ) {
if ( $details['url'] === $default ) {
$default_data = $details;
break;
}
}
set_theme_mod( 'header_image', $default );
set_theme_mod( 'header_image_data', (object) $default_data );
}
```
| Uses | Description |
| --- | --- |
| [Custom\_Image\_Header::remove\_header\_image()](remove_header_image) wp-admin/includes/class-custom-image-header.php | Remove a header image. |
| [Custom\_Image\_Header::process\_default\_headers()](process_default_headers) wp-admin/includes/class-custom-image-header.php | Process the default headers |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [set\_theme\_mod()](../../functions/set_theme_mod) wp-includes/theme.php | Updates theme modification value for the active theme. |
| [get\_template\_directory\_uri()](../../functions/get_template_directory_uri) wp-includes/theme.php | Retrieves template directory URI for the active theme. |
| [get\_stylesheet\_directory\_uri()](../../functions/get_stylesheet_directory_uri) wp-includes/theme.php | Retrieves stylesheet directory URI for the active theme. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::take\_action()](take_action) wp-admin/includes/class-custom-image-header.php | Execute custom header modification. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress Custom_Image_Header::step_2() Custom\_Image\_Header::step\_2()
================================
Display second step of custom header image page.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function step_2() {
check_admin_referer( 'custom-header-upload', '_wpnonce-custom-header-upload' );
if ( ! current_theme_supports( 'custom-header', 'uploads' ) ) {
wp_die(
'<h1>' . __( 'Something went wrong.' ) . '</h1>' .
'<p>' . __( 'The active theme does not support uploading a custom header image.' ) . '</p>',
403
);
}
if ( empty( $_POST ) && isset( $_GET['file'] ) ) {
$attachment_id = absint( $_GET['file'] );
$file = get_attached_file( $attachment_id, true );
$url = wp_get_attachment_image_src( $attachment_id, 'full' );
$url = $url[0];
} elseif ( isset( $_POST ) ) {
$data = $this->step_2_manage_upload();
$attachment_id = $data['attachment_id'];
$file = $data['file'];
$url = $data['url'];
}
if ( file_exists( $file ) ) {
list( $width, $height, $type, $attr ) = wp_getimagesize( $file );
} else {
$data = wp_get_attachment_metadata( $attachment_id );
$height = isset( $data['height'] ) ? (int) $data['height'] : 0;
$width = isset( $data['width'] ) ? (int) $data['width'] : 0;
unset( $data );
}
$max_width = 0;
// For flex, limit size of image displayed to 1500px unless theme says otherwise.
if ( current_theme_supports( 'custom-header', 'flex-width' ) ) {
$max_width = 1500;
}
if ( current_theme_supports( 'custom-header', 'max-width' ) ) {
$max_width = max( $max_width, get_theme_support( 'custom-header', 'max-width' ) );
}
$max_width = max( $max_width, get_theme_support( 'custom-header', 'width' ) );
// If flexible height isn't supported and the image is the exact right size.
if ( ! current_theme_supports( 'custom-header', 'flex-height' )
&& ! current_theme_supports( 'custom-header', 'flex-width' )
&& (int) get_theme_support( 'custom-header', 'width' ) === $width
&& (int) get_theme_support( 'custom-header', 'height' ) === $height
) {
// Add the metadata.
if ( file_exists( $file ) ) {
wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
}
$this->set_header_image( compact( 'url', 'attachment_id', 'width', 'height' ) );
/**
* Fires after the header image is set or an error is returned.
*
* @since 2.1.0
*
* @param string $file Path to the file.
* @param int $attachment_id Attachment ID.
*/
do_action( 'wp_create_file_in_uploads', $file, $attachment_id ); // For replication.
return $this->finished();
} elseif ( $width > $max_width ) {
$oitar = $width / $max_width;
$image = wp_crop_image(
$attachment_id,
0,
0,
$width,
$height,
$max_width,
$height / $oitar,
false,
str_replace( wp_basename( $file ), 'midsize-' . wp_basename( $file ), $file )
);
if ( ! $image || is_wp_error( $image ) ) {
wp_die( __( 'Image could not be processed. Please go back and try again.' ), __( 'Image Processing Error' ) );
}
/** This filter is documented in wp-admin/includes/class-custom-image-header.php */
$image = apply_filters( 'wp_create_file_in_uploads', $image, $attachment_id ); // For replication.
$url = str_replace( wp_basename( $url ), wp_basename( $image ), $url );
$width = $width / $oitar;
$height = $height / $oitar;
} else {
$oitar = 1;
}
?>
<div class="wrap">
<h1><?php _e( 'Crop Header Image' ); ?></h1>
<form method="post" action="<?php echo esc_url( add_query_arg( 'step', 3 ) ); ?>">
<p class="hide-if-no-js"><?php _e( 'Choose the part of the image you want to use as your header.' ); ?></p>
<p class="hide-if-js"><strong><?php _e( 'You need JavaScript to choose a part of the image.' ); ?></strong></p>
<div id="crop_image" style="position: relative">
<img src="<?php echo esc_url( $url ); ?>" id="upload" width="<?php echo $width; ?>" height="<?php echo $height; ?>" alt="" />
</div>
<input type="hidden" name="x1" id="x1" value="0" />
<input type="hidden" name="y1" id="y1" value="0" />
<input type="hidden" name="width" id="width" value="<?php echo esc_attr( $width ); ?>" />
<input type="hidden" name="height" id="height" value="<?php echo esc_attr( $height ); ?>" />
<input type="hidden" name="attachment_id" id="attachment_id" value="<?php echo esc_attr( $attachment_id ); ?>" />
<input type="hidden" name="oitar" id="oitar" value="<?php echo esc_attr( $oitar ); ?>" />
<?php if ( empty( $_POST ) && isset( $_GET['file'] ) ) { ?>
<input type="hidden" name="create-new-attachment" value="true" />
<?php } ?>
<?php wp_nonce_field( 'custom-header-crop-image' ); ?>
<p class="submit">
<?php submit_button( __( 'Crop and Publish' ), 'primary', 'submit', false ); ?>
<?php
if ( isset( $oitar ) && 1 === $oitar
&& ( current_theme_supports( 'custom-header', 'flex-height' )
|| current_theme_supports( 'custom-header', 'flex-width' ) )
) {
submit_button( __( 'Skip Cropping, Publish Image as Is' ), '', 'skip-cropping', false );
}
?>
</p>
</form>
</div>
<?php
}
```
[do\_action( 'wp\_create\_file\_in\_uploads', string $file, int $attachment\_id )](../../hooks/wp_create_file_in_uploads)
Fires after the header image is set or an error is returned.
| Uses | Description |
| --- | --- |
| [wp\_getimagesize()](../../functions/wp_getimagesize) wp-includes/media.php | Allows PHP’s getimagesize() to be debuggable when necessary. |
| [wp\_nonce\_field()](../../functions/wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [check\_admin\_referer()](../../functions/check_admin_referer) wp-includes/pluggable.php | Ensures intent by verifying that a user was referred from another admin page with the correct security nonce. |
| [wp\_generate\_attachment\_metadata()](../../functions/wp_generate_attachment_metadata) wp-admin/includes/image.php | Generates attachment meta data and create image sub-sizes for images. |
| [wp\_get\_attachment\_image\_src()](../../functions/wp_get_attachment_image_src) wp-includes/media.php | Retrieves an image to represent an attachment. |
| [wp\_get\_attachment\_metadata()](../../functions/wp_get_attachment_metadata) wp-includes/post.php | Retrieves attachment metadata for attachment ID. |
| [wp\_update\_attachment\_metadata()](../../functions/wp_update_attachment_metadata) wp-includes/post.php | Updates metadata for an attachment. |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [get\_attached\_file()](../../functions/get_attached_file) wp-includes/post.php | Retrieves attached file path based on attachment ID. |
| [Custom\_Image\_Header::finished()](finished) wp-admin/includes/class-custom-image-header.php | Display last step of custom header image page. |
| [Custom\_Image\_Header::set\_header\_image()](set_header_image) wp-admin/includes/class-custom-image-header.php | Choose a header image, selected from existing uploaded and default headers, or provide an array of uploaded header data (either new, or from media library). |
| [Custom\_Image\_Header::step\_2\_manage\_upload()](step_2_manage_upload) wp-admin/includes/class-custom-image-header.php | Upload the file to be cropped in the second step. |
| [submit\_button()](../../functions/submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [wp\_crop\_image()](../../functions/wp_crop_image) wp-admin/includes/image.php | Crops an image to a given size. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::admin\_page()](admin_page) wp-admin/includes/class-custom-image-header.php | Display the page based on the current step. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Custom_Image_Header::attachment_fields_to_edit( array $form_fields ): array Custom\_Image\_Header::attachment\_fields\_to\_edit( array $form\_fields ): array
=================================================================================
Unused since 3.5.0.
`$form_fields` array Required array $form\_fields
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function attachment_fields_to_edit( $form_fields ) {
return $form_fields;
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress Custom_Image_Header::remove_header_image() Custom\_Image\_Header::remove\_header\_image()
==============================================
Remove a header image.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
final public function remove_header_image() {
$this->set_header_image( 'remove-header' );
}
```
| Uses | Description |
| --- | --- |
| [Custom\_Image\_Header::set\_header\_image()](set_header_image) wp-admin/includes/class-custom-image-header.php | Choose a header image, selected from existing uploaded and default headers, or provide an array of uploaded header data (either new, or from media library). |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::reset\_header\_image()](reset_header_image) wp-admin/includes/class-custom-image-header.php | Reset a header image to the default image for the theme. |
| [Custom\_Image\_Header::take\_action()](take_action) wp-admin/includes/class-custom-image-header.php | Execute custom header modification. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress Custom_Image_Header::insert_attachment( array $attachment, string $cropped ): int Custom\_Image\_Header::insert\_attachment( array $attachment, string $cropped ): int
====================================================================================
Insert an attachment and its metadata.
`$attachment` array Required An array with attachment object data. `$cropped` string Required File path to cropped image. int Attachment ID.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
final public function insert_attachment( $attachment, $cropped ) {
$parent_id = isset( $attachment['post_parent'] ) ? $attachment['post_parent'] : null;
unset( $attachment['post_parent'] );
$attachment_id = wp_insert_attachment( $attachment, $cropped );
$metadata = wp_generate_attachment_metadata( $attachment_id, $cropped );
// If this is a crop, save the original attachment ID as metadata.
if ( $parent_id ) {
$metadata['attachment_parent'] = $parent_id;
}
/**
* Filters the header image attachment metadata.
*
* @since 3.9.0
*
* @see wp_generate_attachment_metadata()
*
* @param array $metadata Attachment metadata.
*/
$metadata = apply_filters( 'wp_header_image_attachment_metadata', $metadata );
wp_update_attachment_metadata( $attachment_id, $metadata );
return $attachment_id;
}
```
[apply\_filters( 'wp\_header\_image\_attachment\_metadata', array $metadata )](../../hooks/wp_header_image_attachment_metadata)
Filters the header image attachment metadata.
| Uses | Description |
| --- | --- |
| [wp\_generate\_attachment\_metadata()](../../functions/wp_generate_attachment_metadata) wp-admin/includes/image.php | Generates attachment meta data and create image sub-sizes for images. |
| [wp\_insert\_attachment()](../../functions/wp_insert_attachment) wp-includes/post.php | Inserts an attachment. |
| [wp\_update\_attachment\_metadata()](../../functions/wp_update_attachment_metadata) wp-includes/post.php | Updates metadata for an attachment. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::ajax\_header\_crop()](ajax_header_crop) wp-admin/includes/class-custom-image-header.php | Gets attachment uploaded by Media Manager, crops it, then saves it as a new object. Returns JSON-encoded object details. |
| [Custom\_Image\_Header::step\_3()](step_3) wp-admin/includes/class-custom-image-header.php | Display third step of custom header image page. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
| programming_docs |
wordpress Custom_Image_Header::js() Custom\_Image\_Header::js()
===========================
Execute JavaScript depending on step.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function js() {
$step = $this->step();
if ( ( 1 === $step || 3 === $step ) && current_theme_supports( 'custom-header', 'header-text' ) ) {
$this->js_1();
} elseif ( 2 === $step ) {
$this->js_2();
}
}
```
| Uses | Description |
| --- | --- |
| [Custom\_Image\_Header::step()](step) wp-admin/includes/class-custom-image-header.php | Get the current step. |
| [Custom\_Image\_Header::js\_1()](js_1) wp-admin/includes/class-custom-image-header.php | Display JavaScript based on Step 1 and 3. |
| [Custom\_Image\_Header::js\_2()](js_2) wp-admin/includes/class-custom-image-header.php | Display JavaScript based on Step 2. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Custom_Image_Header::js_includes() Custom\_Image\_Header::js\_includes()
=====================================
Set up the enqueue for the JavaScript files.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function js_includes() {
$step = $this->step();
if ( ( 1 === $step || 3 === $step ) ) {
wp_enqueue_media();
wp_enqueue_script( 'custom-header' );
if ( current_theme_supports( 'custom-header', 'header-text' ) ) {
wp_enqueue_script( 'wp-color-picker' );
}
} elseif ( 2 === $step ) {
wp_enqueue_script( 'imgareaselect' );
}
}
```
| Uses | Description |
| --- | --- |
| [Custom\_Image\_Header::step()](step) wp-admin/includes/class-custom-image-header.php | Get the current step. |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [wp\_enqueue\_media()](../../functions/wp_enqueue_media) wp-includes/media.php | Enqueues all scripts, styles, settings, and templates necessary to use all media JS APIs. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Custom_Image_Header::get_default_header_images(): array Custom\_Image\_Header::get\_default\_header\_images(): array
============================================================
Gets the details of default header images if defined.
array Default header images.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function get_default_header_images() {
$this->process_default_headers();
// Get the default image if there is one.
$default = get_theme_support( 'custom-header', 'default-image' );
if ( ! $default ) { // If not, easy peasy.
return $this->default_headers;
}
$default = sprintf( $default, get_template_directory_uri(), get_stylesheet_directory_uri() );
$already_has_default = false;
foreach ( $this->default_headers as $k => $h ) {
if ( $h['url'] === $default ) {
$already_has_default = true;
break;
}
}
if ( $already_has_default ) {
return $this->default_headers;
}
// If the one true image isn't included in the default set, prepend it.
$header_images = array();
$header_images['default'] = array(
'url' => $default,
'thumbnail_url' => $default,
'description' => 'Default',
);
// The rest of the set comes after.
return array_merge( $header_images, $this->default_headers );
}
```
| Uses | Description |
| --- | --- |
| [Custom\_Image\_Header::process\_default\_headers()](process_default_headers) wp-admin/includes/class-custom-image-header.php | Process the default headers |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [get\_template\_directory\_uri()](../../functions/get_template_directory_uri) wp-includes/theme.php | Retrieves template directory URI for the active theme. |
| [get\_stylesheet\_directory\_uri()](../../functions/get_stylesheet_directory_uri) wp-includes/theme.php | Retrieves stylesheet directory URI for the active theme. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Header\_Image\_Control::prepare\_control()](../wp_customize_header_image_control/prepare_control) wp-includes/customize/class-wp-customize-header-image-control.php | |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress Custom_Image_Header::step_3() Custom\_Image\_Header::step\_3()
================================
Display third step of custom header image page.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function step_3() {
check_admin_referer( 'custom-header-crop-image' );
if ( ! current_theme_supports( 'custom-header', 'uploads' ) ) {
wp_die(
'<h1>' . __( 'Something went wrong.' ) . '</h1>' .
'<p>' . __( 'The active theme does not support uploading a custom header image.' ) . '</p>',
403
);
}
if ( ! empty( $_POST['skip-cropping'] )
&& ! current_theme_supports( 'custom-header', 'flex-height' )
&& ! current_theme_supports( 'custom-header', 'flex-width' )
) {
wp_die(
'<h1>' . __( 'Something went wrong.' ) . '</h1>' .
'<p>' . __( 'The active theme does not support a flexible sized header image.' ) . '</p>',
403
);
}
if ( $_POST['oitar'] > 1 ) {
$_POST['x1'] = $_POST['x1'] * $_POST['oitar'];
$_POST['y1'] = $_POST['y1'] * $_POST['oitar'];
$_POST['width'] = $_POST['width'] * $_POST['oitar'];
$_POST['height'] = $_POST['height'] * $_POST['oitar'];
}
$attachment_id = absint( $_POST['attachment_id'] );
$original = get_attached_file( $attachment_id );
$dimensions = $this->get_header_dimensions(
array(
'height' => $_POST['height'],
'width' => $_POST['width'],
)
);
$height = $dimensions['dst_height'];
$width = $dimensions['dst_width'];
if ( empty( $_POST['skip-cropping'] ) ) {
$cropped = wp_crop_image(
$attachment_id,
(int) $_POST['x1'],
(int) $_POST['y1'],
(int) $_POST['width'],
(int) $_POST['height'],
$width,
$height
);
} elseif ( ! empty( $_POST['create-new-attachment'] ) ) {
$cropped = _copy_image_file( $attachment_id );
} else {
$cropped = get_attached_file( $attachment_id );
}
if ( ! $cropped || is_wp_error( $cropped ) ) {
wp_die( __( 'Image could not be processed. Please go back and try again.' ), __( 'Image Processing Error' ) );
}
/** This filter is documented in wp-admin/includes/class-custom-image-header.php */
$cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication.
$attachment = $this->create_attachment_object( $cropped, $attachment_id );
if ( ! empty( $_POST['create-new-attachment'] ) ) {
unset( $attachment['ID'] );
}
// Update the attachment.
$attachment_id = $this->insert_attachment( $attachment, $cropped );
$url = wp_get_attachment_url( $attachment_id );
$this->set_header_image( compact( 'url', 'attachment_id', 'width', 'height' ) );
// Cleanup.
$medium = str_replace( wp_basename( $original ), 'midsize-' . wp_basename( $original ), $original );
if ( file_exists( $medium ) ) {
wp_delete_file( $medium );
}
if ( empty( $_POST['create-new-attachment'] ) && empty( $_POST['skip-cropping'] ) ) {
wp_delete_file( $original );
}
return $this->finished();
}
```
[do\_action( 'wp\_create\_file\_in\_uploads', string $file, int $attachment\_id )](../../hooks/wp_create_file_in_uploads)
Fires after the header image is set or an error is returned.
| Uses | Description |
| --- | --- |
| [wp\_delete\_file()](../../functions/wp_delete_file) wp-includes/functions.php | Deletes a file. |
| [wp\_crop\_image()](../../functions/wp_crop_image) wp-admin/includes/image.php | Crops an image to a given size. |
| [Custom\_Image\_Header::get\_header\_dimensions()](get_header_dimensions) wp-admin/includes/class-custom-image-header.php | Calculate width and height based on what the currently selected theme supports. |
| [Custom\_Image\_Header::create\_attachment\_object()](create_attachment_object) wp-admin/includes/class-custom-image-header.php | Create an attachment ‘object’. |
| [Custom\_Image\_Header::insert\_attachment()](insert_attachment) wp-admin/includes/class-custom-image-header.php | Insert an attachment and its metadata. |
| [Custom\_Image\_Header::set\_header\_image()](set_header_image) wp-admin/includes/class-custom-image-header.php | Choose a header image, selected from existing uploaded and default headers, or provide an array of uploaded header data (either new, or from media library). |
| [Custom\_Image\_Header::finished()](finished) wp-admin/includes/class-custom-image-header.php | Display last step of custom header image page. |
| [get\_attached\_file()](../../functions/get_attached_file) wp-includes/post.php | Retrieves attached file path based on attachment ID. |
| [\_copy\_image\_file()](../../functions/_copy_image_file) wp-admin/includes/image.php | Copies an existing image file. |
| [wp\_get\_attachment\_url()](../../functions/wp_get_attachment_url) wp-includes/post.php | Retrieves the URL for an attachment. |
| [check\_admin\_referer()](../../functions/check_admin_referer) wp-includes/pluggable.php | Ensures intent by verifying that a user was referred from another admin page with the correct security nonce. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::admin\_page()](admin_page) wp-admin/includes/class-custom-image-header.php | Display the page based on the current step. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Switched to using [wp\_get\_attachment\_url()](../../functions/wp_get_attachment_url) instead of the guid for retrieving the header image URL. |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Custom_Image_Header::get_previous_crop( array $attachment ): int|false Custom\_Image\_Header::get\_previous\_crop( array $attachment ): int|false
==========================================================================
Get the ID of a previous crop from the same base image.
`$attachment` array Required An array with a cropped attachment object data. int|false An attachment ID if one exists. False if none.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function get_previous_crop( $attachment ) {
$header_images = $this->get_uploaded_header_images();
// Bail early if there are no header images.
if ( empty( $header_images ) ) {
return false;
}
$previous = false;
foreach ( $header_images as $image ) {
if ( $image['attachment_parent'] === $attachment['post_parent'] ) {
$previous = $image['attachment_id'];
break;
}
}
return $previous;
}
```
| Uses | Description |
| --- | --- |
| [Custom\_Image\_Header::get\_uploaded\_header\_images()](get_uploaded_header_images) wp-admin/includes/class-custom-image-header.php | Gets the previously uploaded header images. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::ajax\_header\_crop()](ajax_header_crop) wp-admin/includes/class-custom-image-header.php | Gets attachment uploaded by Media Manager, crops it, then saves it as a new object. Returns JSON-encoded object details. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress Custom_Image_Header::get_header_dimensions( array $dimensions ): array Custom\_Image\_Header::get\_header\_dimensions( array $dimensions ): array
==========================================================================
Calculate width and height based on what the currently selected theme supports.
`$dimensions` array Required array dst\_height and dst\_width of header image.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
final public function get_header_dimensions( $dimensions ) {
$max_width = 0;
$width = absint( $dimensions['width'] );
$height = absint( $dimensions['height'] );
$theme_height = get_theme_support( 'custom-header', 'height' );
$theme_width = get_theme_support( 'custom-header', 'width' );
$has_flex_width = current_theme_supports( 'custom-header', 'flex-width' );
$has_flex_height = current_theme_supports( 'custom-header', 'flex-height' );
$has_max_width = current_theme_supports( 'custom-header', 'max-width' );
$dst = array(
'dst_height' => null,
'dst_width' => null,
);
// For flex, limit size of image displayed to 1500px unless theme says otherwise.
if ( $has_flex_width ) {
$max_width = 1500;
}
if ( $has_max_width ) {
$max_width = max( $max_width, get_theme_support( 'custom-header', 'max-width' ) );
}
$max_width = max( $max_width, $theme_width );
if ( $has_flex_height && ( ! $has_flex_width || $width > $max_width ) ) {
$dst['dst_height'] = absint( $height * ( $max_width / $width ) );
} elseif ( $has_flex_height && $has_flex_width ) {
$dst['dst_height'] = $height;
} else {
$dst['dst_height'] = $theme_height;
}
if ( $has_flex_width && ( ! $has_flex_height || $width > $max_width ) ) {
$dst['dst_width'] = absint( $width * ( $max_width / $width ) );
} elseif ( $has_flex_width && $has_flex_height ) {
$dst['dst_width'] = $width;
} else {
$dst['dst_width'] = $theme_width;
}
return $dst;
}
```
| Uses | Description |
| --- | --- |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::ajax\_header\_crop()](ajax_header_crop) wp-admin/includes/class-custom-image-header.php | Gets attachment uploaded by Media Manager, crops it, then saves it as a new object. Returns JSON-encoded object details. |
| [Custom\_Image\_Header::step\_3()](step_3) wp-admin/includes/class-custom-image-header.php | Display third step of custom header image page. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress Custom_Image_Header::js_2() Custom\_Image\_Header::js\_2()
==============================
Display JavaScript based on Step 2.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function js_2() {
?>
<script type="text/javascript">
function onEndCrop( coords ) {
jQuery( '#x1' ).val(coords.x);
jQuery( '#y1' ).val(coords.y);
jQuery( '#width' ).val(coords.w);
jQuery( '#height' ).val(coords.h);
}
jQuery( function() {
var xinit = <?php echo absint( get_theme_support( 'custom-header', 'width' ) ); ?>;
var yinit = <?php echo absint( get_theme_support( 'custom-header', 'height' ) ); ?>;
var ratio = xinit / yinit;
var ximg = jQuery('img#upload').width();
var yimg = jQuery('img#upload').height();
if ( yimg < yinit || ximg < xinit ) {
if ( ximg / yimg > ratio ) {
yinit = yimg;
xinit = yinit * ratio;
} else {
xinit = ximg;
yinit = xinit / ratio;
}
}
jQuery('img#upload').imgAreaSelect({
handles: true,
keys: true,
show: true,
x1: 0,
y1: 0,
x2: xinit,
y2: yinit,
<?php
if ( ! current_theme_supports( 'custom-header', 'flex-height' )
&& ! current_theme_supports( 'custom-header', 'flex-width' )
) {
?>
aspectRatio: xinit + ':' + yinit,
<?php
}
if ( ! current_theme_supports( 'custom-header', 'flex-height' ) ) {
?>
maxHeight: <?php echo get_theme_support( 'custom-header', 'height' ); ?>,
<?php
}
if ( ! current_theme_supports( 'custom-header', 'flex-width' ) ) {
?>
maxWidth: <?php echo get_theme_support( 'custom-header', 'width' ); ?>,
<?php
}
?>
onInit: function () {
jQuery('#width').val(xinit);
jQuery('#height').val(yinit);
},
onSelectChange: function(img, c) {
jQuery('#x1').val(c.x1);
jQuery('#y1').val(c.y1);
jQuery('#width').val(c.width);
jQuery('#height').val(c.height);
}
});
} );
</script>
<?php
}
```
| Uses | Description |
| --- | --- |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::js()](js) wp-admin/includes/class-custom-image-header.php | Execute JavaScript depending on step. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress Custom_Image_Header::step_2_manage_upload() Custom\_Image\_Header::step\_2\_manage\_upload()
================================================
Upload the file to be cropped in the second step.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function step_2_manage_upload() {
$overrides = array( 'test_form' => false );
$uploaded_file = $_FILES['import'];
$wp_filetype = wp_check_filetype_and_ext( $uploaded_file['tmp_name'], $uploaded_file['name'] );
if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) ) {
wp_die( __( 'The uploaded file is not a valid image. Please try again.' ) );
}
$file = wp_handle_upload( $uploaded_file, $overrides );
if ( isset( $file['error'] ) ) {
wp_die( $file['error'], __( 'Image Upload Error' ) );
}
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$filename = wp_basename( $file );
// Construct the attachment array.
$attachment = array(
'post_title' => $filename,
'post_content' => $url,
'post_mime_type' => $type,
'guid' => $url,
'context' => 'custom-header',
);
// Save the data.
$attachment_id = wp_insert_attachment( $attachment, $file );
return compact( 'attachment_id', 'file', 'filename', 'url', 'type' );
}
```
| Uses | Description |
| --- | --- |
| [wp\_handle\_upload()](../../functions/wp_handle_upload) wp-admin/includes/file.php | Wrapper for [\_wp\_handle\_upload()](../../functions/_wp_handle_upload) . |
| [wp\_check\_filetype\_and\_ext()](../../functions/wp_check_filetype_and_ext) wp-includes/functions.php | Attempts to determine the real file type of a file. |
| [wp\_insert\_attachment()](../../functions/wp_insert_attachment) wp-includes/post.php | Inserts an attachment. |
| [wp\_match\_mime\_types()](../../functions/wp_match_mime_types) wp-includes/post.php | Checks a MIME-Type against a list. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::step\_2()](step_2) wp-admin/includes/class-custom-image-header.php | Display second step of custom header image page. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
| programming_docs |
wordpress Custom_Image_Header::step(): int Custom\_Image\_Header::step(): int
==================================
Get the current step.
int Current step.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function step() {
if ( ! isset( $_GET['step'] ) ) {
return 1;
}
$step = (int) $_GET['step'];
if ( $step < 1 || 3 < $step ||
( 2 === $step && ! wp_verify_nonce( $_REQUEST['_wpnonce-custom-header-upload'], 'custom-header-upload' ) ) ||
( 3 === $step && ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'custom-header-crop-image' ) )
) {
return 1;
}
return $step;
}
```
| Uses | Description |
| --- | --- |
| [wp\_verify\_nonce()](../../functions/wp_verify_nonce) wp-includes/pluggable.php | Verifies that a correct security nonce was used with time limit. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::admin\_page()](admin_page) wp-admin/includes/class-custom-image-header.php | Display the page based on the current step. |
| [Custom\_Image\_Header::js\_includes()](js_includes) wp-admin/includes/class-custom-image-header.php | Set up the enqueue for the JavaScript files. |
| [Custom\_Image\_Header::css\_includes()](css_includes) wp-admin/includes/class-custom-image-header.php | Set up the enqueue for the CSS files |
| [Custom\_Image\_Header::js()](js) wp-admin/includes/class-custom-image-header.php | Execute JavaScript depending on step. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress Custom_Image_Header::__construct( callable $admin_header_callback, callable $admin_image_div_callback = '' ) Custom\_Image\_Header::\_\_construct( callable $admin\_header\_callback, callable $admin\_image\_div\_callback = '' )
=====================================================================================================================
Constructor – Register administration header callback.
`$admin_header_callback` callable Required `$admin_image_div_callback` callable Optional custom image div output callback. Default: `''`
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function __construct( $admin_header_callback, $admin_image_div_callback = '' ) {
$this->admin_header_callback = $admin_header_callback;
$this->admin_image_div_callback = $admin_image_div_callback;
add_action( 'admin_menu', array( $this, 'init' ) );
add_action( 'customize_save_after', array( $this, 'customize_set_last_used' ) );
add_action( 'wp_ajax_custom-header-crop', array( $this, 'ajax_header_crop' ) );
add_action( 'wp_ajax_custom-header-add', array( $this, 'ajax_header_add' ) );
add_action( 'wp_ajax_custom-header-remove', array( $this, 'ajax_header_remove' ) );
}
```
| Uses | Description |
| --- | --- |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Used By | Description |
| --- | --- |
| [\_custom\_header\_background\_just\_in\_time()](../../functions/_custom_header_background_just_in_time) wp-includes/theme.php | Registers the internal custom header and background routines. |
| [WP\_Customize\_Header\_Image\_Setting::update()](../wp_customize_header_image_setting/update) wp-includes/customize/class-wp-customize-header-image-setting.php | |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Custom_Image_Header::filter_upload_tabs( array $tabs ): array Custom\_Image\_Header::filter\_upload\_tabs( array $tabs ): array
=================================================================
Unused since 3.5.0.
`$tabs` array Required array $tabs
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function filter_upload_tabs( $tabs ) {
return $tabs;
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress Custom_Image_Header::admin_page() Custom\_Image\_Header::admin\_page()
====================================
Display the page based on the current step.
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function admin_page() {
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_die( __( 'Sorry, you are not allowed to customize headers.' ) );
}
$step = $this->step();
if ( 2 === $step ) {
$this->step_2();
} elseif ( 3 === $step ) {
$this->step_3();
} else {
$this->step_1();
}
}
```
| Uses | Description |
| --- | --- |
| [Custom\_Image\_Header::step\_2()](step_2) wp-admin/includes/class-custom-image-header.php | Display second step of custom header image page. |
| [Custom\_Image\_Header::step\_3()](step_3) wp-admin/includes/class-custom-image-header.php | Display third step of custom header image page. |
| [Custom\_Image\_Header::step\_1()](step_1) wp-admin/includes/class-custom-image-header.php | Display first step of custom header image page. |
| [Custom\_Image\_Header::step()](step) wp-admin/includes/class-custom-image-header.php | Get the current step. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Custom_Image_Header::process_default_headers() Custom\_Image\_Header::process\_default\_headers()
==================================================
Process the default headers
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function process_default_headers() {
global $_wp_default_headers;
if ( ! isset( $_wp_default_headers ) ) {
return;
}
if ( ! empty( $this->default_headers ) ) {
return;
}
$this->default_headers = $_wp_default_headers;
$template_directory_uri = get_template_directory_uri();
$stylesheet_directory_uri = get_stylesheet_directory_uri();
foreach ( array_keys( $this->default_headers ) as $header ) {
$this->default_headers[ $header ]['url'] = sprintf(
$this->default_headers[ $header ]['url'],
$template_directory_uri,
$stylesheet_directory_uri
);
$this->default_headers[ $header ]['thumbnail_url'] = sprintf(
$this->default_headers[ $header ]['thumbnail_url'],
$template_directory_uri,
$stylesheet_directory_uri
);
}
}
```
| Uses | Description |
| --- | --- |
| [get\_template\_directory\_uri()](../../functions/get_template_directory_uri) wp-includes/theme.php | Retrieves template directory URI for the active theme. |
| [get\_stylesheet\_directory\_uri()](../../functions/get_stylesheet_directory_uri) wp-includes/theme.php | Retrieves stylesheet directory URI for the active theme. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::get\_default\_header\_images()](get_default_header_images) wp-admin/includes/class-custom-image-header.php | Gets the details of default header images if defined. |
| [Custom\_Image\_Header::step\_1()](step_1) wp-admin/includes/class-custom-image-header.php | Display first step of custom header image page. |
| [Custom\_Image\_Header::set\_header\_image()](set_header_image) wp-admin/includes/class-custom-image-header.php | Choose a header image, selected from existing uploaded and default headers, or provide an array of uploaded header data (either new, or from media library). |
| [Custom\_Image\_Header::reset\_header\_image()](reset_header_image) wp-admin/includes/class-custom-image-header.php | Reset a header image to the default image for the theme. |
| [WP\_Customize\_Header\_Image\_Control::prepare\_control()](../wp_customize_header_image_control/prepare_control) wp-includes/customize/class-wp-customize-header-image-control.php | |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress Custom_Image_Header::show_header_selector( string $type = 'default' ) Custom\_Image\_Header::show\_header\_selector( string $type = 'default' )
=========================================================================
Display UI for selecting one of several default headers.
Show the random image option if this theme has multiple header images.
Random image option is on by default if no header has been set.
`$type` string Optional The header type. One of `'default'` (for the Uploaded Images control) or `'uploaded'` (for the Uploaded Images control). Default: `'default'`
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function show_header_selector( $type = 'default' ) {
if ( 'default' === $type ) {
$headers = $this->default_headers;
} else {
$headers = get_uploaded_header_images();
$type = 'uploaded';
}
if ( 1 < count( $headers ) ) {
echo '<div class="random-header">';
echo '<label><input name="default-header" type="radio" value="random-' . $type . '-image"' . checked( is_random_header_image( $type ), true, false ) . ' />';
_e( '<strong>Random:</strong> Show a different image on each page.' );
echo '</label>';
echo '</div>';
}
echo '<div class="available-headers">';
foreach ( $headers as $header_key => $header ) {
$header_thumbnail = $header['thumbnail_url'];
$header_url = $header['url'];
$header_alt_text = empty( $header['alt_text'] ) ? '' : $header['alt_text'];
echo '<div class="default-header">';
echo '<label><input name="default-header" type="radio" value="' . esc_attr( $header_key ) . '" ' . checked( $header_url, get_theme_mod( 'header_image' ), false ) . ' />';
$width = '';
if ( ! empty( $header['attachment_id'] ) ) {
$width = ' width="230"';
}
echo '<img src="' . set_url_scheme( $header_thumbnail ) . '" alt="' . esc_attr( $header_alt_text ) . '"' . $width . ' /></label>';
echo '</div>';
}
echo '<div class="clear"></div></div>';
}
```
| Uses | Description |
| --- | --- |
| [get\_uploaded\_header\_images()](../../functions/get_uploaded_header_images) wp-includes/theme.php | Gets the header images uploaded for the active theme. |
| [is\_random\_header\_image()](../../functions/is_random_header_image) wp-includes/theme.php | Checks if random header image is in use. |
| [get\_theme\_mod()](../../functions/get_theme_mod) wp-includes/theme.php | Retrieves theme modification value for the active theme. |
| [checked()](../../functions/checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [set\_url\_scheme()](../../functions/set_url_scheme) wp-includes/link-template.php | Sets the scheme for a URL. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::step\_1()](step_1) wp-admin/includes/class-custom-image-header.php | Display first step of custom header image page. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress Custom_Image_Header::css_includes() Custom\_Image\_Header::css\_includes()
======================================
Set up the enqueue for the CSS files
File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
public function css_includes() {
$step = $this->step();
if ( ( 1 === $step || 3 === $step ) && current_theme_supports( 'custom-header', 'header-text' ) ) {
wp_enqueue_style( 'wp-color-picker' );
} elseif ( 2 === $step ) {
wp_enqueue_style( 'imgareaselect' );
}
}
```
| Uses | Description |
| --- | --- |
| [Custom\_Image\_Header::step()](step) wp-admin/includes/class-custom-image-header.php | Get the current step. |
| [wp\_enqueue\_style()](../../functions/wp_enqueue_style) wp-includes/functions.wp-styles.php | Enqueue a CSS stylesheet. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress Custom_Image_Header::set_header_image( mixed $choice ) Custom\_Image\_Header::set\_header\_image( mixed $choice )
==========================================================
Choose a header image, selected from existing uploaded and default headers, or provide an array of uploaded header data (either new, or from media library).
`$choice` mixed Required Which header image to select. Allows for values of `'random-default-image'`, for randomly cycling among the default images; `'random-uploaded-image'`, for randomly cycling among the uploaded images; the key of a default image registered for that theme; and the key of an image uploaded for that theme (the attachment ID of the image).
Or an array of arguments: attachment\_id, url, width, height. All are required. File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/)
```
final public function set_header_image( $choice ) {
if ( is_array( $choice ) || is_object( $choice ) ) {
$choice = (array) $choice;
if ( ! isset( $choice['attachment_id'] ) || ! isset( $choice['url'] ) ) {
return;
}
$choice['url'] = sanitize_url( $choice['url'] );
$header_image_data = (object) array(
'attachment_id' => $choice['attachment_id'],
'url' => $choice['url'],
'thumbnail_url' => $choice['url'],
'height' => $choice['height'],
'width' => $choice['width'],
);
update_post_meta( $choice['attachment_id'], '_wp_attachment_is_custom_header', get_stylesheet() );
set_theme_mod( 'header_image', $choice['url'] );
set_theme_mod( 'header_image_data', $header_image_data );
return;
}
if ( in_array( $choice, array( 'remove-header', 'random-default-image', 'random-uploaded-image' ), true ) ) {
set_theme_mod( 'header_image', $choice );
remove_theme_mod( 'header_image_data' );
return;
}
$uploaded = get_uploaded_header_images();
if ( $uploaded && isset( $uploaded[ $choice ] ) ) {
$header_image_data = $uploaded[ $choice ];
} else {
$this->process_default_headers();
if ( isset( $this->default_headers[ $choice ] ) ) {
$header_image_data = $this->default_headers[ $choice ];
} else {
return;
}
}
set_theme_mod( 'header_image', sanitize_url( $header_image_data['url'] ) );
set_theme_mod( 'header_image_data', $header_image_data );
}
```
| Uses | Description |
| --- | --- |
| [Custom\_Image\_Header::process\_default\_headers()](process_default_headers) wp-admin/includes/class-custom-image-header.php | Process the default headers |
| [set\_theme\_mod()](../../functions/set_theme_mod) wp-includes/theme.php | Updates theme modification value for the active theme. |
| [remove\_theme\_mod()](../../functions/remove_theme_mod) wp-includes/theme.php | Removes theme modification name from active theme list. |
| [get\_uploaded\_header\_images()](../../functions/get_uploaded_header_images) wp-includes/theme.php | Gets the header images uploaded for the active theme. |
| [get\_stylesheet()](../../functions/get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [sanitize\_url()](../../functions/sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::step\_2()](step_2) wp-admin/includes/class-custom-image-header.php | Display second step of custom header image page. |
| [Custom\_Image\_Header::step\_3()](step_3) wp-admin/includes/class-custom-image-header.php | Display third step of custom header image page. |
| [Custom\_Image\_Header::remove\_header\_image()](remove_header_image) wp-admin/includes/class-custom-image-header.php | Remove a header image. |
| [Custom\_Image\_Header::take\_action()](take_action) wp-admin/includes/class-custom-image-header.php | Execute custom header modification. |
| [WP\_Customize\_Header\_Image\_Setting::update()](../wp_customize_header_image_setting/update) wp-includes/customize/class-wp-customize-header-image-setting.php | |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Tax_Query::get_sql_clauses(): string[] WP\_Tax\_Query::get\_sql\_clauses(): string[]
=============================================
Generates SQL clauses to be appended to a main query.
Called by the public [WP\_Tax\_Query::get\_sql()](get_sql), this method is abstracted out to maintain parity with the other Query classes.
string[] Array containing JOIN and WHERE SQL clauses to append to the main query.
* `join`stringSQL fragment to append to the main JOIN clause.
* `where`stringSQL fragment to append to the main WHERE clause.
File: `wp-includes/class-wp-tax-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-tax-query.php/)
```
protected function get_sql_clauses() {
/*
* $queries are passed by reference to get_sql_for_query() for recursion.
* To keep $this->queries unaltered, pass a copy.
*/
$queries = $this->queries;
$sql = $this->get_sql_for_query( $queries );
if ( ! empty( $sql['where'] ) ) {
$sql['where'] = ' AND ' . $sql['where'];
}
return $sql;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Tax\_Query::get\_sql\_for\_query()](get_sql_for_query) wp-includes/class-wp-tax-query.php | Generates SQL clauses for a single query array. |
| Used By | Description |
| --- | --- |
| [WP\_Tax\_Query::get\_sql()](get_sql) wp-includes/class-wp-tax-query.php | Generates SQL clauses to be appended to a main query. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Tax_Query::find_compatible_table_alias( array $clause, array $parent_query ): string|false WP\_Tax\_Query::find\_compatible\_table\_alias( array $clause, array $parent\_query ): string|false
===================================================================================================
Identifies an existing table alias that is compatible with the current query clause.
We avoid unnecessary table joins by allowing each clause to look for an existing table alias that is compatible with the query that it needs to perform.
An existing alias is compatible if (a) it is a sibling of `$clause` (ie, it’s under the scope of the same relation), and (b) the combination of operator and relation between the clauses allows for a shared table join. In the case of [WP\_Tax\_Query](../wp_tax_query), this only applies to ‘IN’ clauses that are connected by the relation ‘OR’.
`$clause` array Required Query clause. `$parent_query` array Required Parent query of $clause. string|false Table alias if found, otherwise false.
File: `wp-includes/class-wp-tax-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-tax-query.php/)
```
protected function find_compatible_table_alias( $clause, $parent_query ) {
$alias = false;
// Sanity check. Only IN queries use the JOIN syntax.
if ( ! isset( $clause['operator'] ) || 'IN' !== $clause['operator'] ) {
return $alias;
}
// Since we're only checking IN queries, we're only concerned with OR relations.
if ( ! isset( $parent_query['relation'] ) || 'OR' !== $parent_query['relation'] ) {
return $alias;
}
$compatible_operators = array( 'IN' );
foreach ( $parent_query as $sibling ) {
if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) {
continue;
}
if ( empty( $sibling['alias'] ) || empty( $sibling['operator'] ) ) {
continue;
}
// The sibling must both have compatible operator to share its alias.
if ( in_array( strtoupper( $sibling['operator'] ), $compatible_operators, true ) ) {
$alias = preg_replace( '/\W/', '_', $sibling['alias'] );
break;
}
}
return $alias;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Tax\_Query::is\_first\_order\_clause()](is_first_order_clause) wp-includes/class-wp-tax-query.php | Determines whether a clause is first-order. |
| Used By | Description |
| --- | --- |
| [WP\_Tax\_Query::get\_sql\_for\_clause()](get_sql_for_clause) wp-includes/class-wp-tax-query.php | Generates SQL JOIN and WHERE clauses for a “first-order” query clause. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Tax_Query::is_first_order_clause( array $query ): bool WP\_Tax\_Query::is\_first\_order\_clause( array $query ): bool
==============================================================
Determines whether a clause is first-order.
A "first-order" clause is one that contains any of the first-order clause keys (‘terms’, ‘taxonomy’, ‘include\_children’, ‘field’, ‘operator’). An empty clause also counts as a first-order clause, for backward compatibility. Any clause that doesn’t meet this is determined, by process of elimination, to be a higher-order query.
`$query` array Required Tax query arguments. bool Whether the query clause is a first-order clause.
File: `wp-includes/class-wp-tax-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-tax-query.php/)
```
protected static function is_first_order_clause( $query ) {
return is_array( $query ) && ( empty( $query ) || array_key_exists( 'terms', $query ) || array_key_exists( 'taxonomy', $query ) || array_key_exists( 'include_children', $query ) || array_key_exists( 'field', $query ) || array_key_exists( 'operator', $query ) );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Tax\_Query::sanitize\_query()](sanitize_query) wp-includes/class-wp-tax-query.php | Ensures the ‘tax\_query’ argument passed to the class constructor is well-formed. |
| [WP\_Tax\_Query::get\_sql\_for\_query()](get_sql_for_query) wp-includes/class-wp-tax-query.php | Generates SQL clauses for a single query array. |
| [WP\_Tax\_Query::find\_compatible\_table\_alias()](find_compatible_table_alias) wp-includes/class-wp-tax-query.php | Identifies an existing table alias that is compatible with the current query clause. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Tax_Query::get_sql_for_clause( array $clause, array $parent_query ): string[] WP\_Tax\_Query::get\_sql\_for\_clause( array $clause, array $parent\_query ): string[]
======================================================================================
Generates SQL JOIN and WHERE clauses for a “first-order” query clause.
`$clause` array Required Query clause (passed by reference). `$parent_query` array Required Parent query array. string[] Array containing JOIN and WHERE SQL clauses to append to a first-order query.
* `join`stringSQL fragment to append to the main JOIN clause.
* `where`stringSQL fragment to append to the main WHERE clause.
File: `wp-includes/class-wp-tax-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-tax-query.php/)
```
public function get_sql_for_clause( &$clause, $parent_query ) {
global $wpdb;
$sql = array(
'where' => array(),
'join' => array(),
);
$join = '';
$where = '';
$this->clean_query( $clause );
if ( is_wp_error( $clause ) ) {
return self::$no_results;
}
$terms = $clause['terms'];
$operator = strtoupper( $clause['operator'] );
if ( 'IN' === $operator ) {
if ( empty( $terms ) ) {
return self::$no_results;
}
$terms = implode( ',', $terms );
/*
* Before creating another table join, see if this clause has a
* sibling with an existing join that can be shared.
*/
$alias = $this->find_compatible_table_alias( $clause, $parent_query );
if ( false === $alias ) {
$i = count( $this->table_aliases );
$alias = $i ? 'tt' . $i : $wpdb->term_relationships;
// Store the alias as part of a flat array to build future iterators.
$this->table_aliases[] = $alias;
// Store the alias with this clause, so later siblings can use it.
$clause['alias'] = $alias;
$join .= " LEFT JOIN $wpdb->term_relationships";
$join .= $i ? " AS $alias" : '';
$join .= " ON ($this->primary_table.$this->primary_id_column = $alias.object_id)";
}
$where = "$alias.term_taxonomy_id $operator ($terms)";
} elseif ( 'NOT IN' === $operator ) {
if ( empty( $terms ) ) {
return $sql;
}
$terms = implode( ',', $terms );
$where = "$this->primary_table.$this->primary_id_column NOT IN (
SELECT object_id
FROM $wpdb->term_relationships
WHERE term_taxonomy_id IN ($terms)
)";
} elseif ( 'AND' === $operator ) {
if ( empty( $terms ) ) {
return $sql;
}
$num_terms = count( $terms );
$terms = implode( ',', $terms );
$where = "(
SELECT COUNT(1)
FROM $wpdb->term_relationships
WHERE term_taxonomy_id IN ($terms)
AND object_id = $this->primary_table.$this->primary_id_column
) = $num_terms";
} elseif ( 'NOT EXISTS' === $operator || 'EXISTS' === $operator ) {
$where = $wpdb->prepare(
"$operator (
SELECT 1
FROM $wpdb->term_relationships
INNER JOIN $wpdb->term_taxonomy
ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
WHERE $wpdb->term_taxonomy.taxonomy = %s
AND $wpdb->term_relationships.object_id = $this->primary_table.$this->primary_id_column
)",
$clause['taxonomy']
);
}
$sql['join'][] = $join;
$sql['where'][] = $where;
return $sql;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Tax\_Query::find\_compatible\_table\_alias()](find_compatible_table_alias) wp-includes/class-wp-tax-query.php | Identifies an existing table alias that is compatible with the current query clause. |
| [WP\_Tax\_Query::clean\_query()](clean_query) wp-includes/class-wp-tax-query.php | Validates a single query. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Tax\_Query::get\_sql\_for\_query()](get_sql_for_query) wp-includes/class-wp-tax-query.php | Generates SQL clauses for a single query array. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Tax_Query::sanitize_relation( string $relation ): string WP\_Tax\_Query::sanitize\_relation( string $relation ): string
==============================================================
Sanitizes a ‘relation’ operator.
`$relation` string Required Raw relation key from the query argument. string Sanitized relation (`'AND'` or `'OR'`).
File: `wp-includes/class-wp-tax-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-tax-query.php/)
```
public function sanitize_relation( $relation ) {
if ( 'OR' === strtoupper( $relation ) ) {
return 'OR';
} else {
return 'AND';
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Tax\_Query::sanitize\_query()](sanitize_query) wp-includes/class-wp-tax-query.php | Ensures the ‘tax\_query’ argument passed to the class constructor is well-formed. |
| [WP\_Tax\_Query::\_\_construct()](__construct) wp-includes/class-wp-tax-query.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Tax_Query::sanitize_query( array $queries ): array WP\_Tax\_Query::sanitize\_query( array $queries ): array
========================================================
Ensures the ‘tax\_query’ argument passed to the class constructor is well-formed.
Ensures that each query-level clause has a ‘relation’ key, and that each first-order clause contains all the necessary keys from `$defaults`.
`$queries` array Required Array of queries clauses. array Sanitized array of query clauses.
File: `wp-includes/class-wp-tax-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-tax-query.php/)
```
public function sanitize_query( $queries ) {
$cleaned_query = array();
$defaults = array(
'taxonomy' => '',
'terms' => array(),
'field' => 'term_id',
'operator' => 'IN',
'include_children' => true,
);
foreach ( $queries as $key => $query ) {
if ( 'relation' === $key ) {
$cleaned_query['relation'] = $this->sanitize_relation( $query );
// First-order clause.
} elseif ( self::is_first_order_clause( $query ) ) {
$cleaned_clause = array_merge( $defaults, $query );
$cleaned_clause['terms'] = (array) $cleaned_clause['terms'];
$cleaned_query[] = $cleaned_clause;
/*
* Keep a copy of the clause in the flate
* $queried_terms array, for use in WP_Query.
*/
if ( ! empty( $cleaned_clause['taxonomy'] ) && 'NOT IN' !== $cleaned_clause['operator'] ) {
$taxonomy = $cleaned_clause['taxonomy'];
if ( ! isset( $this->queried_terms[ $taxonomy ] ) ) {
$this->queried_terms[ $taxonomy ] = array();
}
/*
* Backward compatibility: Only store the first
* 'terms' and 'field' found for a given taxonomy.
*/
if ( ! empty( $cleaned_clause['terms'] ) && ! isset( $this->queried_terms[ $taxonomy ]['terms'] ) ) {
$this->queried_terms[ $taxonomy ]['terms'] = $cleaned_clause['terms'];
}
if ( ! empty( $cleaned_clause['field'] ) && ! isset( $this->queried_terms[ $taxonomy ]['field'] ) ) {
$this->queried_terms[ $taxonomy ]['field'] = $cleaned_clause['field'];
}
}
// Otherwise, it's a nested query, so we recurse.
} elseif ( is_array( $query ) ) {
$cleaned_subquery = $this->sanitize_query( $query );
if ( ! empty( $cleaned_subquery ) ) {
// All queries with children must have a relation.
if ( ! isset( $cleaned_subquery['relation'] ) ) {
$cleaned_subquery['relation'] = 'AND';
}
$cleaned_query[] = $cleaned_subquery;
}
}
}
return $cleaned_query;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Tax\_Query::sanitize\_relation()](sanitize_relation) wp-includes/class-wp-tax-query.php | Sanitizes a ‘relation’ operator. |
| [WP\_Tax\_Query::is\_first\_order\_clause()](is_first_order_clause) wp-includes/class-wp-tax-query.php | Determines whether a clause is first-order. |
| [WP\_Tax\_Query::sanitize\_query()](sanitize_query) wp-includes/class-wp-tax-query.php | Ensures the ‘tax\_query’ argument passed to the class constructor is well-formed. |
| Used By | Description |
| --- | --- |
| [WP\_Tax\_Query::sanitize\_query()](sanitize_query) wp-includes/class-wp-tax-query.php | Ensures the ‘tax\_query’ argument passed to the class constructor is well-formed. |
| [WP\_Tax\_Query::\_\_construct()](__construct) wp-includes/class-wp-tax-query.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Tax_Query::get_sql( string $primary_table, string $primary_id_column ): string[] WP\_Tax\_Query::get\_sql( string $primary\_table, string $primary\_id\_column ): string[]
=========================================================================================
Generates SQL clauses to be appended to a main query.
`$primary_table` string Required Database table where the object being filtered is stored (eg wp\_users). `$primary_id_column` string Required ID column for the filtered object in $primary\_table. string[] Array containing JOIN and WHERE SQL clauses to append to the main query.
* `join`stringSQL fragment to append to the main JOIN clause.
* `where`stringSQL fragment to append to the main WHERE clause.
File: `wp-includes/class-wp-tax-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-tax-query.php/)
```
public function get_sql( $primary_table, $primary_id_column ) {
$this->primary_table = $primary_table;
$this->primary_id_column = $primary_id_column;
return $this->get_sql_clauses();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Tax\_Query::get\_sql\_clauses()](get_sql_clauses) wp-includes/class-wp-tax-query.php | Generates SQL clauses to be appended to a main query. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Tax_Query::transform_query( array $query, string $resulting_field ) WP\_Tax\_Query::transform\_query( array $query, string $resulting\_field )
==========================================================================
Transforms a single query, from one field to another.
Operates on the `$query` object by reference. In the case of error, `$query` is converted to a [WP\_Error](../wp_error) object.
`$query` array Required The single query. Passed by reference. `$resulting_field` string Required The resulting field. Accepts `'slug'`, `'name'`, `'term_taxonomy_id'`, or `'term_id'`. Default `'term_id'`. File: `wp-includes/class-wp-tax-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-tax-query.php/)
```
public function transform_query( &$query, $resulting_field ) {
if ( empty( $query['terms'] ) ) {
return;
}
if ( $query['field'] == $resulting_field ) {
return;
}
$resulting_field = sanitize_key( $resulting_field );
// Empty 'terms' always results in a null transformation.
$terms = array_filter( $query['terms'] );
if ( empty( $terms ) ) {
$query['terms'] = array();
$query['field'] = $resulting_field;
return;
}
$args = array(
'get' => 'all',
'number' => 0,
'taxonomy' => $query['taxonomy'],
'update_term_meta_cache' => false,
'orderby' => 'none',
);
// Term query parameter name depends on the 'field' being searched on.
switch ( $query['field'] ) {
case 'slug':
$args['slug'] = $terms;
break;
case 'name':
$args['name'] = $terms;
break;
case 'term_taxonomy_id':
$args['term_taxonomy_id'] = $terms;
break;
default:
$args['include'] = wp_parse_id_list( $terms );
break;
}
if ( ! is_taxonomy_hierarchical( $query['taxonomy'] ) ) {
$args['number'] = count( $terms );
}
$term_query = new WP_Term_Query();
$term_list = $term_query->query( $args );
if ( is_wp_error( $term_list ) ) {
$query = $term_list;
return;
}
if ( 'AND' === $query['operator'] && count( $term_list ) < count( $query['terms'] ) ) {
$query = new WP_Error( 'inexistent_terms', __( 'Inexistent terms.' ) );
return;
}
$query['terms'] = wp_list_pluck( $term_list, $resulting_field );
$query['field'] = $resulting_field;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Term\_Query::\_\_construct()](../wp_term_query/__construct) wp-includes/class-wp-term-query.php | Constructor. |
| [wp\_parse\_id\_list()](../../functions/wp_parse_id_list) wp-includes/functions.php | Cleans up an array, comma- or space-separated list of IDs. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [is\_taxonomy\_hierarchical()](../../functions/is_taxonomy_hierarchical) wp-includes/taxonomy.php | Determines whether the taxonomy object is hierarchical. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [sanitize\_key()](../../functions/sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Tax\_Query::clean\_query()](clean_query) wp-includes/class-wp-tax-query.php | Validates a single query. |
| Version | Description |
| --- | --- |
| [3.2.0](https://developer.wordpress.org/reference/since/3.2.0/) | Introduced. |
wordpress WP_Tax_Query::__construct( array $tax_query ) WP\_Tax\_Query::\_\_construct( array $tax\_query )
==================================================
Constructor.
`$tax_query` array Required Array of taxonomy query clauses.
* `relation`stringOptional. The MySQL keyword used to join the clauses of the query. Accepts `'AND'`, or `'OR'`. Default `'AND'`.
* `...$0`array An array of first-order clause parameters, or another fully-formed tax query.
+ `taxonomy`stringTaxonomy being queried. Optional when field=term\_taxonomy\_id.
+ `terms`string|int|arrayTerm or terms to filter by.
+ `field`stringField to match $terms against. Accepts `'term_id'`, `'slug'`, `'name'`, or `'term_taxonomy_id'`. Default: `'term_id'`.
+ `operator`stringMySQL operator to be used with $terms in the WHERE clause.
Accepts `'AND'`, `'IN'`, 'NOT IN', `'EXISTS'`, 'NOT EXISTS'.
Default: `'IN'`.
+ `include_children`boolOptional. Whether to include child terms.
Requires a $taxonomy. Default: true. File: `wp-includes/class-wp-tax-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-tax-query.php/)
```
public function __construct( $tax_query ) {
if ( isset( $tax_query['relation'] ) ) {
$this->relation = $this->sanitize_relation( $tax_query['relation'] );
} else {
$this->relation = 'AND';
}
$this->queries = $this->sanitize_query( $tax_query );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Tax\_Query::sanitize\_relation()](sanitize_relation) wp-includes/class-wp-tax-query.php | Sanitizes a ‘relation’ operator. |
| [WP\_Tax\_Query::sanitize\_query()](sanitize_query) wp-includes/class-wp-tax-query.php | Ensures the ‘tax\_query’ argument passed to the class constructor is well-formed. |
| Used By | Description |
| --- | --- |
| [WP\_Query::parse\_tax\_query()](../wp_query/parse_tax_query) wp-includes/class-wp-query.php | Parses various taxonomy related query vars. |
| [get\_tax\_sql()](../../functions/get_tax_sql) wp-includes/taxonomy.php | Given a taxonomy query, generates SQL to be appended to a main query. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Added support for `$operator` 'NOT EXISTS' and `'EXISTS'` values. |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Tax_Query::clean_query( array $query ) WP\_Tax\_Query::clean\_query( array $query )
============================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Validates a single query.
`$query` array Required The single query. Passed by reference. File: `wp-includes/class-wp-tax-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-tax-query.php/)
```
private function clean_query( &$query ) {
if ( empty( $query['taxonomy'] ) ) {
if ( 'term_taxonomy_id' !== $query['field'] ) {
$query = new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
return;
}
// So long as there are shared terms, 'include_children' requires that a taxonomy is set.
$query['include_children'] = false;
} elseif ( ! taxonomy_exists( $query['taxonomy'] ) ) {
$query = new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
return;
}
if ( 'slug' === $query['field'] || 'name' === $query['field'] ) {
$query['terms'] = array_unique( (array) $query['terms'] );
} else {
$query['terms'] = wp_parse_id_list( $query['terms'] );
}
if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
$this->transform_query( $query, 'term_id' );
if ( is_wp_error( $query ) ) {
return;
}
$children = array();
foreach ( $query['terms'] as $term ) {
$children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
$children[] = $term;
}
$query['terms'] = $children;
}
$this->transform_query( $query, 'term_taxonomy_id' );
}
```
| Uses | Description |
| --- | --- |
| [wp\_parse\_id\_list()](../../functions/wp_parse_id_list) wp-includes/functions.php | Cleans up an array, comma- or space-separated list of IDs. |
| [WP\_Tax\_Query::transform\_query()](transform_query) wp-includes/class-wp-tax-query.php | Transforms a single query, from one field to another. |
| [get\_term\_children()](../../functions/get_term_children) wp-includes/taxonomy.php | Merges all term children into a single array of their IDs. |
| [taxonomy\_exists()](../../functions/taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| [is\_taxonomy\_hierarchical()](../../functions/is_taxonomy_hierarchical) wp-includes/taxonomy.php | Determines whether the taxonomy object is hierarchical. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Tax\_Query::get\_sql\_for\_clause()](get_sql_for_clause) wp-includes/class-wp-tax-query.php | Generates SQL JOIN and WHERE clauses for a “first-order” query clause. |
| Version | Description |
| --- | --- |
| [3.2.0](https://developer.wordpress.org/reference/since/3.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Tax_Query::get_sql_for_query( array $query, int $depth ): string[] WP\_Tax\_Query::get\_sql\_for\_query( array $query, int $depth ): string[]
==========================================================================
Generates SQL clauses for a single query array.
If nested subqueries are found, this method recurses the tree to produce the properly nested SQL.
`$query` array Required Query to parse (passed by reference). `$depth` int Optional Number of tree levels deep we currently are.
Used to calculate indentation. Default 0. string[] Array containing JOIN and WHERE SQL clauses to append to a single query array.
* `join`stringSQL fragment to append to the main JOIN clause.
* `where`stringSQL fragment to append to the main WHERE clause.
File: `wp-includes/class-wp-tax-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-tax-query.php/)
```
protected function get_sql_for_query( &$query, $depth = 0 ) {
$sql_chunks = array(
'join' => array(),
'where' => array(),
);
$sql = array(
'join' => '',
'where' => '',
);
$indent = '';
for ( $i = 0; $i < $depth; $i++ ) {
$indent .= ' ';
}
foreach ( $query as $key => &$clause ) {
if ( 'relation' === $key ) {
$relation = $query['relation'];
} elseif ( is_array( $clause ) ) {
// This is a first-order clause.
if ( $this->is_first_order_clause( $clause ) ) {
$clause_sql = $this->get_sql_for_clause( $clause, $query );
$where_count = count( $clause_sql['where'] );
if ( ! $where_count ) {
$sql_chunks['where'][] = '';
} elseif ( 1 === $where_count ) {
$sql_chunks['where'][] = $clause_sql['where'][0];
} else {
$sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
}
$sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
// This is a subquery, so we recurse.
} else {
$clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
$sql_chunks['where'][] = $clause_sql['where'];
$sql_chunks['join'][] = $clause_sql['join'];
}
}
}
// Filter to remove empties.
$sql_chunks['join'] = array_filter( $sql_chunks['join'] );
$sql_chunks['where'] = array_filter( $sql_chunks['where'] );
if ( empty( $relation ) ) {
$relation = 'AND';
}
// Filter duplicate JOIN clauses and combine into a single string.
if ( ! empty( $sql_chunks['join'] ) ) {
$sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
}
// Generate a single WHERE clause with proper brackets and indentation.
if ( ! empty( $sql_chunks['where'] ) ) {
$sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
}
return $sql;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Tax\_Query::is\_first\_order\_clause()](is_first_order_clause) wp-includes/class-wp-tax-query.php | Determines whether a clause is first-order. |
| [WP\_Tax\_Query::get\_sql\_for\_clause()](get_sql_for_clause) wp-includes/class-wp-tax-query.php | Generates SQL JOIN and WHERE clauses for a “first-order” query clause. |
| [WP\_Tax\_Query::get\_sql\_for\_query()](get_sql_for_query) wp-includes/class-wp-tax-query.php | Generates SQL clauses for a single query array. |
| Used By | Description |
| --- | --- |
| [WP\_Tax\_Query::get\_sql\_clauses()](get_sql_clauses) wp-includes/class-wp-tax-query.php | Generates SQL clauses to be appended to a main query. |
| [WP\_Tax\_Query::get\_sql\_for\_query()](get_sql_for_query) wp-includes/class-wp-tax-query.php | Generates SQL clauses for a single query array. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress IXR_ClientMulticall::IXR_ClientMulticall( $server, $path = false, $port = 80 ) IXR\_ClientMulticall::IXR\_ClientMulticall( $server, $path = false, $port = 80 )
================================================================================
PHP4 constructor.
File: `wp-includes/IXR/class-IXR-clientmulticall.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-clientmulticall.php/)
```
public function IXR_ClientMulticall( $server, $path = false, $port = 80 ) {
self::__construct( $server, $path, $port );
}
```
| Uses | Description |
| --- | --- |
| [IXR\_ClientMulticall::\_\_construct()](__construct) wp-includes/IXR/class-IXR-clientmulticall.php | PHP5 constructor. |
wordpress IXR_ClientMulticall::query( $args ): bool IXR\_ClientMulticall::query( $args ): bool
==========================================
bool
File: `wp-includes/IXR/class-IXR-clientmulticall.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-clientmulticall.php/)
```
function query( ...$args )
{
// Prepare multicall, then call the parent::query() method
return parent::query('system.multicall', $this->calls);
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Client::query()](../ixr_client/query) wp-includes/IXR/class-IXR-client.php | |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Formalized the existing `...$args` parameter by adding it to the function signature. |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress IXR_ClientMulticall::addCall( $args ) IXR\_ClientMulticall::addCall( $args )
======================================
File: `wp-includes/IXR/class-IXR-clientmulticall.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-clientmulticall.php/)
```
function addCall( ...$args )
{
$methodName = array_shift($args);
$struct = array(
'methodName' => $methodName,
'params' => $args
);
$this->calls[] = $struct;
}
```
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Formalized the existing `...$args` parameter by adding it to the function signature. |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress IXR_ClientMulticall::__construct( $server, $path = false, $port = 80 ) IXR\_ClientMulticall::\_\_construct( $server, $path = false, $port = 80 )
=========================================================================
PHP5 constructor.
File: `wp-includes/IXR/class-IXR-clientmulticall.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-clientmulticall.php/)
```
function __construct( $server, $path = false, $port = 80 )
{
parent::IXR_Client($server, $path, $port);
$this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)';
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Client::IXR\_Client()](../ixr_client/ixr_client) wp-includes/IXR/class-IXR-client.php | PHP4 constructor. |
| Used By | Description |
| --- | --- |
| [IXR\_ClientMulticall::IXR\_ClientMulticall()](ixr_clientmulticall) wp-includes/IXR/class-IXR-clientmulticall.php | PHP4 constructor. |
wordpress WP_Site::to_array(): array WP\_Site::to\_array(): array
============================
Converts an object to array.
array Object as array.
File: `wp-includes/class-wp-site.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site.php/)
```
public function to_array() {
return get_object_vars( $this );
}
```
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Site::__set( string $key, mixed $value ) WP\_Site::\_\_set( string $key, mixed $value )
==============================================
Setter.
Allows current multisite naming conventions while setting properties.
`$key` string Required Property to set. `$value` mixed Required Value to assign to the property. File: `wp-includes/class-wp-site.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site.php/)
```
public function __set( $key, $value ) {
switch ( $key ) {
case 'id':
$this->blog_id = (string) $value;
break;
case 'network_id':
$this->site_id = (string) $value;
break;
default:
$this->$key = $value;
}
}
```
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Site::__get( string $key ): mixed WP\_Site::\_\_get( string $key ): mixed
=======================================
Getter.
Allows current multisite naming conventions when getting properties.
Allows access to extended site properties.
`$key` string Required Property to get. mixed Value of the property. Null if not available.
File: `wp-includes/class-wp-site.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site.php/)
```
public function __get( $key ) {
switch ( $key ) {
case 'id':
return (int) $this->blog_id;
case 'network_id':
return (int) $this->site_id;
case 'blogname':
case 'siteurl':
case 'post_count':
case 'home':
default: // Custom properties added by 'site_details' filter.
if ( ! did_action( 'ms_loaded' ) ) {
return null;
}
$details = $this->get_details();
if ( isset( $details->$key ) ) {
return $details->$key;
}
}
return null;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site::get\_details()](../wp_site/get_details) wp-includes/class-wp-site.php | Retrieves the details for this site. |
| [did\_action()](../../functions/did_action) wp-includes/plugin.php | Retrieves the number of times an action has been fired during the current request. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Site::get_details(): stdClass WP\_Site::get\_details(): stdClass
==================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness. Use [WP\_Site::\_\_get()](../wp_site/__get) instead.
Retrieves the details for this site.
This method is used internally to lazy-load the extended properties of a site.
* [WP\_Site::\_\_get()](../wp_site/__get)
stdClass A raw site object with all details included.
File: `wp-includes/class-wp-site.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site.php/)
```
private function get_details() {
$details = wp_cache_get( $this->blog_id, 'site-details' );
if ( false === $details ) {
switch_to_blog( $this->blog_id );
// Create a raw copy of the object for backward compatibility with the filter below.
$details = new stdClass();
foreach ( get_object_vars( $this ) as $key => $value ) {
$details->$key = $value;
}
$details->blogname = get_option( 'blogname' );
$details->siteurl = get_option( 'siteurl' );
$details->post_count = get_option( 'post_count' );
$details->home = get_option( 'home' );
restore_current_blog();
wp_cache_set( $this->blog_id, $details, 'site-details' );
}
/** This filter is documented in wp-includes/ms-blogs.php */
$details = apply_filters_deprecated( 'blog_details', array( $details ), '4.7.0', 'site_details' );
/**
* Filters a site's extended properties.
*
* @since 4.6.0
*
* @param stdClass $details The site details.
*/
$details = apply_filters( 'site_details', $details );
return $details;
}
```
[apply\_filters\_deprecated( 'blog\_details', WP\_Site $details )](../../hooks/blog_details)
Filters a blog’s details.
[apply\_filters( 'site\_details', stdClass $details )](../../hooks/site_details)
Filters a site’s extended properties.
| Uses | Description |
| --- | --- |
| [apply\_filters\_deprecated()](../../functions/apply_filters_deprecated) wp-includes/plugin.php | Fires functions attached to a deprecated filter hook. |
| [wp\_cache\_set()](../../functions/wp_cache_set) wp-includes/cache.php | Saves the data to the cache. |
| [switch\_to\_blog()](../../functions/switch_to_blog) wp-includes/ms-blogs.php | Switch the current blog. |
| [restore\_current\_blog()](../../functions/restore_current_blog) wp-includes/ms-blogs.php | Restore the current blog, after calling [switch\_to\_blog()](../../functions/switch_to_blog) . |
| [wp\_cache\_get()](../../functions/wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Site::\_\_get()](__get) wp-includes/class-wp-site.php | Getter. |
| [WP\_Site::\_\_isset()](__isset) wp-includes/class-wp-site.php | Isset-er. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Site::__isset( string $key ): bool WP\_Site::\_\_isset( string $key ): bool
========================================
Isset-er.
Allows current multisite naming conventions when checking for properties.
Checks for extended site properties.
`$key` string Required Property to check if set. bool Whether the property is set.
File: `wp-includes/class-wp-site.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site.php/)
```
public function __isset( $key ) {
switch ( $key ) {
case 'id':
case 'network_id':
return true;
case 'blogname':
case 'siteurl':
case 'post_count':
case 'home':
if ( ! did_action( 'ms_loaded' ) ) {
return false;
}
return true;
default: // Custom properties added by 'site_details' filter.
if ( ! did_action( 'ms_loaded' ) ) {
return false;
}
$details = $this->get_details();
if ( isset( $details->$key ) ) {
return true;
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site::get\_details()](get_details) wp-includes/class-wp-site.php | Retrieves the details for this site. |
| [did\_action()](../../functions/did_action) wp-includes/plugin.php | Retrieves the number of times an action has been fired during the current request. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Site::__construct( WP_Site|object $site ) WP\_Site::\_\_construct( WP\_Site|object $site )
================================================
Creates a new [WP\_Site](../wp_site) object.
Will populate object properties from the object provided and assign other default properties based on that information.
`$site` [WP\_Site](../wp_site)|object Required A site object. File: `wp-includes/class-wp-site.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site.php/)
```
public function __construct( $site ) {
foreach ( get_object_vars( $site ) as $key => $value ) {
$this->$key = $value;
}
}
```
| Used By | Description |
| --- | --- |
| [wp\_maybe\_transition\_site\_statuses\_on\_update()](../../functions/wp_maybe_transition_site_statuses_on_update) wp-includes/ms-site.php | Triggers actions on site status updates. |
| [get\_site()](../../functions/get_site) wp-includes/ms-site.php | Retrieves site data given a site ID or site object. |
| [WP\_Site::get\_instance()](get_instance) wp-includes/class-wp-site.php | Retrieves a site from the database by its ID. |
| [get\_site\_by\_path()](../../functions/get_site_by_path) wp-includes/ms-load.php | Retrieves the closest matching site object by its domain and path. |
| [clean\_blog\_cache()](../../functions/clean_blog_cache) wp-includes/ms-site.php | Clean the blog cache |
| [get\_blog\_details()](../../functions/get_blog_details) wp-includes/ms-blogs.php | Retrieve the details for a blog from the blogs table and blog options. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Site::get_instance( int $site_id ): WP_Site|false WP\_Site::get\_instance( int $site\_id ): WP\_Site|false
========================================================
Retrieves a site from the database by its ID.
`$site_id` int Required The ID of the site to retrieve. [WP\_Site](../wp_site)|false The site's object if found. False if not.
File: `wp-includes/class-wp-site.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site.php/)
```
public static function get_instance( $site_id ) {
global $wpdb;
$site_id = (int) $site_id;
if ( ! $site_id ) {
return false;
}
$_site = wp_cache_get( $site_id, 'sites' );
if ( false === $_site ) {
$_site = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->blogs} WHERE blog_id = %d LIMIT 1", $site_id ) );
if ( empty( $_site ) || is_wp_error( $_site ) ) {
$_site = -1;
}
wp_cache_add( $site_id, $_site, 'sites' );
}
if ( is_numeric( $_site ) ) {
return false;
}
return new WP_Site( $_site );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site::\_\_construct()](__construct) wp-includes/class-wp-site.php | Creates a new [WP\_Site](../wp_site) object. |
| [wp\_cache\_add()](../../functions/wp_cache_add) wp-includes/cache.php | Adds data to the cache, if the cache key doesn’t already exist. |
| [wpdb::get\_row()](../wpdb/get_row) wp-includes/class-wpdb.php | Retrieves one row from the database. |
| [wp\_cache\_get()](../../functions/wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_MS\_Sites\_List\_Table::site\_states()](../wp_ms_sites_list_table/site_states) wp-admin/includes/class-wp-ms-sites-list-table.php | Maybe output comma-separated site states. |
| [get\_site()](../../functions/get_site) wp-includes/ms-site.php | Retrieves site data given a site ID or site object. |
| [get\_blog\_details()](../../functions/get_blog_details) wp-includes/ms-blogs.php | Retrieve the details for a blog from the blogs table and blog options. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Widget_Categories::form( array $instance ) WP\_Widget\_Categories::form( array $instance )
===============================================
Outputs the settings form for the Categories widget.
`$instance` array Required Current settings. File: `wp-includes/widgets/class-wp-widget-categories.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-categories.php/)
```
public function form( $instance ) {
// Defaults.
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$count = isset( $instance['count'] ) ? (bool) $instance['count'] : false;
$hierarchical = isset( $instance['hierarchical'] ) ? (bool) $instance['hierarchical'] : false;
$dropdown = isset( $instance['dropdown'] ) ? (bool) $instance['dropdown'] : false;
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $instance['title'] ); ?>" />
</p>
<p>
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'dropdown' ); ?>" name="<?php echo $this->get_field_name( 'dropdown' ); ?>"<?php checked( $dropdown ); ?> />
<label for="<?php echo $this->get_field_id( 'dropdown' ); ?>"><?php _e( 'Display as dropdown' ); ?></label>
<br />
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>"<?php checked( $count ); ?> />
<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php _e( 'Show post counts' ); ?></label>
<br />
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'hierarchical' ); ?>" name="<?php echo $this->get_field_name( 'hierarchical' ); ?>"<?php checked( $hierarchical ); ?> />
<label for="<?php echo $this->get_field_id( 'hierarchical' ); ?>"><?php _e( 'Show hierarchy' ); ?></label>
</p>
<?php
}
```
| Uses | Description |
| --- | --- |
| [checked()](../../functions/checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Widget_Categories::update( array $new_instance, array $old_instance ): array WP\_Widget\_Categories::update( array $new\_instance, array $old\_instance ): array
===================================================================================
Handles updating settings for the current Categories widget instance.
`$new_instance` array Required New settings for this instance as input by the user via [WP\_Widget::form()](../wp_widget/form). `$old_instance` array Required Old settings for this instance. array Updated settings to save.
File: `wp-includes/widgets/class-wp-widget-categories.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-categories.php/)
```
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = sanitize_text_field( $new_instance['title'] );
$instance['count'] = ! empty( $new_instance['count'] ) ? 1 : 0;
$instance['hierarchical'] = ! empty( $new_instance['hierarchical'] ) ? 1 : 0;
$instance['dropdown'] = ! empty( $new_instance['dropdown'] ) ? 1 : 0;
return $instance;
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Categories::__construct() WP\_Widget\_Categories::\_\_construct()
=======================================
Sets up a new Categories widget instance.
File: `wp-includes/widgets/class-wp-widget-categories.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-categories.php/)
```
public function __construct() {
$widget_ops = array(
'classname' => 'widget_categories',
'description' => __( 'A list or dropdown of categories.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
parent::__construct( 'categories', __( 'Categories' ), $widget_ops );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget::\_\_construct()](../wp_widget/__construct) wp-includes/class-wp-widget.php | PHP5 constructor. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Categories::widget( array $args, array $instance ) WP\_Widget\_Categories::widget( array $args, array $instance )
==============================================================
Outputs the content for the current Categories widget instance.
`$args` array Required Display arguments including `'before_title'`, `'after_title'`, `'before_widget'`, and `'after_widget'`. `$instance` array Required Settings for the current Categories widget instance. File: `wp-includes/widgets/class-wp-widget-categories.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-categories.php/)
```
public function widget( $args, $instance ) {
static $first_dropdown = true;
$default_title = __( 'Categories' );
$title = ! empty( $instance['title'] ) ? $instance['title'] : $default_title;
/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
$count = ! empty( $instance['count'] ) ? '1' : '0';
$hierarchical = ! empty( $instance['hierarchical'] ) ? '1' : '0';
$dropdown = ! empty( $instance['dropdown'] ) ? '1' : '0';
echo $args['before_widget'];
if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
}
$cat_args = array(
'orderby' => 'name',
'show_count' => $count,
'hierarchical' => $hierarchical,
);
if ( $dropdown ) {
printf( '<form action="%s" method="get">', esc_url( home_url() ) );
$dropdown_id = ( $first_dropdown ) ? 'cat' : "{$this->id_base}-dropdown-{$this->number}";
$first_dropdown = false;
echo '<label class="screen-reader-text" for="' . esc_attr( $dropdown_id ) . '">' . $title . '</label>';
$cat_args['show_option_none'] = __( 'Select Category' );
$cat_args['id'] = $dropdown_id;
/**
* Filters the arguments for the Categories widget drop-down.
*
* @since 2.8.0
* @since 4.9.0 Added the `$instance` parameter.
*
* @see wp_dropdown_categories()
*
* @param array $cat_args An array of Categories widget drop-down arguments.
* @param array $instance Array of settings for the current widget.
*/
wp_dropdown_categories( apply_filters( 'widget_categories_dropdown_args', $cat_args, $instance ) );
echo '</form>';
$type_attr = current_theme_supports( 'html5', 'script' ) ? '' : ' type="text/javascript"';
?>
<script<?php echo $type_attr; ?>>
/* <![CDATA[ */
(function() {
var dropdown = document.getElementById( "<?php echo esc_js( $dropdown_id ); ?>" );
function onCatChange() {
if ( dropdown.options[ dropdown.selectedIndex ].value > 0 ) {
dropdown.parentNode.submit();
}
}
dropdown.onchange = onCatChange;
})();
/* ]]> */
</script>
<?php
} else {
$format = current_theme_supports( 'html5', 'navigation-widgets' ) ? 'html5' : 'xhtml';
/** This filter is documented in wp-includes/widgets/class-wp-nav-menu-widget.php */
$format = apply_filters( 'navigation_widgets_format', $format );
if ( 'html5' === $format ) {
// The title may be filtered: Strip out HTML and make sure the aria-label is never empty.
$title = trim( strip_tags( $title ) );
$aria_label = $title ? $title : $default_title;
echo '<nav aria-label="' . esc_attr( $aria_label ) . '">';
}
?>
<ul>
<?php
$cat_args['title_li'] = '';
/**
* Filters the arguments for the Categories widget.
*
* @since 2.8.0
* @since 4.9.0 Added the `$instance` parameter.
*
* @param array $cat_args An array of Categories widget options.
* @param array $instance Array of settings for the current widget.
*/
wp_list_categories( apply_filters( 'widget_categories_args', $cat_args, $instance ) );
?>
</ul>
<?php
if ( 'html5' === $format ) {
echo '</nav>';
}
}
echo $args['after_widget'];
}
```
[apply\_filters( 'navigation\_widgets\_format', string $format )](../../hooks/navigation_widgets_format)
Filters the HTML format of widgets with navigation links.
[apply\_filters( 'widget\_categories\_args', array $cat\_args, array $instance )](../../hooks/widget_categories_args)
Filters the arguments for the Categories widget.
[apply\_filters( 'widget\_categories\_dropdown\_args', array $cat\_args, array $instance )](../../hooks/widget_categories_dropdown_args)
Filters the arguments for the Categories widget drop-down.
[apply\_filters( 'widget\_title', string $title, array $instance, mixed $id\_base )](../../hooks/widget_title)
Filters the widget title.
| Uses | Description |
| --- | --- |
| [wp\_dropdown\_categories()](../../functions/wp_dropdown_categories) wp-includes/category-template.php | Displays or retrieves the HTML dropdown list of categories. |
| [wp\_list\_categories()](../../functions/wp_list_categories) wp-includes/category-template.php | Displays or retrieves the HTML list of categories. |
| [esc\_js()](../../functions/esc_js) wp-includes/formatting.php | Escapes single quotes, `"`, , `&`, and fixes line endings. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Creates a unique HTML ID for the `<select>` element if more than one instance is displayed on the page. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Name_Control::content_template() WP\_Customize\_Nav\_Menu\_Name\_Control::content\_template()
============================================================
Render the Underscore template for this control.
File: `wp-includes/customize/class-wp-customize-nav-menu-name-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-name-control.php/)
```
protected function content_template() {
?>
<label>
<# if ( data.label ) { #>
<span class="customize-control-title">{{ data.label }}</span>
<# } #>
<input type="text" class="menu-name-field live-update-section-title"
<# if ( data.description ) { #>
aria-describedby="{{ data.section }}-description"
<# } #>
/>
</label>
<# if ( data.description ) { #>
<p id="{{ data.section }}-description">{{ data.description }}</p>
<# } #>
<?php
}
```
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Name_Control::render_content() WP\_Customize\_Nav\_Menu\_Name\_Control::render\_content()
==========================================================
No-op since we’re using JS template.
File: `wp-includes/customize/class-wp-customize-nav-menu-name-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-name-control.php/)
```
protected function render_content() {}
```
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Filesystem_Direct::chmod( string $file, int|false $mode = false, bool $recursive = false ): bool WP\_Filesystem\_Direct::chmod( string $file, int|false $mode = false, bool $recursive = false ): bool
=====================================================================================================
Changes filesystem permissions.
`$file` string Required Path to the file. `$mode` int|false Optional The permissions as octal number, usually 0644 for files, 0755 for directories. Default: `false`
`$recursive` bool Optional If set to true, changes file permissions recursively.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function chmod( $file, $mode = false, $recursive = false ) {
if ( ! $mode ) {
if ( $this->is_file( $file ) ) {
$mode = FS_CHMOD_FILE;
} elseif ( $this->is_dir( $file ) ) {
$mode = FS_CHMOD_DIR;
} else {
return false;
}
}
if ( ! $recursive || ! $this->is_dir( $file ) ) {
return chmod( $file, $mode );
}
// Is a directory, and we want recursive.
$file = trailingslashit( $file );
$filelist = $this->dirlist( $file );
foreach ( (array) $filelist as $filename => $filemeta ) {
$this->chmod( $file . $filename, $mode, $recursive );
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-direct.php | Gets details for files in a directory or a specific file. |
| [WP\_Filesystem\_Direct::is\_file()](is_file) wp-admin/includes/class-wp-filesystem-direct.php | Checks if resource is a file. |
| [WP\_Filesystem\_Direct::is\_dir()](is_dir) wp-admin/includes/class-wp-filesystem-direct.php | Checks if resource is a directory. |
| [WP\_Filesystem\_Direct::chmod()](chmod) wp-admin/includes/class-wp-filesystem-direct.php | Changes filesystem permissions. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::mkdir()](mkdir) wp-admin/includes/class-wp-filesystem-direct.php | Creates a directory. |
| [WP\_Filesystem\_Direct::copy()](copy) wp-admin/includes/class-wp-filesystem-direct.php | Copies a file. |
| [WP\_Filesystem\_Direct::put\_contents()](put_contents) wp-admin/includes/class-wp-filesystem-direct.php | Writes a string to a file. |
| [WP\_Filesystem\_Direct::chmod()](chmod) wp-admin/includes/class-wp-filesystem-direct.php | Changes filesystem permissions. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::size( string $file ): int|false WP\_Filesystem\_Direct::size( string $file ): int|false
=======================================================
Gets the file size (in bytes).
`$file` string Required Path to file. int|false Size of the file in bytes on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function size( $file ) {
return @filesize( $file );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-direct.php | Gets details for files in a directory or a specific file. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::getchmod( string $file ): string WP\_Filesystem\_Direct::getchmod( string $file ): string
========================================================
Gets the permissions of the specified file or filepath in their octal format.
FIXME does not handle errors in fileperms()
`$file` string Required Path to the file. string Mode of the file (the last 3 digits).
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function getchmod( $file ) {
return substr( decoct( @fileperms( $file ) ), -3 );
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::exists( string $path ): bool WP\_Filesystem\_Direct::exists( string $path ): bool
====================================================
Checks if a file or directory exists.
`$path` string Required Path to file or directory. bool Whether $path exists or not.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function exists( $path ) {
return @file_exists( $path );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::copy()](copy) wp-admin/includes/class-wp-filesystem-direct.php | Copies a file. |
| [WP\_Filesystem\_Direct::move()](move) wp-admin/includes/class-wp-filesystem-direct.php | Moves a file. |
| [WP\_Filesystem\_Direct::chgrp()](chgrp) wp-admin/includes/class-wp-filesystem-direct.php | Changes the file group. |
| [WP\_Filesystem\_Direct::chown()](chown) wp-admin/includes/class-wp-filesystem-direct.php | Changes the owner of a file or directory. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::chdir( string $dir ): bool WP\_Filesystem\_Direct::chdir( string $dir ): bool
==================================================
Changes current directory.
`$dir` string Required The new current directory. bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function chdir( $dir ) {
return @chdir( $dir );
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::rmdir( string $path, bool $recursive = false ): bool WP\_Filesystem\_Direct::rmdir( string $path, bool $recursive = false ): bool
============================================================================
Deletes a directory.
`$path` string Required Path to directory. `$recursive` bool Optional Whether to recursively remove files/directories.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function rmdir( $path, $recursive = false ) {
return $this->delete( $path, $recursive );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::delete()](delete) wp-admin/includes/class-wp-filesystem-direct.php | Deletes a file or directory. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::get_contents( string $file ): string|false WP\_Filesystem\_Direct::get\_contents( string $file ): string|false
===================================================================
Reads entire file into a string.
`$file` string Required Name of the file to read. string|false Read data on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function get_contents( $file ) {
return @file_get_contents( $file );
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::chown( string $file, string|int $owner, bool $recursive = false ): bool WP\_Filesystem\_Direct::chown( string $file, string|int $owner, bool $recursive = false ): bool
===============================================================================================
Changes the owner of a file or directory.
`$file` string Required Path to the file or directory. `$owner` string|int Required A user name or number. `$recursive` bool Optional If set to true, changes file owner recursively.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function chown( $file, $owner, $recursive = false ) {
if ( ! $this->exists( $file ) ) {
return false;
}
if ( ! $recursive ) {
return chown( $file, $owner );
}
if ( ! $this->is_dir( $file ) ) {
return chown( $file, $owner );
}
// Is a directory, and we want recursive.
$filelist = $this->dirlist( $file );
foreach ( $filelist as $filename ) {
$this->chown( $file . '/' . $filename, $owner, $recursive );
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-direct.php | Gets details for files in a directory or a specific file. |
| [WP\_Filesystem\_Direct::exists()](exists) wp-admin/includes/class-wp-filesystem-direct.php | Checks if a file or directory exists. |
| [WP\_Filesystem\_Direct::is\_dir()](is_dir) wp-admin/includes/class-wp-filesystem-direct.php | Checks if resource is a directory. |
| [WP\_Filesystem\_Direct::chown()](chown) wp-admin/includes/class-wp-filesystem-direct.php | Changes the owner of a file or directory. |
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::mkdir()](mkdir) wp-admin/includes/class-wp-filesystem-direct.php | Creates a directory. |
| [WP\_Filesystem\_Direct::chown()](chown) wp-admin/includes/class-wp-filesystem-direct.php | Changes the owner of a file or directory. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress WP_Filesystem_Direct::is_writable( string $path ): bool WP\_Filesystem\_Direct::is\_writable( string $path ): bool
==========================================================
Checks if a file or directory is writable.
`$path` string Required Path to file or directory. bool Whether $path is writable.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function is_writable( $path ) {
return @is_writable( $path );
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::group( string $file ): string|false WP\_Filesystem\_Direct::group( string $file ): string|false
===========================================================
Gets the file’s group.
`$file` string Required Path to the file. string|false The group on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function group( $file ) {
$gid = @filegroup( $file );
if ( ! $gid ) {
return false;
}
if ( ! function_exists( 'posix_getgrgid' ) ) {
return $gid;
}
$grouparray = posix_getgrgid( $gid );
if ( ! $grouparray ) {
return false;
}
return $grouparray['name'];
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-direct.php | Gets details for files in a directory or a specific file. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::chgrp( string $file, string|int $group, bool $recursive = false ): bool WP\_Filesystem\_Direct::chgrp( string $file, string|int $group, bool $recursive = false ): bool
===============================================================================================
Changes the file group.
`$file` string Required Path to the file. `$group` string|int Required A group name or number. `$recursive` bool Optional If set to true, changes file group recursively.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function chgrp( $file, $group, $recursive = false ) {
if ( ! $this->exists( $file ) ) {
return false;
}
if ( ! $recursive ) {
return chgrp( $file, $group );
}
if ( ! $this->is_dir( $file ) ) {
return chgrp( $file, $group );
}
// Is a directory, and we want recursive.
$file = trailingslashit( $file );
$filelist = $this->dirlist( $file );
foreach ( $filelist as $filename ) {
$this->chgrp( $file . $filename, $group, $recursive );
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-direct.php | Gets details for files in a directory or a specific file. |
| [WP\_Filesystem\_Direct::exists()](exists) wp-admin/includes/class-wp-filesystem-direct.php | Checks if a file or directory exists. |
| [WP\_Filesystem\_Direct::is\_dir()](is_dir) wp-admin/includes/class-wp-filesystem-direct.php | Checks if resource is a directory. |
| [WP\_Filesystem\_Direct::chgrp()](chgrp) wp-admin/includes/class-wp-filesystem-direct.php | Changes the file group. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::mkdir()](mkdir) wp-admin/includes/class-wp-filesystem-direct.php | Creates a directory. |
| [WP\_Filesystem\_Direct::chgrp()](chgrp) wp-admin/includes/class-wp-filesystem-direct.php | Changes the file group. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::put_contents( string $file, string $contents, int|false $mode = false ): bool WP\_Filesystem\_Direct::put\_contents( string $file, string $contents, int|false $mode = false ): bool
======================================================================================================
Writes a string to a file.
`$file` string Required Remote path to the file where to write the data. `$contents` string Required The data to write. `$mode` int|false Optional The file permissions as octal number, usually 0644.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function put_contents( $file, $contents, $mode = false ) {
$fp = @fopen( $file, 'wb' );
if ( ! $fp ) {
return false;
}
mbstring_binary_safe_encoding();
$data_length = strlen( $contents );
$bytes_written = fwrite( $fp, $contents );
reset_mbstring_encoding();
fclose( $fp );
if ( $data_length !== $bytes_written ) {
return false;
}
$this->chmod( $file, $mode );
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::chmod()](chmod) wp-admin/includes/class-wp-filesystem-direct.php | Changes filesystem permissions. |
| [mbstring\_binary\_safe\_encoding()](../../functions/mbstring_binary_safe_encoding) wp-includes/functions.php | Sets the mbstring internal encoding to a binary safe encoding when func\_overload is enabled. |
| [reset\_mbstring\_encoding()](../../functions/reset_mbstring_encoding) wp-includes/functions.php | Resets the mbstring internal encoding to a users previously set encoding. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::is_dir( string $path ): bool WP\_Filesystem\_Direct::is\_dir( string $path ): bool
=====================================================
Checks if resource is a directory.
`$path` string Required Directory path. bool Whether $path is a directory.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function is_dir( $path ) {
return @is_dir( $path );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-direct.php | Gets details for files in a directory or a specific file. |
| [WP\_Filesystem\_Direct::delete()](delete) wp-admin/includes/class-wp-filesystem-direct.php | Deletes a file or directory. |
| [WP\_Filesystem\_Direct::chgrp()](chgrp) wp-admin/includes/class-wp-filesystem-direct.php | Changes the file group. |
| [WP\_Filesystem\_Direct::chmod()](chmod) wp-admin/includes/class-wp-filesystem-direct.php | Changes filesystem permissions. |
| [WP\_Filesystem\_Direct::chown()](chown) wp-admin/includes/class-wp-filesystem-direct.php | Changes the owner of a file or directory. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::is_readable( string $file ): bool WP\_Filesystem\_Direct::is\_readable( string $file ): bool
==========================================================
Checks if a file is readable.
`$file` string Required Path to file. bool Whether $file is readable.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function is_readable( $file ) {
return @is_readable( $file );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-direct.php | Gets details for files in a directory or a specific file. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::is_file( string $file ): bool WP\_Filesystem\_Direct::is\_file( string $file ): bool
======================================================
Checks if resource is a file.
`$file` string Required File path. bool Whether $file is a file.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function is_file( $file ) {
return @is_file( $file );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-direct.php | Gets details for files in a directory or a specific file. |
| [WP\_Filesystem\_Direct::delete()](delete) wp-admin/includes/class-wp-filesystem-direct.php | Deletes a file or directory. |
| [WP\_Filesystem\_Direct::chmod()](chmod) wp-admin/includes/class-wp-filesystem-direct.php | Changes filesystem permissions. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::mtime( string $file ): int|false WP\_Filesystem\_Direct::mtime( string $file ): int|false
========================================================
Gets the file modification time.
`$file` string Required Path to file. int|false Unix timestamp representing modification time, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function mtime( $file ) {
return @filemtime( $file );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-direct.php | Gets details for files in a directory or a specific file. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::mkdir( string $path, int|false $chmod = false, string|int|false $chown = false, string|int|false $chgrp = false ): bool WP\_Filesystem\_Direct::mkdir( string $path, int|false $chmod = false, string|int|false $chown = false, string|int|false $chgrp = false ): bool
===============================================================================================================================================
Creates a directory.
`$path` string Required Path for new directory. `$chmod` int|false Optional The permissions as octal number (or false to skip chmod).
Default: `false`
`$chown` string|int|false Optional A user name or number (or false to skip chown).
Default: `false`
`$chgrp` string|int|false Optional A group name or number (or false to skip chgrp).
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) {
// Safe mode fails with a trailing slash under certain PHP versions.
$path = untrailingslashit( $path );
if ( empty( $path ) ) {
return false;
}
if ( ! $chmod ) {
$chmod = FS_CHMOD_DIR;
}
if ( ! @mkdir( $path ) ) {
return false;
}
$this->chmod( $path, $chmod );
if ( $chown ) {
$this->chown( $path, $chown );
}
if ( $chgrp ) {
$this->chgrp( $path, $chgrp );
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::chmod()](chmod) wp-admin/includes/class-wp-filesystem-direct.php | Changes filesystem permissions. |
| [WP\_Filesystem\_Direct::chown()](chown) wp-admin/includes/class-wp-filesystem-direct.php | Changes the owner of a file or directory. |
| [WP\_Filesystem\_Direct::chgrp()](chgrp) wp-admin/includes/class-wp-filesystem-direct.php | Changes the file group. |
| [untrailingslashit()](../../functions/untrailingslashit) wp-includes/formatting.php | Removes trailing forward slashes and backslashes if they exist. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::owner( string $file ): string|false WP\_Filesystem\_Direct::owner( string $file ): string|false
===========================================================
Gets the file owner.
`$file` string Required Path to the file. string|false Username of the owner on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function owner( $file ) {
$owneruid = @fileowner( $file );
if ( ! $owneruid ) {
return false;
}
if ( ! function_exists( 'posix_getpwuid' ) ) {
return $owneruid;
}
$ownerarray = posix_getpwuid( $owneruid );
if ( ! $ownerarray ) {
return false;
}
return $ownerarray['name'];
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-direct.php | Gets details for files in a directory or a specific file. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::cwd(): string|false WP\_Filesystem\_Direct::cwd(): string|false
===========================================
Gets the current working directory.
string|false The current working directory on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function cwd() {
return getcwd();
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::__construct( mixed $arg ) WP\_Filesystem\_Direct::\_\_construct( mixed $arg )
===================================================
Constructor.
`$arg` mixed Required Not used. File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function __construct( $arg ) {
$this->method = 'direct';
$this->errors = new WP_Error();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::copy( string $source, string $destination, bool $overwrite = false, int|false $mode = false ): bool WP\_Filesystem\_Direct::copy( string $source, string $destination, bool $overwrite = false, int|false $mode = false ): bool
===========================================================================================================================
Copies a file.
`$source` string Required Path to the source file. `$destination` string Required Path to the destination file. `$overwrite` bool Optional Whether to overwrite the destination file if it exists.
Default: `false`
`$mode` int|false Optional The permissions as octal number, usually 0644 for files, 0755 for dirs. Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function copy( $source, $destination, $overwrite = false, $mode = false ) {
if ( ! $overwrite && $this->exists( $destination ) ) {
return false;
}
$rtval = copy( $source, $destination );
if ( $mode ) {
$this->chmod( $destination, $mode );
}
return $rtval;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::exists()](exists) wp-admin/includes/class-wp-filesystem-direct.php | Checks if a file or directory exists. |
| [WP\_Filesystem\_Direct::chmod()](chmod) wp-admin/includes/class-wp-filesystem-direct.php | Changes filesystem permissions. |
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::move()](move) wp-admin/includes/class-wp-filesystem-direct.php | Moves a file. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::get_contents_array( string $file ): array|false WP\_Filesystem\_Direct::get\_contents\_array( string $file ): array|false
=========================================================================
Reads entire file into an array.
`$file` string Required Path to the file. array|false File contents in an array on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function get_contents_array( $file ) {
return @file( $file );
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::dirlist( string $path, bool $include_hidden = true, bool $recursive = false ): array|false WP\_Filesystem\_Direct::dirlist( string $path, bool $include\_hidden = true, bool $recursive = false ): array|false
===================================================================================================================
Gets details for files in a directory or a specific file.
`$path` string Required Path to directory or file. `$include_hidden` bool Optional Whether to include details of hidden ("." prefixed) files.
Default: `true`
`$recursive` bool Optional Whether to recursively include file details in nested directories.
Default: `false`
array|false Array of files. False if unable to list directory contents.
* `name`stringName of the file or directory.
* `perms`string\*nix representation of permissions.
* `permsn`stringOctal representation of permissions.
* `owner`stringOwner name or ID.
* `size`intSize of file in bytes.
* `lastmodunix`intLast modified unix timestamp.
* `lastmod`mixedLast modified month (3 letter) and day (without leading 0).
* `time`intLast modified time.
* `type`stringType of resource. `'f'` for file, `'d'` for directory.
* `files`mixedIf a directory and `$recursive` is true, contains another array of files.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function dirlist( $path, $include_hidden = true, $recursive = false ) {
if ( $this->is_file( $path ) ) {
$limit_file = basename( $path );
$path = dirname( $path );
} else {
$limit_file = false;
}
if ( ! $this->is_dir( $path ) || ! $this->is_readable( $path ) ) {
return false;
}
$dir = dir( $path );
if ( ! $dir ) {
return false;
}
$ret = array();
while ( false !== ( $entry = $dir->read() ) ) {
$struc = array();
$struc['name'] = $entry;
if ( '.' === $struc['name'] || '..' === $struc['name'] ) {
continue;
}
if ( ! $include_hidden && '.' === $struc['name'][0] ) {
continue;
}
if ( $limit_file && $struc['name'] !== $limit_file ) {
continue;
}
$struc['perms'] = $this->gethchmod( $path . '/' . $entry );
$struc['permsn'] = $this->getnumchmodfromh( $struc['perms'] );
$struc['number'] = false;
$struc['owner'] = $this->owner( $path . '/' . $entry );
$struc['group'] = $this->group( $path . '/' . $entry );
$struc['size'] = $this->size( $path . '/' . $entry );
$struc['lastmodunix'] = $this->mtime( $path . '/' . $entry );
$struc['lastmod'] = gmdate( 'M j', $struc['lastmodunix'] );
$struc['time'] = gmdate( 'h:i:s', $struc['lastmodunix'] );
$struc['type'] = $this->is_dir( $path . '/' . $entry ) ? 'd' : 'f';
if ( 'd' === $struc['type'] ) {
if ( $recursive ) {
$struc['files'] = $this->dirlist( $path . '/' . $struc['name'], $include_hidden, $recursive );
} else {
$struc['files'] = array();
}
}
$ret[ $struc['name'] ] = $struc;
}
$dir->close();
unset( $dir );
return $ret;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-direct.php | Gets details for files in a directory or a specific file. |
| [WP\_Filesystem\_Direct::is\_file()](is_file) wp-admin/includes/class-wp-filesystem-direct.php | Checks if resource is a file. |
| [WP\_Filesystem\_Direct::is\_dir()](is_dir) wp-admin/includes/class-wp-filesystem-direct.php | Checks if resource is a directory. |
| [WP\_Filesystem\_Direct::is\_readable()](is_readable) wp-admin/includes/class-wp-filesystem-direct.php | Checks if a file is readable. |
| [WP\_Filesystem\_Direct::owner()](owner) wp-admin/includes/class-wp-filesystem-direct.php | Gets the file owner. |
| [WP\_Filesystem\_Direct::group()](group) wp-admin/includes/class-wp-filesystem-direct.php | Gets the file’s group. |
| [WP\_Filesystem\_Direct::size()](size) wp-admin/includes/class-wp-filesystem-direct.php | Gets the file size (in bytes). |
| [WP\_Filesystem\_Direct::mtime()](mtime) wp-admin/includes/class-wp-filesystem-direct.php | Gets the file modification time. |
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-direct.php | Gets details for files in a directory or a specific file. |
| [WP\_Filesystem\_Direct::delete()](delete) wp-admin/includes/class-wp-filesystem-direct.php | Deletes a file or directory. |
| [WP\_Filesystem\_Direct::chgrp()](chgrp) wp-admin/includes/class-wp-filesystem-direct.php | Changes the file group. |
| [WP\_Filesystem\_Direct::chmod()](chmod) wp-admin/includes/class-wp-filesystem-direct.php | Changes filesystem permissions. |
| [WP\_Filesystem\_Direct::chown()](chown) wp-admin/includes/class-wp-filesystem-direct.php | Changes the owner of a file or directory. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress WP_Filesystem_Direct::move( string $source, string $destination, bool $overwrite = false ): bool WP\_Filesystem\_Direct::move( string $source, string $destination, bool $overwrite = false ): bool
==================================================================================================
Moves a file.
`$source` string Required Path to the source file. `$destination` string Required Path to the destination file. `$overwrite` bool Optional Whether to overwrite the destination file if it exists.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function move( $source, $destination, $overwrite = false ) {
if ( ! $overwrite && $this->exists( $destination ) ) {
return false;
}
// Try using rename first. if that fails (for example, source is read only) try copy.
if ( @rename( $source, $destination ) ) {
return true;
}
if ( $this->copy( $source, $destination, $overwrite ) && $this->exists( $destination ) ) {
$this->delete( $source );
return true;
} else {
return false;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::exists()](exists) wp-admin/includes/class-wp-filesystem-direct.php | Checks if a file or directory exists. |
| [WP\_Filesystem\_Direct::copy()](copy) wp-admin/includes/class-wp-filesystem-direct.php | Copies a file. |
| [WP\_Filesystem\_Direct::delete()](delete) wp-admin/includes/class-wp-filesystem-direct.php | Deletes a file or directory. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::atime( string $file ): int|false WP\_Filesystem\_Direct::atime( string $file ): int|false
========================================================
Gets the file’s last access time.
`$file` string Required Path to file. int|false Unix timestamp representing last access time, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function atime( $file ) {
return @fileatime( $file );
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::touch( string $file, int $time, int $atime ): bool WP\_Filesystem\_Direct::touch( string $file, int $time, int $atime ): bool
==========================================================================
Sets the access and modification times of a file.
Note: If $file doesn’t exist, it will be created.
`$file` string Required Path to file. `$time` int Optional Modified time to set for file.
Default 0. `$atime` int Optional Access time to set for file.
Default 0. bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function touch( $file, $time = 0, $atime = 0 ) {
if ( 0 === $time ) {
$time = time();
}
if ( 0 === $atime ) {
$atime = time();
}
return touch( $file, $time, $atime );
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Direct::delete( string $file, bool $recursive = false, string|false $type = false ): bool WP\_Filesystem\_Direct::delete( string $file, bool $recursive = false, string|false $type = false ): bool
=========================================================================================================
Deletes a file or directory.
`$file` string Required Path to the file or directory. `$recursive` bool Optional If set to true, deletes files and folders recursively.
Default: `false`
`$type` string|false Optional Type of resource. `'f'` for file, `'d'` for directory.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/)
```
public function delete( $file, $recursive = false, $type = false ) {
if ( empty( $file ) ) {
// Some filesystems report this as /, which can cause non-expected recursive deletion of all files in the filesystem.
return false;
}
$file = str_replace( '\\', '/', $file ); // For Win32, occasional problems deleting files otherwise.
if ( 'f' === $type || $this->is_file( $file ) ) {
return @unlink( $file );
}
if ( ! $recursive && $this->is_dir( $file ) ) {
return @rmdir( $file );
}
// At this point it's a folder, and we're in recursive mode.
$file = trailingslashit( $file );
$filelist = $this->dirlist( $file, true );
$retval = true;
if ( is_array( $filelist ) ) {
foreach ( $filelist as $filename => $fileinfo ) {
if ( ! $this->delete( $file . $filename, $recursive, $fileinfo['type'] ) ) {
$retval = false;
}
}
}
if ( file_exists( $file ) && ! @rmdir( $file ) ) {
$retval = false;
}
return $retval;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-direct.php | Gets details for files in a directory or a specific file. |
| [WP\_Filesystem\_Direct::is\_file()](is_file) wp-admin/includes/class-wp-filesystem-direct.php | Checks if resource is a file. |
| [WP\_Filesystem\_Direct::is\_dir()](is_dir) wp-admin/includes/class-wp-filesystem-direct.php | Checks if resource is a directory. |
| [WP\_Filesystem\_Direct::delete()](delete) wp-admin/includes/class-wp-filesystem-direct.php | Deletes a file or directory. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Direct::rmdir()](rmdir) wp-admin/includes/class-wp-filesystem-direct.php | Deletes a directory. |
| [WP\_Filesystem\_Direct::move()](move) wp-admin/includes/class-wp-filesystem-direct.php | Moves a file. |
| [WP\_Filesystem\_Direct::delete()](delete) wp-admin/includes/class-wp-filesystem-direct.php | Deletes a file or directory. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_User_Search::prepare_vars_for_template_usage() WP\_User\_Search::prepare\_vars\_for\_template\_usage()
=======================================================
Prepares variables for use in templates.
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function prepare_vars_for_template_usage() {}
```
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_User_Search::do_paging() WP\_User\_Search::do\_paging()
==============================
Handles paging for the user search query.
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
public function do_paging() {
if ( $this->total_users_for_query > $this->users_per_page ) { // Have to page the results.
$args = array();
if ( ! empty($this->search_term) )
$args['usersearch'] = urlencode($this->search_term);
if ( ! empty($this->role) )
$args['role'] = urlencode($this->role);
$this->paging_text = paginate_links( array(
'total' => ceil($this->total_users_for_query / $this->users_per_page),
'current' => $this->page,
'base' => 'users.php?%_%',
'format' => 'userspage=%#%',
'add_args' => $args
) );
if ( $this->paging_text ) {
$this->paging_text = sprintf(
/* translators: 1: Starting number of users on the current page, 2: Ending number of users, 3: Total number of users. */
'<span class="displaying-num">' . __( 'Displaying %1$s–%2$s of %3$s' ) . '</span>%s',
number_format_i18n( ( $this->page - 1 ) * $this->users_per_page + 1 ),
number_format_i18n( min( $this->page * $this->users_per_page, $this->total_users_for_query ) ),
number_format_i18n( $this->total_users_for_query ),
$this->paging_text
);
}
}
}
```
| Uses | Description |
| --- | --- |
| [paginate\_links()](../../functions/paginate_links) wp-includes/general-template.php | Retrieves paginated links for archive post pages. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| Used By | Description |
| --- | --- |
| [WP\_User\_Search::\_\_construct()](__construct) wp-admin/includes/deprecated.php | PHP5 Constructor – Sets up the object properties. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_User_Search::prepare_query() WP\_User\_Search::prepare\_query()
==================================
Prepares the user search query (legacy).
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
public function prepare_query() {
global $wpdb;
$this->first_user = ($this->page - 1) * $this->users_per_page;
$this->query_limit = $wpdb->prepare(" LIMIT %d, %d", $this->first_user, $this->users_per_page);
$this->query_orderby = ' ORDER BY user_login';
$search_sql = '';
if ( $this->search_term ) {
$searches = array();
$search_sql = 'AND (';
foreach ( array('user_login', 'user_nicename', 'user_email', 'user_url', 'display_name') as $col )
$searches[] = $wpdb->prepare( $col . ' LIKE %s', '%' . like_escape($this->search_term) . '%' );
$search_sql .= implode(' OR ', $searches);
$search_sql .= ')';
}
$this->query_from = " FROM $wpdb->users";
$this->query_where = " WHERE 1=1 $search_sql";
if ( $this->role ) {
$this->query_from .= " INNER JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id";
$this->query_where .= $wpdb->prepare(" AND $wpdb->usermeta.meta_key = '{$wpdb->prefix}capabilities' AND $wpdb->usermeta.meta_value LIKE %s", '%' . $this->role . '%');
} elseif ( is_multisite() ) {
$level_key = $wpdb->prefix . 'capabilities'; // WPMU site admins don't have user_levels.
$this->query_from .= ", $wpdb->usermeta";
$this->query_where .= " AND $wpdb->users.ID = $wpdb->usermeta.user_id AND meta_key = '{$level_key}'";
}
do_action_ref_array( 'pre_user_search', array( &$this ) );
}
```
| Uses | Description |
| --- | --- |
| [like\_escape()](../../functions/like_escape) wp-includes/deprecated.php | Formerly used to escape strings before searching the DB. It was poorly documented and never worked as described. |
| [do\_action\_ref\_array()](../../functions/do_action_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook, specifying arguments in an array. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_User\_Search::\_\_construct()](__construct) wp-admin/includes/deprecated.php | PHP5 Constructor – Sets up the object properties. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_User_Search::results_are_paged(): bool WP\_User\_Search::results\_are\_paged(): bool
=============================================
Whether paging is enabled.
* [do\_paging()](../../functions/do_paging): Builds paging text.
bool
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function results_are_paged() {
if ( $this->paging_text )
return true;
return false;
}
```
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_User_Search::get_results(): array WP\_User\_Search::get\_results(): array
=======================================
Retrieves the user search query results.
array
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
public function get_results() {
return (array) $this->results;
}
```
| Used By | Description |
| --- | --- |
| [WP\_MS\_Users\_List\_Table::prepare\_items()](../wp_ms_users_list_table/prepare_items) wp-admin/includes/class-wp-ms-users-list-table.php | |
| [WP\_Users\_List\_Table::prepare\_items()](../wp_users_list_table/prepare_items) wp-admin/includes/class-wp-users-list-table.php | Prepare the users list for display. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_User_Search::is_search(): bool WP\_User\_Search::is\_search(): bool
====================================
Whether there are search terms.
bool
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function is_search() {
if ( $this->search_term )
return true;
return false;
}
```
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_User_Search::WP_User_Search( string $search_term = '', int $page = '', string $role = '' ): WP_User_Search WP\_User\_Search::WP\_User\_Search( string $search\_term = '', int $page = '', string $role = '' ): WP\_User\_Search
====================================================================================================================
PHP4 Constructor – Sets up the object properties.
`$search_term` string Optional Search terms string. Default: `''`
`$page` int Optional Page ID. Default: `''`
`$role` string Optional Role name. Default: `''`
[WP\_User\_Search](../wp_user_search)
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
public function WP_User_Search( $search_term = '', $page = '', $role = '' ) {
self::__construct( $search_term, $page, $role );
}
```
| Uses | Description |
| --- | --- |
| [WP\_User\_Search::\_\_construct()](__construct) wp-admin/includes/deprecated.php | PHP5 Constructor – Sets up the object properties. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_User_Search::query() WP\_User\_Search::query()
=========================
Executes the user search query.
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
public function query() {
global $wpdb;
$this->results = $wpdb->get_col("SELECT DISTINCT($wpdb->users.ID)" . $this->query_from . $this->query_where . $this->query_orderby . $this->query_limit);
if ( $this->results )
$this->total_users_for_query = $wpdb->get_var("SELECT COUNT(DISTINCT($wpdb->users.ID))" . $this->query_from . $this->query_where); // No limit.
else
$this->search_errors = new WP_Error('no_matching_users_found', __('No users found.'));
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_col()](../wpdb/get_col) wp-includes/class-wpdb.php | Retrieves one column from the database. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wpdb::get\_var()](../wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_User\_Search::\_\_construct()](__construct) wp-admin/includes/deprecated.php | PHP5 Constructor – Sets up the object properties. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_User_Search::page_links() WP\_User\_Search::page\_links()
===============================
Displaying paging text.
* [do\_paging()](../../functions/do_paging): Builds paging text.
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function page_links() {
echo $this->paging_text;
}
```
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_User_Search::__construct( string $search_term = '', int $page = '', string $role = '' ): WP_User_Search WP\_User\_Search::\_\_construct( string $search\_term = '', int $page = '', string $role = '' ): WP\_User\_Search
=================================================================================================================
PHP5 Constructor – Sets up the object properties.
`$search_term` string Optional Search terms string. Default: `''`
`$page` int Optional Page ID. Default: `''`
`$role` string Optional Role name. Default: `''`
[WP\_User\_Search](../wp_user_search)
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function __construct( $search_term = '', $page = '', $role = '' ) {
_deprecated_function( __FUNCTION__, '3.1.0', 'WP_User_Query' );
$this->search_term = wp_unslash( $search_term );
$this->raw_page = ( '' == $page ) ? false : (int) $page;
$this->page = ( '' == $page ) ? 1 : (int) $page;
$this->role = $role;
$this->prepare_query();
$this->query();
$this->do_paging();
}
```
| Uses | Description |
| --- | --- |
| [WP\_User\_Search::prepare\_query()](prepare_query) wp-admin/includes/deprecated.php | Prepares the user search query (legacy). |
| [WP\_User\_Search::query()](query) wp-admin/includes/deprecated.php | Executes the user search query. |
| [WP\_User\_Search::do\_paging()](do_paging) wp-admin/includes/deprecated.php | Handles paging for the user search query. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Used By | Description |
| --- | --- |
| [WP\_User\_Search::WP\_User\_Search()](wp_user_search) wp-admin/includes/deprecated.php | PHP4 Constructor – Sets up the object properties. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_REST_Block_Pattern_Categories_Controller::prepare_item_for_response( array $item, WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Block\_Pattern\_Categories\_Controller::prepare\_item\_for\_response( array $item, WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=======================================================================================================================================================
Prepare a raw block pattern category before it gets output in a REST API response.
`$item` array Required Raw category as registered, before any changes. `$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php/)
```
public function prepare_item_for_response( $item, $request ) {
$fields = $this->get_fields_for_response( $request );
$keys = array( 'name', 'label' );
$data = array();
foreach ( $keys as $key ) {
if ( rest_is_field_included( $key, $fields ) ) {
$data[ $key ] = $item[ $key ];
}
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
return rest_ensure_response( $data );
}
```
| Uses | Description |
| --- | --- |
| [rest\_is\_field\_included()](../../functions/rest_is_field_included) wp-includes/rest-api.php | Given an array of fields to include in a response, some of which may be `nested.fields`, determine whether the provided field should be included in the response body. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Block\_Pattern\_Categories\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php | Retrieves all block pattern categories. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Block_Pattern_Categories_Controller::get_items( WP_REST_Request $request ): WP_Error|WP_REST_Response WP\_REST\_Block\_Pattern\_Categories\_Controller::get\_items( WP\_REST\_Request $request ): WP\_Error|WP\_REST\_Response
========================================================================================================================
Retrieves all block pattern categories.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_Error](../wp_error)|[WP\_REST\_Response](../wp_rest_response) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php/)
```
public function get_items( $request ) {
$response = array();
$categories = WP_Block_Pattern_Categories_Registry::get_instance()->get_all_registered();
foreach ( $categories as $category ) {
$prepared_category = $this->prepare_item_for_response( $category, $request );
$response[] = $this->prepare_response_for_collection( $prepared_category );
}
return rest_ensure_response( $response );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Block\_Pattern\_Categories\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php | Prepare a raw block pattern category before it gets output in a REST API response. |
| [WP\_Block\_Pattern\_Categories\_Registry::get\_instance()](../wp_block_pattern_categories_registry/get_instance) wp-includes/class-wp-block-pattern-categories-registry.php | Utility method to retrieve the main instance of the class. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_REST_Block_Pattern_Categories_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Block\_Pattern\_Categories\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
==============================================================================================================================
Checks whether a given request has permission to read block patterns.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php/)
```
public function get_items_permissions_check( $request ) {
if ( current_user_can( 'edit_posts' ) ) {
return true;
}
foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
if ( current_user_can( $post_type->cap->edit_posts ) ) {
return true;
}
}
return new WP_Error(
'rest_cannot_view',
__( 'Sorry, you are not allowed to view the registered block pattern categories.' ),
array( 'status' => rest_authorization_required_code() )
);
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_REST_Block_Pattern_Categories_Controller::register_routes() WP\_REST\_Block\_Pattern\_Categories\_Controller::register\_routes()
====================================================================
Registers the routes for the objects of the controller.
File: `wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php/)
```
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base,
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [register\_rest\_route()](../../functions/register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_REST_Block_Pattern_Categories_Controller::__construct() WP\_REST\_Block\_Pattern\_Categories\_Controller::\_\_construct()
=================================================================
Constructs the controller.
File: `wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php/)
```
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'block-patterns/categories';
}
```
| Used By | Description |
| --- | --- |
| [create\_initial\_rest\_routes()](../../functions/create_initial_rest_routes) wp-includes/rest-api.php | Registers default REST API routes. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_REST_Block_Pattern_Categories_Controller::get_item_schema(): array WP\_REST\_Block\_Pattern\_Categories\_Controller::get\_item\_schema(): array
============================================================================
Retrieves the block pattern category schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php/)
```
public function get_item_schema() {
$schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'block-pattern-category',
'type' => 'object',
'properties' => array(
'name' => array(
'description' => __( 'The category name.' ),
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'label' => array(
'description' => __( 'The category label, in human readable format.' ),
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
),
);
return $this->add_additional_fields_schema( $schema );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_HTTP_Requests_Response::to_array(): array WP\_HTTP\_Requests\_Response::to\_array(): array
================================================
Converts the object to a [WP\_Http](../wp_http) response array.
array [WP\_Http](../wp_http) response array, per [WP\_Http::request()](../wp_http/request).
File: `wp-includes/class-wp-http-requests-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-response.php/)
```
public function to_array() {
return array(
'headers' => $this->get_headers(),
'body' => $this->get_data(),
'response' => array(
'code' => $this->get_status(),
'message' => get_status_header_desc( $this->get_status() ),
),
'cookies' => $this->get_cookies(),
'filename' => $this->filename,
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_HTTP\_Requests\_Response::get\_cookies()](get_cookies) wp-includes/class-wp-http-requests-response.php | Retrieves cookies from the response. |
| [WP\_HTTP\_Requests\_Response::get\_headers()](get_headers) wp-includes/class-wp-http-requests-response.php | Retrieves headers associated with the response. |
| [WP\_HTTP\_Requests\_Response::get\_data()](get_data) wp-includes/class-wp-http-requests-response.php | Retrieves the response data. |
| [WP\_HTTP\_Requests\_Response::get\_status()](get_status) wp-includes/class-wp-http-requests-response.php | Retrieves the HTTP return code for the response. |
| [get\_status\_header\_desc()](../../functions/get_status_header_desc) wp-includes/functions.php | Retrieves the description for the HTTP status. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_HTTP_Requests_Response::get_response_object(): Requests_Response WP\_HTTP\_Requests\_Response::get\_response\_object(): Requests\_Response
=========================================================================
Retrieves the response object for the request.
[Requests\_Response](../requests_response) HTTP response.
File: `wp-includes/class-wp-http-requests-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-response.php/)
```
public function get_response_object() {
return $this->response;
}
```
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_HTTP_Requests_Response::set_data( string $data ) WP\_HTTP\_Requests\_Response::set\_data( string $data )
=======================================================
Sets the response data.
`$data` string Required Response data. File: `wp-includes/class-wp-http-requests-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-response.php/)
```
public function set_data( $data ) {
$this->response->body = $data;
}
```
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_HTTP_Requests_Response::set_status( int $code ) WP\_HTTP\_Requests\_Response::set\_status( int $code )
======================================================
Sets the 3-digit HTTP status code.
`$code` int Required HTTP status. File: `wp-includes/class-wp-http-requests-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-response.php/)
```
public function set_status( $code ) {
$this->response->status_code = absint( $code );
}
```
| Uses | Description |
| --- | --- |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_HTTP_Requests_Response::set_headers( array $headers ) WP\_HTTP\_Requests\_Response::set\_headers( array $headers )
============================================================
Sets all header values.
`$headers` array Required Map of header name to header value. File: `wp-includes/class-wp-http-requests-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-response.php/)
```
public function set_headers( $headers ) {
$this->response->headers = new Requests_Response_Headers( $headers );
}
```
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_HTTP_Requests_Response::get_status(): int WP\_HTTP\_Requests\_Response::get\_status(): int
================================================
Retrieves the HTTP return code for the response.
int The 3-digit HTTP status code.
File: `wp-includes/class-wp-http-requests-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-response.php/)
```
public function get_status() {
return $this->response->status_code;
}
```
| Used By | Description |
| --- | --- |
| [WP\_HTTP\_Requests\_Response::to\_array()](to_array) wp-includes/class-wp-http-requests-response.php | Converts the object to a [WP\_Http](../wp_http) response array. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_HTTP_Requests_Response::get_data(): string WP\_HTTP\_Requests\_Response::get\_data(): string
=================================================
Retrieves the response data.
string Response data.
File: `wp-includes/class-wp-http-requests-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-response.php/)
```
public function get_data() {
return $this->response->body;
}
```
| Used By | Description |
| --- | --- |
| [WP\_HTTP\_Requests\_Response::to\_array()](to_array) wp-includes/class-wp-http-requests-response.php | Converts the object to a [WP\_Http](../wp_http) response array. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_HTTP_Requests_Response::get_headers(): Requests_Utility_CaseInsensitiveDictionary WP\_HTTP\_Requests\_Response::get\_headers(): Requests\_Utility\_CaseInsensitiveDictionary
==========================================================================================
Retrieves headers associated with the response.
[Requests\_Utility\_CaseInsensitiveDictionary](../requests_utility_caseinsensitivedictionary) Map of header name to header value.
File: `wp-includes/class-wp-http-requests-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-response.php/)
```
public function get_headers() {
// Ensure headers remain case-insensitive.
$converted = new Requests_Utility_CaseInsensitiveDictionary();
foreach ( $this->response->headers->getAll() as $key => $value ) {
if ( count( $value ) === 1 ) {
$converted[ $key ] = $value[0];
} else {
$converted[ $key ] = $value;
}
}
return $converted;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Utility\_CaseInsensitiveDictionary::\_\_construct()](../requests_utility_caseinsensitivedictionary/__construct) wp-includes/Requests/Utility/CaseInsensitiveDictionary.php | Creates a case insensitive dictionary. |
| Used By | Description |
| --- | --- |
| [WP\_HTTP\_Requests\_Response::to\_array()](to_array) wp-includes/class-wp-http-requests-response.php | Converts the object to a [WP\_Http](../wp_http) response array. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_HTTP_Requests_Response::get_cookies(): WP_HTTP_Cookie[] WP\_HTTP\_Requests\_Response::get\_cookies(): WP\_HTTP\_Cookie[]
================================================================
Retrieves cookies from the response.
[WP\_HTTP\_Cookie](../wp_http_cookie)[] List of cookie objects.
File: `wp-includes/class-wp-http-requests-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-response.php/)
```
public function get_cookies() {
$cookies = array();
foreach ( $this->response->cookies as $cookie ) {
$cookies[] = new WP_Http_Cookie(
array(
'name' => $cookie->name,
'value' => urldecode( $cookie->value ),
'expires' => isset( $cookie->attributes['expires'] ) ? $cookie->attributes['expires'] : null,
'path' => isset( $cookie->attributes['path'] ) ? $cookie->attributes['path'] : null,
'domain' => isset( $cookie->attributes['domain'] ) ? $cookie->attributes['domain'] : null,
'host_only' => isset( $cookie->flags['host-only'] ) ? $cookie->flags['host-only'] : null,
)
);
}
return $cookies;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Http\_Cookie::\_\_construct()](../wp_http_cookie/__construct) wp-includes/class-wp-http-cookie.php | Sets up this cookie object. |
| Used By | Description |
| --- | --- |
| [WP\_HTTP\_Requests\_Response::to\_array()](to_array) wp-includes/class-wp-http-requests-response.php | Converts the object to a [WP\_Http](../wp_http) response array. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_HTTP_Requests_Response::__construct( Requests_Response $response, string $filename = '' ) WP\_HTTP\_Requests\_Response::\_\_construct( Requests\_Response $response, string $filename = '' )
==================================================================================================
Constructor.
`$response` [Requests\_Response](../requests_response) Required HTTP response. `$filename` string Optional File name. Default: `''`
File: `wp-includes/class-wp-http-requests-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-response.php/)
```
public function __construct( Requests_Response $response, $filename = '' ) {
$this->response = $response;
$this->filename = $filename;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Http::request()](../wp_http/request) wp-includes/class-wp-http.php | Send an HTTP request to a URI. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_HTTP_Requests_Response::header( string $key, string $value, bool $replace = true ) WP\_HTTP\_Requests\_Response::header( string $key, string $value, bool $replace = true )
========================================================================================
Sets a single HTTP header.
`$key` string Required Header name. `$value` string Required Header value. `$replace` bool Optional Whether to replace an existing header of the same name.
Default: `true`
File: `wp-includes/class-wp-http-requests-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-response.php/)
```
public function header( $key, $value, $replace = true ) {
if ( $replace ) {
unset( $this->response->headers[ $key ] );
}
$this->response->headers[ $key ] = $value;
}
```
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Section::json(): array WP\_Customize\_Nav\_Menu\_Section::json(): array
================================================
Get section parameters for JS.
array Exported parameters.
File: `wp-includes/customize/class-wp-customize-nav-menu-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-section.php/)
```
public function json() {
$exported = parent::json();
$exported['menu_id'] = (int) preg_replace( '/^nav_menu\[(-?\d+)\]/', '$1', $this->id );
return $exported;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Section::json()](../wp_customize_section/json) wp-includes/class-wp-customize-section.php | Gather the parameters passed to client JavaScript via JSON. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Selective_Refresh::handle_error( int $errno, string $errstr, string $errfile = null, int $errline = null ): true WP\_Customize\_Selective\_Refresh::handle\_error( int $errno, string $errstr, string $errfile = null, int $errline = null ): true
=================================================================================================================================
Handles PHP errors triggered during rendering the partials.
These errors will be relayed back to the client in the Ajax response.
`$errno` int Required Error number. `$errstr` string Required Error string. `$errfile` string Optional Error file. Default: `null`
`$errline` int Optional Error line. Default: `null`
true Always true.
File: `wp-includes/customize/class-wp-customize-selective-refresh.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-selective-refresh.php/)
```
public function handle_error( $errno, $errstr, $errfile = null, $errline = null ) {
$this->triggered_errors[] = array(
'partial' => $this->current_partial_id,
'error_number' => $errno,
'error_string' => $errstr,
'error_file' => $errfile,
'error_line' => $errline,
);
return true;
}
```
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Selective_Refresh::partials(): array WP\_Customize\_Selective\_Refresh::partials(): array
====================================================
Retrieves the registered partials.
array Partials.
File: `wp-includes/customize/class-wp-customize-selective-refresh.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-selective-refresh.php/)
```
public function partials() {
return $this->partials;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Selective\_Refresh::export\_preview\_data()](export_preview_data) wp-includes/customize/class-wp-customize-selective-refresh.php | Exports data in preview after it has finished rendering so that partials can be added at runtime. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Selective_Refresh::init_preview() WP\_Customize\_Selective\_Refresh::init\_preview()
==================================================
Initializes the Customizer preview.
File: `wp-includes/customize/class-wp-customize-selective-refresh.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-selective-refresh.php/)
```
public function init_preview() {
add_action( 'template_redirect', array( $this, 'handle_render_partials_request' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_preview_scripts' ) );
}
```
| Uses | Description |
| --- | --- |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Selective_Refresh::handle_render_partials_request() WP\_Customize\_Selective\_Refresh::handle\_render\_partials\_request()
======================================================================
Handles the Ajax request to return the rendered partials for the requested placements.
File: `wp-includes/customize/class-wp-customize-selective-refresh.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-selective-refresh.php/)
```
public function handle_render_partials_request() {
if ( ! $this->is_render_partials_request() ) {
return;
}
/*
* Note that is_customize_preview() returning true will entail that the
* user passed the 'customize' capability check and the nonce check, since
* WP_Customize_Manager::setup_theme() is where the previewing flag is set.
*/
if ( ! is_customize_preview() ) {
wp_send_json_error( 'expected_customize_preview', 403 );
} elseif ( ! isset( $_POST['partials'] ) ) {
wp_send_json_error( 'missing_partials', 400 );
}
// Ensure that doing selective refresh on 404 template doesn't result in fallback rendering behavior (full refreshes).
status_header( 200 );
$partials = json_decode( wp_unslash( $_POST['partials'] ), true );
if ( ! is_array( $partials ) ) {
wp_send_json_error( 'malformed_partials' );
}
$this->add_dynamic_partials( array_keys( $partials ) );
/**
* Fires immediately before partials are rendered.
*
* Plugins may do things like call wp_enqueue_scripts() and gather a list of the scripts
* and styles which may get enqueued in the response.
*
* @since 4.5.0
*
* @param WP_Customize_Selective_Refresh $refresh Selective refresh component.
* @param array $partials Placements' context data for the partials rendered in the request.
* The array is keyed by partial ID, with each item being an array of
* the placements' context data.
*/
do_action( 'customize_render_partials_before', $this, $partials );
set_error_handler( array( $this, 'handle_error' ), error_reporting() );
$contents = array();
foreach ( $partials as $partial_id => $container_contexts ) {
$this->current_partial_id = $partial_id;
if ( ! is_array( $container_contexts ) ) {
wp_send_json_error( 'malformed_container_contexts' );
}
$partial = $this->get_partial( $partial_id );
if ( ! $partial || ! $partial->check_capabilities() ) {
$contents[ $partial_id ] = null;
continue;
}
$contents[ $partial_id ] = array();
// @todo The array should include not only the contents, but also whether the container is included?
if ( empty( $container_contexts ) ) {
// Since there are no container contexts, render just once.
$contents[ $partial_id ][] = $partial->render( null );
} else {
foreach ( $container_contexts as $container_context ) {
$contents[ $partial_id ][] = $partial->render( $container_context );
}
}
}
$this->current_partial_id = null;
restore_error_handler();
/**
* Fires immediately after partials are rendered.
*
* Plugins may do things like call wp_footer() to scrape scripts output and return them
* via the {@see 'customize_render_partials_response'} filter.
*
* @since 4.5.0
*
* @param WP_Customize_Selective_Refresh $refresh Selective refresh component.
* @param array $partials Placements' context data for the partials rendered in the request.
* The array is keyed by partial ID, with each item being an array of
* the placements' context data.
*/
do_action( 'customize_render_partials_after', $this, $partials );
$response = array(
'contents' => $contents,
);
if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) {
$response['errors'] = $this->triggered_errors;
}
$setting_validities = $this->manager->validate_setting_values( $this->manager->unsanitized_post_values() );
$exported_setting_validities = array_map( array( $this->manager, 'prepare_setting_validity_for_js' ), $setting_validities );
$response['setting_validities'] = $exported_setting_validities;
/**
* Filters the response from rendering the partials.
*
* Plugins may use this filter to inject `$scripts` and `$styles`, which are dependencies
* for the partials being rendered. The response data will be available to the client via
* the `render-partials-response` JS event, so the client can then inject the scripts and
* styles into the DOM if they have not already been enqueued there.
*
* If plugins do this, they'll need to take care for any scripts that do `document.write()`
* and make sure that these are not injected, or else to override the function to no-op,
* or else the page will be destroyed.
*
* Plugins should be aware that `$scripts` and `$styles` may eventually be included by
* default in the response.
*
* @since 4.5.0
*
* @param array $response {
* Response.
*
* @type array $contents Associative array mapping a partial ID its corresponding array of contents
* for the containers requested.
* @type array $errors List of errors triggered during rendering of partials, if `WP_DEBUG_DISPLAY`
* is enabled.
* }
* @param WP_Customize_Selective_Refresh $refresh Selective refresh component.
* @param array $partials Placements' context data for the partials rendered in the request.
* The array is keyed by partial ID, with each item being an array of
* the placements' context data.
*/
$response = apply_filters( 'customize_render_partials_response', $response, $this, $partials );
wp_send_json_success( $response );
}
```
[do\_action( 'customize\_render\_partials\_after', WP\_Customize\_Selective\_Refresh $refresh, array $partials )](../../hooks/customize_render_partials_after)
Fires immediately after partials are rendered.
[do\_action( 'customize\_render\_partials\_before', WP\_Customize\_Selective\_Refresh $refresh, array $partials )](../../hooks/customize_render_partials_before)
Fires immediately before partials are rendered.
[apply\_filters( 'customize\_render\_partials\_response', array $response, WP\_Customize\_Selective\_Refresh $refresh, array $partials )](../../hooks/customize_render_partials_response)
Filters the response from rendering the partials.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Selective\_Refresh::is\_render\_partials\_request()](is_render_partials_request) wp-includes/customize/class-wp-customize-selective-refresh.php | Checks whether the request is for rendering partials. |
| [WP\_Customize\_Selective\_Refresh::add\_dynamic\_partials()](add_dynamic_partials) wp-includes/customize/class-wp-customize-selective-refresh.php | Registers dynamically-created partials. |
| [WP\_Customize\_Selective\_Refresh::get\_partial()](get_partial) wp-includes/customize/class-wp-customize-selective-refresh.php | Retrieves a partial. |
| [is\_customize\_preview()](../../functions/is_customize_preview) wp-includes/theme.php | Whether the site is being previewed in the Customizer. |
| [status\_header()](../../functions/status_header) wp-includes/functions.php | Sets HTTP status header. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [wp\_send\_json\_error()](../../functions/wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [wp\_send\_json\_success()](../../functions/wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Selective_Refresh::add_partial( WP_Customize_Partial|string $id, array $args = array() ): WP_Customize_Partial WP\_Customize\_Selective\_Refresh::add\_partial( WP\_Customize\_Partial|string $id, array $args = array() ): WP\_Customize\_Partial
===================================================================================================================================
Adds a partial.
* [WP\_Customize\_Partial::\_\_construct()](../wp_customize_partial/__construct)
`$id` [WP\_Customize\_Partial](../wp_customize_partial)|string Required Customize Partial object, or Partial ID. `$args` array Optional Array of properties for the new Partials object.
See [WP\_Customize\_Partial::\_\_construct()](../wp_customize_partial/__construct) for information on accepted arguments. More Arguments from WP\_Customize\_Partial::\_\_construct( ... $args ) Array of properties for the new Partials object.
* `type`stringType of the partial to be created.
* `selector`stringThe jQuery selector to find the container element for the partial, that is, a partial's placement.
* `settings`string[]IDs for settings tied to the partial. If undefined, `$id` will be used.
* `primary_setting`stringThe ID for the setting that this partial is primarily responsible for rendering. If not supplied, it will default to the ID of the first setting.
* `capability`stringCapability required to edit this partial.
Normally this is empty and the capability is derived from the capabilities of the associated `$settings`.
* `render_callback`callableRender callback.
Callback is called with one argument, the instance of [WP\_Customize\_Partial](../wp_customize_partial).
The callback can either echo the partial or return the partial as a string, or return false if error.
* `container_inclusive`boolWhether the container element is included in the partial, or if only the contents are rendered.
* `fallback_refresh`boolWhether to refresh the entire preview in case a partial cannot be refreshed.
A partial render is considered a failure if the render\_callback returns false.
Default: `array()`
[WP\_Customize\_Partial](../wp_customize_partial) The instance of the partial that was added.
File: `wp-includes/customize/class-wp-customize-selective-refresh.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-selective-refresh.php/)
```
public function add_partial( $id, $args = array() ) {
if ( $id instanceof WP_Customize_Partial ) {
$partial = $id;
} else {
$class = 'WP_Customize_Partial';
/** This filter is documented in wp-includes/customize/class-wp-customize-selective-refresh.php */
$args = apply_filters( 'customize_dynamic_partial_args', $args, $id );
/** This filter is documented in wp-includes/customize/class-wp-customize-selective-refresh.php */
$class = apply_filters( 'customize_dynamic_partial_class', $class, $id, $args );
$partial = new $class( $this, $id, $args );
}
$this->partials[ $partial->id ] = $partial;
return $partial;
}
```
[apply\_filters( 'customize\_dynamic\_partial\_args', false|array $partial\_args, string $partial\_id )](../../hooks/customize_dynamic_partial_args)
Filters a dynamic partial’s constructor arguments.
[apply\_filters( 'customize\_dynamic\_partial\_class', string $partial\_class, string $partial\_id, array $partial\_args )](../../hooks/customize_dynamic_partial_class)
Filters the class used to construct partials.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Selective\_Refresh::add\_dynamic\_partials()](add_dynamic_partials) wp-includes/customize/class-wp-customize-selective-refresh.php | Registers dynamically-created partials. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Selective_Refresh::export_preview_data() WP\_Customize\_Selective\_Refresh::export\_preview\_data()
==========================================================
Exports data in preview after it has finished rendering so that partials can be added at runtime.
File: `wp-includes/customize/class-wp-customize-selective-refresh.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-selective-refresh.php/)
```
public function export_preview_data() {
$partials = array();
foreach ( $this->partials() as $partial ) {
if ( $partial->check_capabilities() ) {
$partials[ $partial->id ] = $partial->json();
}
}
$switched_locale = switch_to_locale( get_user_locale() );
$l10n = array(
'shiftClickToEdit' => __( 'Shift-click to edit this element.' ),
'clickEditMenu' => __( 'Click to edit this menu.' ),
'clickEditWidget' => __( 'Click to edit this widget.' ),
'clickEditTitle' => __( 'Click to edit the site title.' ),
'clickEditMisc' => __( 'Click to edit this element.' ),
/* translators: %s: document.write() */
'badDocumentWrite' => sprintf( __( '%s is forbidden' ), 'document.write()' ),
);
if ( $switched_locale ) {
restore_previous_locale();
}
$exports = array(
'partials' => $partials,
'renderQueryVar' => self::RENDER_QUERY_VAR,
'l10n' => $l10n,
);
// Export data to JS.
printf( '<script>var _customizePartialRefreshExports = %s;</script>', wp_json_encode( $exports ) );
}
```
| Uses | Description |
| --- | --- |
| [restore\_previous\_locale()](../../functions/restore_previous_locale) wp-includes/l10n.php | Restores the translations according to the previous locale. |
| [switch\_to\_locale()](../../functions/switch_to_locale) wp-includes/l10n.php | Switches the translations according to the given locale. |
| [get\_user\_locale()](../../functions/get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| [WP\_Customize\_Selective\_Refresh::partials()](partials) wp-includes/customize/class-wp-customize-selective-refresh.php | Retrieves the registered partials. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Selective_Refresh::add_dynamic_partials( string[] $partial_ids ): WP_Customize_Partial[] WP\_Customize\_Selective\_Refresh::add\_dynamic\_partials( string[] $partial\_ids ): WP\_Customize\_Partial[]
=============================================================================================================
Registers dynamically-created partials.
* [WP\_Customize\_Manager::add\_dynamic\_settings()](../wp_customize_manager/add_dynamic_settings)
`$partial_ids` string[] Required Array of the partial IDs to add. [WP\_Customize\_Partial](../wp_customize_partial)[] Array of added [WP\_Customize\_Partial](../wp_customize_partial) instances.
File: `wp-includes/customize/class-wp-customize-selective-refresh.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-selective-refresh.php/)
```
public function add_dynamic_partials( $partial_ids ) {
$new_partials = array();
foreach ( $partial_ids as $partial_id ) {
// Skip partials already created.
$partial = $this->get_partial( $partial_id );
if ( $partial ) {
continue;
}
$partial_args = false;
$partial_class = 'WP_Customize_Partial';
/**
* Filters a dynamic partial's constructor arguments.
*
* For a dynamic partial to be registered, this filter must be employed
* to override the default false value with an array of args to pass to
* the WP_Customize_Partial constructor.
*
* @since 4.5.0
*
* @param false|array $partial_args The arguments to the WP_Customize_Partial constructor.
* @param string $partial_id ID for dynamic partial.
*/
$partial_args = apply_filters( 'customize_dynamic_partial_args', $partial_args, $partial_id );
if ( false === $partial_args ) {
continue;
}
/**
* Filters the class used to construct partials.
*
* Allow non-statically created partials to be constructed with custom WP_Customize_Partial subclass.
*
* @since 4.5.0
*
* @param string $partial_class WP_Customize_Partial or a subclass.
* @param string $partial_id ID for dynamic partial.
* @param array $partial_args The arguments to the WP_Customize_Partial constructor.
*/
$partial_class = apply_filters( 'customize_dynamic_partial_class', $partial_class, $partial_id, $partial_args );
$partial = new $partial_class( $this, $partial_id, $partial_args );
$this->add_partial( $partial );
$new_partials[] = $partial;
}
return $new_partials;
}
```
[apply\_filters( 'customize\_dynamic\_partial\_args', false|array $partial\_args, string $partial\_id )](../../hooks/customize_dynamic_partial_args)
Filters a dynamic partial’s constructor arguments.
[apply\_filters( 'customize\_dynamic\_partial\_class', string $partial\_class, string $partial\_id, array $partial\_args )](../../hooks/customize_dynamic_partial_class)
Filters the class used to construct partials.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Selective\_Refresh::get\_partial()](get_partial) wp-includes/customize/class-wp-customize-selective-refresh.php | Retrieves a partial. |
| [WP\_Customize\_Selective\_Refresh::add\_partial()](add_partial) wp-includes/customize/class-wp-customize-selective-refresh.php | Adds a partial. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Selective\_Refresh::handle\_render\_partials\_request()](handle_render_partials_request) wp-includes/customize/class-wp-customize-selective-refresh.php | Handles the Ajax request to return the rendered partials for the requested placements. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Selective_Refresh::remove_partial( string $id ) WP\_Customize\_Selective\_Refresh::remove\_partial( string $id )
================================================================
Removes a partial.
`$id` string Required Customize Partial ID. File: `wp-includes/customize/class-wp-customize-selective-refresh.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-selective-refresh.php/)
```
public function remove_partial( $id ) {
unset( $this->partials[ $id ] );
}
```
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Selective_Refresh::__construct( WP_Customize_Manager $manager ) WP\_Customize\_Selective\_Refresh::\_\_construct( WP\_Customize\_Manager $manager )
===================================================================================
Plugin bootstrap for Partial Refresh functionality.
`$manager` [WP\_Customize\_Manager](../wp_customize_manager) Required Customizer bootstrap instance. File: `wp-includes/customize/class-wp-customize-selective-refresh.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-selective-refresh.php/)
```
public function __construct( WP_Customize_Manager $manager ) {
$this->manager = $manager;
require_once ABSPATH . WPINC . '/customize/class-wp-customize-partial.php';
add_action( 'customize_preview_init', array( $this, 'init_preview' ) );
}
```
| Uses | Description |
| --- | --- |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::\_\_construct()](../wp_customize_manager/__construct) wp-includes/class-wp-customize-manager.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Selective_Refresh::get_partial( string $id ): WP_Customize_Partial|null WP\_Customize\_Selective\_Refresh::get\_partial( string $id ): WP\_Customize\_Partial|null
==========================================================================================
Retrieves a partial.
`$id` string Required Customize Partial ID. [WP\_Customize\_Partial](../wp_customize_partial)|null The partial, if set. Otherwise null.
File: `wp-includes/customize/class-wp-customize-selective-refresh.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-selective-refresh.php/)
```
public function get_partial( $id ) {
if ( isset( $this->partials[ $id ] ) ) {
return $this->partials[ $id ];
} else {
return null;
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Selective\_Refresh::add\_dynamic\_partials()](add_dynamic_partials) wp-includes/customize/class-wp-customize-selective-refresh.php | Registers dynamically-created partials. |
| [WP\_Customize\_Selective\_Refresh::handle\_render\_partials\_request()](handle_render_partials_request) wp-includes/customize/class-wp-customize-selective-refresh.php | Handles the Ajax request to return the rendered partials for the requested placements. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Selective_Refresh::is_render_partials_request(): bool WP\_Customize\_Selective\_Refresh::is\_render\_partials\_request(): bool
========================================================================
Checks whether the request is for rendering partials.
Note that this will not consider whether the request is authorized or valid, just that essentially the route is a match.
bool Whether the request is for rendering partials.
File: `wp-includes/customize/class-wp-customize-selective-refresh.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-selective-refresh.php/)
```
public function is_render_partials_request() {
return ! empty( $_POST[ self::RENDER_QUERY_VAR ] );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Selective\_Refresh::handle\_render\_partials\_request()](handle_render_partials_request) wp-includes/customize/class-wp-customize-selective-refresh.php | Handles the Ajax request to return the rendered partials for the requested placements. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Selective_Refresh::enqueue_preview_scripts() WP\_Customize\_Selective\_Refresh::enqueue\_preview\_scripts()
==============================================================
Enqueues preview scripts.
File: `wp-includes/customize/class-wp-customize-selective-refresh.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-selective-refresh.php/)
```
public function enqueue_preview_scripts() {
wp_enqueue_script( 'customize-selective-refresh' );
add_action( 'wp_footer', array( $this, 'export_preview_data' ), 1000 );
}
```
| Uses | Description |
| --- | --- |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Widget_Recent_Comments::form( array $instance ) WP\_Widget\_Recent\_Comments::form( array $instance )
=====================================================
Outputs the settings form for the Recent Comments widget.
`$instance` array Required Current settings. File: `wp-includes/widgets/class-wp-widget-recent-comments.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-recent-comments.php/)
```
public function form( $instance ) {
$title = isset( $instance['title'] ) ? $instance['title'] : '';
$number = isset( $instance['number'] ) ? absint( $instance['number'] ) : 5;
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of comments to show:' ); ?></label>
<input class="tiny-text" id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" type="number" step="1" min="1" value="<?php echo $number; ?>" size="3" />
</p>
<?php
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Recent_Comments::update( array $new_instance, array $old_instance ): array WP\_Widget\_Recent\_Comments::update( array $new\_instance, array $old\_instance ): array
=========================================================================================
Handles updating settings for the current Recent Comments widget instance.
`$new_instance` array Required New settings for this instance as input by the user via [WP\_Widget::form()](../wp_widget/form). `$old_instance` array Required Old settings for this instance. array Updated settings to save.
File: `wp-includes/widgets/class-wp-widget-recent-comments.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-recent-comments.php/)
```
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = sanitize_text_field( $new_instance['title'] );
$instance['number'] = absint( $new_instance['number'] );
return $instance;
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Recent_Comments::recent_comments_style() WP\_Widget\_Recent\_Comments::recent\_comments\_style()
=======================================================
Outputs the default styles for the Recent Comments widget.
File: `wp-includes/widgets/class-wp-widget-recent-comments.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-recent-comments.php/)
```
public function recent_comments_style() {
/**
* Filters the Recent Comments default widget styles.
*
* @since 3.1.0
*
* @param bool $active Whether the widget is active. Default true.
* @param string $id_base The widget ID.
*/
if ( ! current_theme_supports( 'widgets' ) // Temp hack #14876.
|| ! apply_filters( 'show_recent_comments_widget_style', true, $this->id_base ) ) {
return;
}
$type_attr = current_theme_supports( 'html5', 'style' ) ? '' : ' type="text/css"';
printf(
'<style%s>.recentcomments a{display:inline !important;padding:0 !important;margin:0 !important;}</style>',
$type_attr
);
}
```
[apply\_filters( 'show\_recent\_comments\_widget\_style', bool $active, string $id\_base )](../../hooks/show_recent_comments_widget_style)
Filters the Recent Comments default widget styles.
| Uses | Description |
| --- | --- |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Recent_Comments::__construct() WP\_Widget\_Recent\_Comments::\_\_construct()
=============================================
Sets up a new Recent Comments widget instance.
File: `wp-includes/widgets/class-wp-widget-recent-comments.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-recent-comments.php/)
```
public function __construct() {
$widget_ops = array(
'classname' => 'widget_recent_comments',
'description' => __( 'Your site’s most recent comments.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
parent::__construct( 'recent-comments', __( 'Recent Comments' ), $widget_ops );
$this->alt_option_name = 'widget_recent_comments';
if ( is_active_widget( false, false, $this->id_base ) || is_customize_preview() ) {
add_action( 'wp_head', array( $this, 'recent_comments_style' ) );
}
}
```
| Uses | Description |
| --- | --- |
| [is\_customize\_preview()](../../functions/is_customize_preview) wp-includes/theme.php | Whether the site is being previewed in the Customizer. |
| [WP\_Widget::\_\_construct()](../wp_widget/__construct) wp-includes/class-wp-widget.php | PHP5 constructor. |
| [is\_active\_widget()](../../functions/is_active_widget) wp-includes/widgets.php | Determines whether a given widget is displayed on the front end. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Recent_Comments::widget( array $args, array $instance ) WP\_Widget\_Recent\_Comments::widget( array $args, array $instance )
====================================================================
Outputs the content for the current Recent Comments widget instance.
`$args` array Required Display arguments including `'before_title'`, `'after_title'`, `'before_widget'`, and `'after_widget'`. `$instance` array Required Settings for the current Recent Comments widget instance. File: `wp-includes/widgets/class-wp-widget-recent-comments.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-recent-comments.php/)
```
public function widget( $args, $instance ) {
static $first_instance = true;
if ( ! isset( $args['widget_id'] ) ) {
$args['widget_id'] = $this->id;
}
$output = '';
$default_title = __( 'Recent Comments' );
$title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : $default_title;
/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
$number = ( ! empty( $instance['number'] ) ) ? absint( $instance['number'] ) : 5;
if ( ! $number ) {
$number = 5;
}
$comments = get_comments(
/**
* Filters the arguments for the Recent Comments widget.
*
* @since 3.4.0
* @since 4.9.0 Added the `$instance` parameter.
*
* @see WP_Comment_Query::query() for information on accepted arguments.
*
* @param array $comment_args An array of arguments used to retrieve the recent comments.
* @param array $instance Array of settings for the current widget.
*/
apply_filters(
'widget_comments_args',
array(
'number' => $number,
'status' => 'approve',
'post_status' => 'publish',
),
$instance
)
);
$output .= $args['before_widget'];
if ( $title ) {
$output .= $args['before_title'] . $title . $args['after_title'];
}
$recent_comments_id = ( $first_instance ) ? 'recentcomments' : "recentcomments-{$this->number}";
$first_instance = false;
$format = current_theme_supports( 'html5', 'navigation-widgets' ) ? 'html5' : 'xhtml';
/** This filter is documented in wp-includes/widgets/class-wp-nav-menu-widget.php */
$format = apply_filters( 'navigation_widgets_format', $format );
if ( 'html5' === $format ) {
// The title may be filtered: Strip out HTML and make sure the aria-label is never empty.
$title = trim( strip_tags( $title ) );
$aria_label = $title ? $title : $default_title;
$output .= '<nav aria-label="' . esc_attr( $aria_label ) . '">';
}
$output .= '<ul id="' . esc_attr( $recent_comments_id ) . '">';
if ( is_array( $comments ) && $comments ) {
// Prime cache for associated posts. (Prime post term cache if we need it for permalinks.)
$post_ids = array_unique( wp_list_pluck( $comments, 'comment_post_ID' ) );
_prime_post_caches( $post_ids, strpos( get_option( 'permalink_structure' ), '%category%' ), false );
foreach ( (array) $comments as $comment ) {
$output .= '<li class="recentcomments">';
$output .= sprintf(
/* translators: Comments widget. 1: Comment author, 2: Post link. */
_x( '%1$s on %2$s', 'widgets' ),
'<span class="comment-author-link">' . get_comment_author_link( $comment ) . '</span>',
'<a href="' . esc_url( get_comment_link( $comment ) ) . '">' . get_the_title( $comment->comment_post_ID ) . '</a>'
);
$output .= '</li>';
}
}
$output .= '</ul>';
if ( 'html5' === $format ) {
$output .= '</nav>';
}
$output .= $args['after_widget'];
echo $output;
}
```
[apply\_filters( 'navigation\_widgets\_format', string $format )](../../hooks/navigation_widgets_format)
Filters the HTML format of widgets with navigation links.
[apply\_filters( 'widget\_comments\_args', array $comment\_args, array $instance )](../../hooks/widget_comments_args)
Filters the arguments for the Recent Comments widget.
[apply\_filters( 'widget\_title', string $title, array $instance, mixed $id\_base )](../../hooks/widget_title)
Filters the widget title.
| Uses | Description |
| --- | --- |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [get\_the\_title()](../../functions/get_the_title) wp-includes/post-template.php | Retrieves the post title. |
| [\_prime\_post\_caches()](../../functions/_prime_post_caches) wp-includes/post.php | Adds any posts from the given IDs to the cache that do not already exist in cache. |
| [get\_comment\_link()](../../functions/get_comment_link) wp-includes/comment-template.php | Retrieves the link to a given comment. |
| [get\_comment\_author\_link()](../../functions/get_comment_author_link) wp-includes/comment-template.php | Retrieves the HTML link to the URL of the author of the current comment. |
| [get\_comments()](../../functions/get_comments) wp-includes/comment.php | Retrieves a list of comments. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | Creates a unique HTML ID for the `<ul>` element if more than one instance is displayed on the page. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Recent_Comments::flush_widget_cache() WP\_Widget\_Recent\_Comments::flush\_widget\_cache()
====================================================
This method has been deprecated. Fragment caching was removed in favor of split queries instead.
Flushes the Recent Comments widget cache.
File: `wp-includes/widgets/class-wp-widget-recent-comments.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-recent-comments.php/)
```
public function flush_widget_cache() {
_deprecated_function( __METHOD__, '4.4.0' );
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Fragment caching was removed in favor of split queries. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Screen::render_screen_layout() WP\_Screen::render\_screen\_layout()
====================================
Renders the option for number of columns on the page.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function render_screen_layout() {
if ( ! $this->get_option( 'layout_columns' ) ) {
return;
}
$screen_layout_columns = $this->get_columns();
$num = $this->get_option( 'layout_columns', 'max' );
?>
<fieldset class='columns-prefs'>
<legend class="screen-layout"><?php _e( 'Layout' ); ?></legend>
<?php for ( $i = 1; $i <= $num; ++$i ) : ?>
<label class="columns-prefs-<?php echo $i; ?>">
<input type='radio' name='screen_columns' value='<?php echo esc_attr( $i ); ?>' <?php checked( $screen_layout_columns, $i ); ?> />
<?php
printf(
/* translators: %s: Number of columns on the page. */
_n( '%s column', '%s columns', $i ),
number_format_i18n( $i )
);
?>
</label>
<?php endfor; ?>
</fieldset>
<?php
}
```
| Uses | Description |
| --- | --- |
| [WP\_Screen::get\_option()](get_option) wp-admin/includes/class-wp-screen.php | Gets the arguments for an option for the screen. |
| [WP\_Screen::get\_columns()](get_columns) wp-admin/includes/class-wp-screen.php | Gets the number of layout columns the user has selected. |
| [\_n()](../../functions/_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [checked()](../../functions/checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_screen\_options()](render_screen_options) wp-admin/includes/class-wp-screen.php | Renders the screen options tab. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
| programming_docs |
wordpress WP_Screen::remove_help_tabs() WP\_Screen::remove\_help\_tabs()
================================
Removes all help tabs from the contextual help for the screen.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function remove_help_tabs() {
$this->_help_tabs = array();
}
```
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Screen::remove_option( string $option ) WP\_Screen::remove\_option( string $option )
============================================
Removes an option from the screen.
`$option` string Required Option ID. File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function remove_option( $option ) {
unset( $this->_options[ $option ] );
}
```
| Version | Description |
| --- | --- |
| [3.8.0](https://developer.wordpress.org/reference/since/3.8.0/) | Introduced. |
wordpress WP_Screen::get_options(): array WP\_Screen::get\_options(): array
=================================
Gets the options registered for the screen.
array Options with arguments.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function get_options() {
return $this->_options;
}
```
| Version | Description |
| --- | --- |
| [3.8.0](https://developer.wordpress.org/reference/since/3.8.0/) | Introduced. |
wordpress WP_Screen::remove_screen_reader_content() WP\_Screen::remove\_screen\_reader\_content()
=============================================
Removes all the accessible hidden headings and text for the screen.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function remove_screen_reader_content() {
$this->_screen_reader_content = array();
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Screen::get_help_tabs(): array WP\_Screen::get\_help\_tabs(): array
====================================
Gets the help tabs registered for the screen.
array Help tabs with arguments.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function get_help_tabs() {
$help_tabs = $this->_help_tabs;
$priorities = array();
foreach ( $help_tabs as $help_tab ) {
if ( isset( $priorities[ $help_tab['priority'] ] ) ) {
$priorities[ $help_tab['priority'] ][] = $help_tab;
} else {
$priorities[ $help_tab['priority'] ] = array( $help_tab );
}
}
ksort( $priorities );
$sorted = array();
foreach ( $priorities as $list ) {
foreach ( $list as $tab ) {
$sorted[ $tab['id'] ] = $tab;
}
}
return $sorted;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_screen\_meta()](render_screen_meta) wp-admin/includes/class-wp-screen.php | Renders the screen’s help section. |
| [page\_attributes\_meta\_box()](../../functions/page_attributes_meta_box) wp-admin/includes/meta-boxes.php | Displays page attributes form fields. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Help tabs are ordered by their priority. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Screen::show_screen_options(): bool WP\_Screen::show\_screen\_options(): bool
=========================================
bool
This method automatically sets the $\_screen\_settings property and returns the $\_show\_screen\_options property.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function show_screen_options() {
global $wp_meta_boxes;
if ( is_bool( $this->_show_screen_options ) ) {
return $this->_show_screen_options;
}
$columns = get_column_headers( $this );
$show_screen = ! empty( $wp_meta_boxes[ $this->id ] ) || $columns || $this->get_option( 'per_page' );
$this->_screen_settings = '';
if ( 'post' === $this->base ) {
$expand = '<fieldset class="editor-expand hidden"><legend>' . __( 'Additional settings' ) . '</legend><label for="editor-expand-toggle">';
$expand .= '<input type="checkbox" id="editor-expand-toggle"' . checked( get_user_setting( 'editor_expand', 'on' ), 'on', false ) . ' />';
$expand .= __( 'Enable full-height editor and distraction-free functionality.' ) . '</label></fieldset>';
$this->_screen_settings = $expand;
}
/**
* Filters the screen settings text displayed in the Screen Options tab.
*
* @since 3.0.0
*
* @param string $screen_settings Screen settings.
* @param WP_Screen $screen WP_Screen object.
*/
$this->_screen_settings = apply_filters( 'screen_settings', $this->_screen_settings, $this );
if ( $this->_screen_settings || $this->_options ) {
$show_screen = true;
}
/**
* Filters whether to show the Screen Options tab.
*
* @since 3.2.0
*
* @param bool $show_screen Whether to show Screen Options tab.
* Default true.
* @param WP_Screen $screen Current WP_Screen instance.
*/
$this->_show_screen_options = apply_filters( 'screen_options_show_screen', $show_screen, $this );
return $this->_show_screen_options;
}
```
[apply\_filters( 'screen\_options\_show\_screen', bool $show\_screen, WP\_Screen $screen )](../../hooks/screen_options_show_screen)
Filters whether to show the Screen Options tab.
[apply\_filters( 'screen\_settings', string $screen\_settings, WP\_Screen $screen )](../../hooks/screen_settings)
Filters the screen settings text displayed in the Screen Options tab.
| Uses | Description |
| --- | --- |
| [WP\_Screen::get\_option()](get_option) wp-admin/includes/class-wp-screen.php | Gets the arguments for an option for the screen. |
| [get\_column\_headers()](../../functions/get_column_headers) wp-admin/includes/screen.php | Get the column headers for a screen |
| [checked()](../../functions/checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [get\_user\_setting()](../../functions/get_user_setting) wp-includes/option.php | Retrieves user interface setting value based on setting name. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_screen\_meta()](render_screen_meta) wp-admin/includes/class-wp-screen.php | Renders the screen’s help section. |
wordpress WP_Screen::remove_options() WP\_Screen::remove\_options()
=============================
Removes all options from the screen.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function remove_options() {
$this->_options = array();
}
```
| Version | Description |
| --- | --- |
| [3.8.0](https://developer.wordpress.org/reference/since/3.8.0/) | Introduced. |
wordpress WP_Screen::add_help_tab( array $args ) WP\_Screen::add\_help\_tab( array $args )
=========================================
Adds a help tab to the contextual help for the screen.
Call this on the `load-$pagenow` hook for the relevant screen, or fetch the `$current_screen` object, or use [get\_current\_screen()](../../functions/get_current_screen) and then call the method from the object.
You may need to filter `$current_screen` using an if or switch statement to prevent new help tabs from being added to ALL admin screens.
`$args` array Required Array of arguments used to display the help tab.
* `title`stringTitle for the tab. Default false.
* `id`stringTab ID. Must be HTML-safe and should be unique for this menu.
It is NOT allowed to contain any empty spaces. Default false.
* `content`stringOptional. Help tab content in plain text or HTML. Default empty string.
* `callback`callableOptional. A callback to generate the tab content. Default false.
* `priority`intOptional. The priority of the tab, used for ordering. Default 10.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function add_help_tab( $args ) {
$defaults = array(
'title' => false,
'id' => false,
'content' => '',
'callback' => false,
'priority' => 10,
);
$args = wp_parse_args( $args, $defaults );
$args['id'] = sanitize_html_class( $args['id'] );
// Ensure we have an ID and title.
if ( ! $args['id'] || ! $args['title'] ) {
return;
}
// Allows for overriding an existing tab with that ID.
$this->_help_tabs[ $args['id'] ] = $args;
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_html\_class()](../../functions/sanitize_html_class) wp-includes/formatting.php | Sanitizes an HTML classname to ensure it only contains valid characters. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_screen\_meta()](render_screen_meta) wp-admin/includes/class-wp-screen.php | Renders the screen’s help section. |
| [Custom\_Image\_Header::help()](../custom_image_header/help) wp-admin/includes/class-custom-image-header.php | Adds contextual help. |
| [Custom\_Background::admin\_load()](../custom_background/admin_load) wp-admin/includes/class-custom-background.php | Sets up the enqueue for the CSS & JavaScript files. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | The `$priority` argument was added. |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Screen::remove_help_tab( string $id ) WP\_Screen::remove\_help\_tab( string $id )
===========================================
Removes a help tab from the contextual help for the screen.
`$id` string Required The help tab ID. File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function remove_help_tab( $id ) {
unset( $this->_help_tabs[ $id ] );
}
```
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Screen::render_per_page_options() WP\_Screen::render\_per\_page\_options()
========================================
Renders the items per page option.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function render_per_page_options() {
if ( null === $this->get_option( 'per_page' ) ) {
return;
}
$per_page_label = $this->get_option( 'per_page', 'label' );
if ( null === $per_page_label ) {
$per_page_label = __( 'Number of items per page:' );
}
$option = $this->get_option( 'per_page', 'option' );
if ( ! $option ) {
$option = str_replace( '-', '_', "{$this->id}_per_page" );
}
$per_page = (int) get_user_option( $option );
if ( empty( $per_page ) || $per_page < 1 ) {
$per_page = $this->get_option( 'per_page', 'default' );
if ( ! $per_page ) {
$per_page = 20;
}
}
if ( 'edit_comments_per_page' === $option ) {
$comment_status = isset( $_REQUEST['comment_status'] ) ? $_REQUEST['comment_status'] : 'all';
/** This filter is documented in wp-admin/includes/class-wp-comments-list-table.php */
$per_page = apply_filters( 'comments_per_page', $per_page, $comment_status );
} elseif ( 'categories_per_page' === $option ) {
/** This filter is documented in wp-admin/includes/class-wp-terms-list-table.php */
$per_page = apply_filters( 'edit_categories_per_page', $per_page );
} else {
/** This filter is documented in wp-admin/includes/class-wp-list-table.php */
$per_page = apply_filters( "{$option}", $per_page );
}
// Back compat.
if ( isset( $this->post_type ) ) {
/** This filter is documented in wp-admin/includes/post.php */
$per_page = apply_filters( 'edit_posts_per_page', $per_page, $this->post_type );
}
// This needs a submit button.
add_filter( 'screen_options_show_submit', '__return_true' );
?>
<fieldset class="screen-options">
<legend><?php _e( 'Pagination' ); ?></legend>
<?php if ( $per_page_label ) : ?>
<label for="<?php echo esc_attr( $option ); ?>"><?php echo $per_page_label; ?></label>
<input type="number" step="1" min="1" max="999" class="screen-per-page" name="wp_screen_options[value]"
id="<?php echo esc_attr( $option ); ?>" maxlength="3"
value="<?php echo esc_attr( $per_page ); ?>" />
<?php endif; ?>
<input type="hidden" name="wp_screen_options[option]" value="<?php echo esc_attr( $option ); ?>" />
</fieldset>
<?php
}
```
[apply\_filters( 'comments\_per\_page', int $comments\_per\_page, string $comment\_status )](../../hooks/comments_per_page)
Filters the number of comments listed per page in the comments list table.
[apply\_filters( 'edit\_categories\_per\_page', int $tags\_per\_page )](../../hooks/edit_categories_per_page)
Filters the number of terms displayed per page for the Categories list table.
[apply\_filters( 'edit\_posts\_per\_page', int $posts\_per\_page, string $post\_type )](../../hooks/edit_posts_per_page)
Filters the number of posts displayed per page when specifically listing “posts”.
[apply\_filters( "{$option}", int $per\_page )](../../hooks/option)
Filters the number of items to be displayed on each page of the list table.
| Uses | Description |
| --- | --- |
| [get\_user\_option()](../../functions/get_user_option) wp-includes/user.php | Retrieves user option that can be either per Site or per Network. |
| [WP\_Screen::get\_option()](get_option) wp-admin/includes/class-wp-screen.php | Gets the arguments for an option for the screen. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_screen\_options()](render_screen_options) wp-admin/includes/class-wp-screen.php | Renders the screen options tab. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Screen::add_option( string $option, mixed $args = array() ) WP\_Screen::add\_option( string $option, mixed $args = array() )
================================================================
Adds an option for the screen.
Call this in template files after admin.php is loaded and before admin-header.php is loaded to add screen options.
`$option` string Required Option ID. `$args` mixed Optional Option-dependent arguments. Default: `array()`
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function add_option( $option, $args = array() ) {
$this->_options[ $option ] = $args;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_screen\_meta()](render_screen_meta) wp-admin/includes/class-wp-screen.php | Renders the screen’s help section. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Screen::render_meta_boxes_preferences() WP\_Screen::render\_meta\_boxes\_preferences()
==============================================
Renders the meta boxes preferences.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function render_meta_boxes_preferences() {
global $wp_meta_boxes;
if ( ! isset( $wp_meta_boxes[ $this->id ] ) ) {
return;
}
?>
<fieldset class="metabox-prefs">
<legend><?php _e( 'Screen elements' ); ?></legend>
<p>
<?php _e( 'Some screen elements can be shown or hidden by using the checkboxes.' ); ?>
<?php _e( 'They can be expanded and collapsed by clickling on their headings, and arranged by dragging their headings or by clicking on the up and down arrows.' ); ?>
</p>
<?php
meta_box_prefs( $this );
if ( 'dashboard' === $this->id && has_action( 'welcome_panel' ) && current_user_can( 'edit_theme_options' ) ) {
if ( isset( $_GET['welcome'] ) ) {
$welcome_checked = empty( $_GET['welcome'] ) ? 0 : 1;
update_user_meta( get_current_user_id(), 'show_welcome_panel', $welcome_checked );
} else {
$welcome_checked = (int) get_user_meta( get_current_user_id(), 'show_welcome_panel', true );
if ( 2 === $welcome_checked && wp_get_current_user()->user_email !== get_option( 'admin_email' ) ) {
$welcome_checked = false;
}
}
echo '<label for="wp_welcome_panel-hide">';
echo '<input type="checkbox" id="wp_welcome_panel-hide"' . checked( (bool) $welcome_checked, true, false ) . ' />';
echo _x( 'Welcome', 'Welcome panel' ) . "</label>\n";
}
?>
</fieldset>
<?php
}
```
| Uses | Description |
| --- | --- |
| [meta\_box\_prefs()](../../functions/meta_box_prefs) wp-admin/includes/screen.php | Prints the meta box preferences for screen meta. |
| [wp\_get\_current\_user()](../../functions/wp_get_current_user) wp-includes/pluggable.php | Retrieves the current user object. |
| [checked()](../../functions/checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [has\_action()](../../functions/has_action) wp-includes/plugin.php | Checks if any action has been registered for a hook. |
| [update\_user\_meta()](../../functions/update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| [get\_user\_meta()](../../functions/get_user_meta) wp-includes/user.php | Retrieves user meta field for a user. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_screen\_options()](render_screen_options) wp-admin/includes/class-wp-screen.php | Renders the screen options tab. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress WP_Screen::render_view_mode() WP\_Screen::render\_view\_mode()
================================
Renders the list table view mode preferences.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function render_view_mode() {
global $mode;
$screen = get_current_screen();
// Currently only enabled for posts and comments lists.
if ( 'edit' !== $screen->base && 'edit-comments' !== $screen->base ) {
return;
}
$view_mode_post_types = get_post_types( array( 'show_ui' => true ) );
/**
* Filters the post types that have different view mode options.
*
* @since 4.4.0
*
* @param string[] $view_mode_post_types Array of post types that can change view modes.
* Default post types with show_ui on.
*/
$view_mode_post_types = apply_filters( 'view_mode_post_types', $view_mode_post_types );
if ( 'edit' === $screen->base && ! in_array( $this->post_type, $view_mode_post_types, true ) ) {
return;
}
if ( ! isset( $mode ) ) {
$mode = get_user_setting( 'posts_list_mode', 'list' );
}
// This needs a submit button.
add_filter( 'screen_options_show_submit', '__return_true' );
?>
<fieldset class="metabox-prefs view-mode">
<legend><?php _e( 'View mode' ); ?></legend>
<label for="list-view-mode">
<input id="list-view-mode" type="radio" name="mode" value="list" <?php checked( 'list', $mode ); ?> />
<?php _e( 'Compact view' ); ?>
</label>
<label for="excerpt-view-mode">
<input id="excerpt-view-mode" type="radio" name="mode" value="excerpt" <?php checked( 'excerpt', $mode ); ?> />
<?php _e( 'Extended view' ); ?>
</label>
</fieldset>
<?php
}
```
[apply\_filters( 'view\_mode\_post\_types', string[] $view\_mode\_post\_types )](../../hooks/view_mode_post_types)
Filters the post types that have different view mode options.
| Uses | Description |
| --- | --- |
| [get\_current\_screen()](../../functions/get_current_screen) wp-admin/includes/screen.php | Get the current screen object |
| [checked()](../../functions/checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [get\_user\_setting()](../../functions/get_user_setting) wp-includes/option.php | Retrieves user interface setting value based on setting name. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [get\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_screen\_options()](render_screen_options) wp-admin/includes/class-wp-screen.php | Renders the screen options tab. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Screen::render_list_table_columns_preferences() WP\_Screen::render\_list\_table\_columns\_preferences()
=======================================================
Renders the list table columns preferences.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function render_list_table_columns_preferences() {
$columns = get_column_headers( $this );
$hidden = get_hidden_columns( $this );
if ( ! $columns ) {
return;
}
$legend = ! empty( $columns['_title'] ) ? $columns['_title'] : __( 'Columns' );
?>
<fieldset class="metabox-prefs">
<legend><?php echo $legend; ?></legend>
<?php
$special = array( '_title', 'cb', 'comment', 'media', 'name', 'title', 'username', 'blogname' );
foreach ( $columns as $column => $title ) {
// Can't hide these for they are special.
if ( in_array( $column, $special, true ) ) {
continue;
}
if ( empty( $title ) ) {
continue;
}
/*
* The Comments column uses HTML in the display name with some screen
* reader text. Make sure to strip tags from the Comments column
* title and any other custom column title plugins might add.
*/
$title = wp_strip_all_tags( $title );
$id = "$column-hide";
echo '<label>';
echo '<input class="hide-column-tog" name="' . $id . '" type="checkbox" id="' . $id . '" value="' . $column . '"' . checked( ! in_array( $column, $hidden, true ), true, false ) . ' />';
echo "$title</label>\n";
}
?>
</fieldset>
<?php
}
```
| Uses | Description |
| --- | --- |
| [get\_column\_headers()](../../functions/get_column_headers) wp-admin/includes/screen.php | Get the column headers for a screen |
| [get\_hidden\_columns()](../../functions/get_hidden_columns) wp-admin/includes/screen.php | Get a list of hidden columns. |
| [wp\_strip\_all\_tags()](../../functions/wp_strip_all_tags) wp-includes/formatting.php | Properly strips all HTML tags including script and style |
| [checked()](../../functions/checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_screen\_options()](render_screen_options) wp-admin/includes/class-wp-screen.php | Renders the screen options tab. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Screen::render_screen_meta() WP\_Screen::render\_screen\_meta()
==================================
Renders the screen’s help section.
This will trigger the deprecated filters for backward compatibility.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function render_screen_meta() {
/**
* Filters the legacy contextual help list.
*
* @since 2.7.0
* @deprecated 3.3.0 Use {@see get_current_screen()->add_help_tab()} or
* {@see get_current_screen()->remove_help_tab()} instead.
*
* @param array $old_compat_help Old contextual help.
* @param WP_Screen $screen Current WP_Screen instance.
*/
self::$_old_compat_help = apply_filters_deprecated(
'contextual_help_list',
array( self::$_old_compat_help, $this ),
'3.3.0',
'get_current_screen()->add_help_tab(), get_current_screen()->remove_help_tab()'
);
$old_help = isset( self::$_old_compat_help[ $this->id ] ) ? self::$_old_compat_help[ $this->id ] : '';
/**
* Filters the legacy contextual help text.
*
* @since 2.7.0
* @deprecated 3.3.0 Use {@see get_current_screen()->add_help_tab()} or
* {@see get_current_screen()->remove_help_tab()} instead.
*
* @param string $old_help Help text that appears on the screen.
* @param string $screen_id Screen ID.
* @param WP_Screen $screen Current WP_Screen instance.
*/
$old_help = apply_filters_deprecated(
'contextual_help',
array( $old_help, $this->id, $this ),
'3.3.0',
'get_current_screen()->add_help_tab(), get_current_screen()->remove_help_tab()'
);
// Default help only if there is no old-style block of text and no new-style help tabs.
if ( empty( $old_help ) && ! $this->get_help_tabs() ) {
/**
* Filters the default legacy contextual help text.
*
* @since 2.8.0
* @deprecated 3.3.0 Use {@see get_current_screen()->add_help_tab()} or
* {@see get_current_screen()->remove_help_tab()} instead.
*
* @param string $old_help_default Default contextual help text.
*/
$default_help = apply_filters_deprecated(
'default_contextual_help',
array( '' ),
'3.3.0',
'get_current_screen()->add_help_tab(), get_current_screen()->remove_help_tab()'
);
if ( $default_help ) {
$old_help = '<p>' . $default_help . '</p>';
}
}
if ( $old_help ) {
$this->add_help_tab(
array(
'id' => 'old-contextual-help',
'title' => __( 'Overview' ),
'content' => $old_help,
)
);
}
$help_sidebar = $this->get_help_sidebar();
$help_class = 'hidden';
if ( ! $help_sidebar ) {
$help_class .= ' no-sidebar';
}
// Time to render!
?>
<div id="screen-meta" class="metabox-prefs">
<div id="contextual-help-wrap" class="<?php echo esc_attr( $help_class ); ?>" tabindex="-1" aria-label="<?php esc_attr_e( 'Contextual Help Tab' ); ?>">
<div id="contextual-help-back"></div>
<div id="contextual-help-columns">
<div class="contextual-help-tabs">
<ul>
<?php
$class = ' class="active"';
foreach ( $this->get_help_tabs() as $tab ) :
$link_id = "tab-link-{$tab['id']}";
$panel_id = "tab-panel-{$tab['id']}";
?>
<li id="<?php echo esc_attr( $link_id ); ?>"<?php echo $class; ?>>
<a href="<?php echo esc_url( "#$panel_id" ); ?>" aria-controls="<?php echo esc_attr( $panel_id ); ?>">
<?php echo esc_html( $tab['title'] ); ?>
</a>
</li>
<?php
$class = '';
endforeach;
?>
</ul>
</div>
<?php if ( $help_sidebar ) : ?>
<div class="contextual-help-sidebar">
<?php echo $help_sidebar; ?>
</div>
<?php endif; ?>
<div class="contextual-help-tabs-wrap">
<?php
$classes = 'help-tab-content active';
foreach ( $this->get_help_tabs() as $tab ) :
$panel_id = "tab-panel-{$tab['id']}";
?>
<div id="<?php echo esc_attr( $panel_id ); ?>" class="<?php echo $classes; ?>">
<?php
// Print tab content.
echo $tab['content'];
// If it exists, fire tab callback.
if ( ! empty( $tab['callback'] ) ) {
call_user_func_array( $tab['callback'], array( $this, $tab ) );
}
?>
</div>
<?php
$classes = 'help-tab-content';
endforeach;
?>
</div>
</div>
</div>
<?php
// Setup layout columns.
/**
* Filters the array of screen layout columns.
*
* This hook provides back-compat for plugins using the back-compat
* Filters instead of add_screen_option().
*
* @since 2.8.0
*
* @param array $empty_columns Empty array.
* @param string $screen_id Screen ID.
* @param WP_Screen $screen Current WP_Screen instance.
*/
$columns = apply_filters( 'screen_layout_columns', array(), $this->id, $this );
if ( ! empty( $columns ) && isset( $columns[ $this->id ] ) ) {
$this->add_option( 'layout_columns', array( 'max' => $columns[ $this->id ] ) );
}
if ( $this->get_option( 'layout_columns' ) ) {
$this->columns = (int) get_user_option( "screen_layout_$this->id" );
if ( ! $this->columns && $this->get_option( 'layout_columns', 'default' ) ) {
$this->columns = $this->get_option( 'layout_columns', 'default' );
}
}
$GLOBALS['screen_layout_columns'] = $this->columns; // Set the global for back-compat.
// Add screen options.
if ( $this->show_screen_options() ) {
$this->render_screen_options();
}
?>
</div>
<?php
if ( ! $this->get_help_tabs() && ! $this->show_screen_options() ) {
return;
}
?>
<div id="screen-meta-links">
<?php if ( $this->show_screen_options() ) : ?>
<div id="screen-options-link-wrap" class="hide-if-no-js screen-meta-toggle">
<button type="button" id="show-settings-link" class="button show-settings" aria-controls="screen-options-wrap" aria-expanded="false"><?php _e( 'Screen Options' ); ?></button>
</div>
<?php
endif;
if ( $this->get_help_tabs() ) :
?>
<div id="contextual-help-link-wrap" class="hide-if-no-js screen-meta-toggle">
<button type="button" id="contextual-help-link" class="button show-settings" aria-controls="contextual-help-wrap" aria-expanded="false"><?php _e( 'Help' ); ?></button>
</div>
<?php endif; ?>
</div>
<?php
}
```
[apply\_filters\_deprecated( 'contextual\_help', string $old\_help, string $screen\_id, WP\_Screen $screen )](../../hooks/contextual_help)
Filters the legacy contextual help text.
[apply\_filters\_deprecated( 'contextual\_help\_list', array $old\_compat\_help, WP\_Screen $screen )](../../hooks/contextual_help_list)
Filters the legacy contextual help list.
[apply\_filters\_deprecated( 'default\_contextual\_help', string $old\_help\_default )](../../hooks/default_contextual_help)
Filters the default legacy contextual help text.
[apply\_filters( 'screen\_layout\_columns', array $empty\_columns, string $screen\_id, WP\_Screen $screen )](../../hooks/screen_layout_columns)
Filters the array of screen layout columns.
| Uses | Description |
| --- | --- |
| [apply\_filters\_deprecated()](../../functions/apply_filters_deprecated) wp-includes/plugin.php | Fires functions attached to a deprecated filter hook. |
| [WP\_Screen::show\_screen\_options()](show_screen_options) wp-admin/includes/class-wp-screen.php | |
| [WP\_Screen::render\_screen\_options()](render_screen_options) wp-admin/includes/class-wp-screen.php | Renders the screen options tab. |
| [WP\_Screen::get\_help\_tabs()](get_help_tabs) wp-admin/includes/class-wp-screen.php | Gets the help tabs registered for the screen. |
| [WP\_Screen::add\_help\_tab()](add_help_tab) wp-admin/includes/class-wp-screen.php | Adds a help tab to the contextual help for the screen. |
| [WP\_Screen::get\_help\_sidebar()](get_help_sidebar) wp-admin/includes/class-wp-screen.php | Gets the content from a contextual help sidebar. |
| [WP\_Screen::get\_option()](get_option) wp-admin/includes/class-wp-screen.php | Gets the arguments for an option for the screen. |
| [WP\_Screen::add\_option()](add_option) wp-admin/includes/class-wp-screen.php | Adds an option for the screen. |
| [esc\_attr\_e()](../../functions/esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [get\_user\_option()](../../functions/get_user_option) wp-includes/user.php | Retrieves user option that can be either per Site or per Network. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Screen::set_parentage( string $parent_file ) WP\_Screen::set\_parentage( string $parent\_file )
==================================================
Sets the parent information for the screen.
This is called in admin-header.php after the menu parent for the screen has been determined.
`$parent_file` string Required The parent file of the screen. Typically the $parent\_file global. File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function set_parentage( $parent_file ) {
$this->parent_file = $parent_file;
list( $this->parent_base ) = explode( '?', $parent_file );
$this->parent_base = str_replace( '.php', '', $this->parent_base );
}
```
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Screen::set_current_screen() WP\_Screen::set\_current\_screen()
==================================
Makes the screen object the current screen.
* [set\_current\_screen()](../../functions/set_current_screen)
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function set_current_screen() {
global $current_screen, $taxnow, $typenow;
$current_screen = $this;
$typenow = $this->post_type;
$taxnow = $this->taxonomy;
/**
* Fires after the current screen has been set.
*
* @since 3.0.0
*
* @param WP_Screen $current_screen Current WP_Screen object.
*/
do_action( 'current_screen', $current_screen );
}
```
[do\_action( 'current\_screen', WP\_Screen $current\_screen )](../../hooks/current_screen)
Fires after the current screen has been set.
| Uses | Description |
| --- | --- |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Screen::get_columns(): int WP\_Screen::get\_columns(): int
===============================
Gets the number of layout columns the user has selected.
The layout\_columns option controls the max number and default number of columns. This method returns the number of columns within that range selected by the user via Screen Options. If no selection has been made, the default provisioned in layout\_columns is returned. If the screen does not support selecting the number of layout columns, 0 is returned.
int Number of columns to display.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function get_columns() {
return $this->columns;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_screen\_layout()](render_screen_layout) wp-admin/includes/class-wp-screen.php | Renders the option for number of columns on the page. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Screen::get_screen_reader_text( string $key ): string WP\_Screen::get\_screen\_reader\_text( string $key ): string
============================================================
Gets a screen reader text string.
`$key` string Required Screen reader text array named key. string Screen reader text string.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function get_screen_reader_text( $key ) {
if ( ! isset( $this->_screen_reader_content[ $key ] ) ) {
return null;
}
return $this->_screen_reader_content[ $key ];
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Screen::set_screen_reader_content( array $content = array() ) WP\_Screen::set\_screen\_reader\_content( array $content = array() )
====================================================================
Adds accessible hidden headings and text for the screen.
`$content` array Optional An associative array of screen reader text strings.
* `heading_views`stringScreen reader text for the filter links heading.
Default 'Filter items list'.
* `heading_pagination`stringScreen reader text for the pagination heading.
Default 'Items list navigation'.
* `heading_list`stringScreen reader text for the items list heading.
Default 'Items list'.
Default: `array()`
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function set_screen_reader_content( $content = array() ) {
$defaults = array(
'heading_views' => __( 'Filter items list' ),
'heading_pagination' => __( 'Items list navigation' ),
'heading_list' => __( 'Items list' ),
);
$content = wp_parse_args( $content, $defaults );
$this->_screen_reader_content = $content;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress WP_Screen::get_screen_reader_content(): array WP\_Screen::get\_screen\_reader\_content(): array
=================================================
Gets the accessible hidden headings and text used in the screen.
* [set\_screen\_reader\_content()](../../functions/set_screen_reader_content): For more information on the array format.
array An associative array of screen reader text strings.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function get_screen_reader_content() {
return $this->_screen_reader_content;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Screen::get_help_tab( string $id ): array WP\_Screen::get\_help\_tab( string $id ): array
===============================================
Gets the arguments for a help tab.
`$id` string Required Help Tab ID. array Help tab arguments.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function get_help_tab( $id ) {
if ( ! isset( $this->_help_tabs[ $id ] ) ) {
return null;
}
return $this->_help_tabs[ $id ];
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Screen::is_block_editor( bool $set = null ): bool WP\_Screen::is\_block\_editor( bool $set = null ): bool
=======================================================
Sets or returns whether the block editor is loading on the current screen.
`$set` bool Optional Sets whether the block editor is loading on the current screen or not. Default: `null`
bool True if the block editor is being loaded, false otherwise.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function is_block_editor( $set = null ) {
if ( null !== $set ) {
$this->is_block_editor = (bool) $set;
}
return $this->is_block_editor;
}
```
| Used By | Description |
| --- | --- |
| [wp\_global\_styles\_render\_svg\_filters()](../../functions/wp_global_styles_render_svg_filters) wp-includes/script-loader.php | Renders the SVG filters supplied by theme.json. |
| [WP\_Privacy\_Policy\_Content::notice()](../wp_privacy_policy_content/notice) wp-admin/includes/class-wp-privacy-policy-content.php | Add a notice with a link to the guide when editing the privacy policy page. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_Screen::__construct() WP\_Screen::\_\_construct()
===========================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Constructor
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
private function __construct() {}
```
| Used By | Description |
| --- | --- |
| [WP\_Screen::get()](get) wp-admin/includes/class-wp-screen.php | Fetches a screen object. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Screen::get_option( string $option, string|false $key = false ): string WP\_Screen::get\_option( string $option, string|false $key = false ): string
============================================================================
Gets the arguments for an option for the screen.
`$option` string Required Option name. `$key` string|false Optional Specific array key for when the option is an array.
Default: `false`
string The option value if set, null otherwise.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function get_option( $option, $key = false ) {
if ( ! isset( $this->_options[ $option ] ) ) {
return null;
}
if ( $key ) {
if ( isset( $this->_options[ $option ][ $key ] ) ) {
return $this->_options[ $option ][ $key ];
}
return null;
}
return $this->_options[ $option ];
}
```
| Used By | Description |
| --- | --- |
| [WP\_Screen::show\_screen\_options()](show_screen_options) wp-admin/includes/class-wp-screen.php | |
| [WP\_Screen::render\_screen\_layout()](render_screen_layout) wp-admin/includes/class-wp-screen.php | Renders the option for number of columns on the page. |
| [WP\_Screen::render\_per\_page\_options()](render_per_page_options) wp-admin/includes/class-wp-screen.php | Renders the items per page option. |
| [WP\_Screen::render\_screen\_meta()](render_screen_meta) wp-admin/includes/class-wp-screen.php | Renders the screen’s help section. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Screen::set_help_sidebar( string $content ) WP\_Screen::set\_help\_sidebar( string $content )
=================================================
Adds a sidebar to the contextual help for the screen.
Call this in template files after admin.php is loaded and before admin-header.php is loaded to add a sidebar to the contextual help.
`$content` string Required Sidebar content in plain text or HTML. File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function set_help_sidebar( $content ) {
$this->_help_sidebar = $content;
}
```
| Used By | Description |
| --- | --- |
| [Custom\_Image\_Header::help()](../custom_image_header/help) wp-admin/includes/class-custom-image-header.php | Adds contextual help. |
| [Custom\_Background::admin\_load()](../custom_background/admin_load) wp-admin/includes/class-custom-background.php | Sets up the enqueue for the CSS & JavaScript files. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Screen::render_screen_reader_content( string $key = '', string $tag = 'h2' ) WP\_Screen::render\_screen\_reader\_content( string $key = '', string $tag = 'h2' )
===================================================================================
Renders screen reader text.
`$key` string Optional The screen reader text array named key. Default: `''`
`$tag` string Optional The HTML tag to wrap the screen reader text. Default h2. Default: `'h2'`
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function render_screen_reader_content( $key = '', $tag = 'h2' ) {
if ( ! isset( $this->_screen_reader_content[ $key ] ) ) {
return;
}
echo "<$tag class='screen-reader-text'>" . $this->_screen_reader_content[ $key ] . "</$tag>";
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Screen::add_old_compat_help( WP_Screen $screen, string $help ) WP\_Screen::add\_old\_compat\_help( WP\_Screen $screen, string $help )
======================================================================
Sets the old string-based contextual help for the screen for backward compatibility.
`$screen` [WP\_Screen](../wp_screen) Required A screen object. `$help` string Required Help text. File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public static function add_old_compat_help( $screen, $help ) {
self::$_old_compat_help[ $screen->id ] = $help;
}
```
| Used By | Description |
| --- | --- |
| [add\_contextual\_help()](../../functions/add_contextual_help) wp-admin/includes/deprecated.php | Add contextual help text for a page. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Screen::get( string|WP_Screen $hook_name = '' ): WP_Screen WP\_Screen::get( string|WP\_Screen $hook\_name = '' ): WP\_Screen
=================================================================
Fetches a screen object.
`$hook_name` string|[WP\_Screen](../wp_screen) Optional The hook name (also known as the hook suffix) used to determine the screen.
Defaults to the current $hook\_suffix global. Default: `''`
[WP\_Screen](../wp_screen) Screen object.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public static function get( $hook_name = '' ) {
if ( $hook_name instanceof WP_Screen ) {
return $hook_name;
}
$id = '';
$post_type = null;
$taxonomy = null;
$in_admin = false;
$action = '';
$is_block_editor = false;
if ( $hook_name ) {
$id = $hook_name;
} elseif ( ! empty( $GLOBALS['hook_suffix'] ) ) {
$id = $GLOBALS['hook_suffix'];
}
// For those pesky meta boxes.
if ( $hook_name && post_type_exists( $hook_name ) ) {
$post_type = $id;
$id = 'post'; // Changes later. Ends up being $base.
} else {
if ( '.php' === substr( $id, -4 ) ) {
$id = substr( $id, 0, -4 );
}
if ( in_array( $id, array( 'post-new', 'link-add', 'media-new', 'user-new' ), true ) ) {
$id = substr( $id, 0, -4 );
$action = 'add';
}
}
if ( ! $post_type && $hook_name ) {
if ( '-network' === substr( $id, -8 ) ) {
$id = substr( $id, 0, -8 );
$in_admin = 'network';
} elseif ( '-user' === substr( $id, -5 ) ) {
$id = substr( $id, 0, -5 );
$in_admin = 'user';
}
$id = sanitize_key( $id );
if ( 'edit-comments' !== $id && 'edit-tags' !== $id && 'edit-' === substr( $id, 0, 5 ) ) {
$maybe = substr( $id, 5 );
if ( taxonomy_exists( $maybe ) ) {
$id = 'edit-tags';
$taxonomy = $maybe;
} elseif ( post_type_exists( $maybe ) ) {
$id = 'edit';
$post_type = $maybe;
}
}
if ( ! $in_admin ) {
$in_admin = 'site';
}
} else {
if ( defined( 'WP_NETWORK_ADMIN' ) && WP_NETWORK_ADMIN ) {
$in_admin = 'network';
} elseif ( defined( 'WP_USER_ADMIN' ) && WP_USER_ADMIN ) {
$in_admin = 'user';
} else {
$in_admin = 'site';
}
}
if ( 'index' === $id ) {
$id = 'dashboard';
} elseif ( 'front' === $id ) {
$in_admin = false;
}
$base = $id;
// If this is the current screen, see if we can be more accurate for post types and taxonomies.
if ( ! $hook_name ) {
if ( isset( $_REQUEST['post_type'] ) ) {
$post_type = post_type_exists( $_REQUEST['post_type'] ) ? $_REQUEST['post_type'] : false;
}
if ( isset( $_REQUEST['taxonomy'] ) ) {
$taxonomy = taxonomy_exists( $_REQUEST['taxonomy'] ) ? $_REQUEST['taxonomy'] : false;
}
switch ( $base ) {
case 'post':
if ( isset( $_GET['post'] ) && isset( $_POST['post_ID'] ) && (int) $_GET['post'] !== (int) $_POST['post_ID'] ) {
wp_die( __( 'A post ID mismatch has been detected.' ), __( 'Sorry, you are not allowed to edit this item.' ), 400 );
} elseif ( isset( $_GET['post'] ) ) {
$post_id = (int) $_GET['post'];
} elseif ( isset( $_POST['post_ID'] ) ) {
$post_id = (int) $_POST['post_ID'];
} else {
$post_id = 0;
}
if ( $post_id ) {
$post = get_post( $post_id );
if ( $post ) {
$post_type = $post->post_type;
/** This filter is documented in wp-admin/post.php */
$replace_editor = apply_filters( 'replace_editor', false, $post );
if ( ! $replace_editor ) {
$is_block_editor = use_block_editor_for_post( $post );
}
}
}
break;
case 'edit-tags':
case 'term':
if ( null === $post_type && is_object_in_taxonomy( 'post', $taxonomy ? $taxonomy : 'post_tag' ) ) {
$post_type = 'post';
}
break;
case 'upload':
$post_type = 'attachment';
break;
}
}
switch ( $base ) {
case 'post':
if ( null === $post_type ) {
$post_type = 'post';
}
// When creating a new post, use the default block editor support value for the post type.
if ( empty( $post_id ) ) {
$is_block_editor = use_block_editor_for_post_type( $post_type );
}
$id = $post_type;
break;
case 'edit':
if ( null === $post_type ) {
$post_type = 'post';
}
$id .= '-' . $post_type;
break;
case 'edit-tags':
case 'term':
if ( null === $taxonomy ) {
$taxonomy = 'post_tag';
}
// The edit-tags ID does not contain the post type. Look for it in the request.
if ( null === $post_type ) {
$post_type = 'post';
if ( isset( $_REQUEST['post_type'] ) && post_type_exists( $_REQUEST['post_type'] ) ) {
$post_type = $_REQUEST['post_type'];
}
}
$id = 'edit-' . $taxonomy;
break;
}
if ( 'network' === $in_admin ) {
$id .= '-network';
$base .= '-network';
} elseif ( 'user' === $in_admin ) {
$id .= '-user';
$base .= '-user';
}
if ( isset( self::$_registry[ $id ] ) ) {
$screen = self::$_registry[ $id ];
if ( get_current_screen() === $screen ) {
return $screen;
}
} else {
$screen = new self();
$screen->id = $id;
}
$screen->base = $base;
$screen->action = $action;
$screen->post_type = (string) $post_type;
$screen->taxonomy = (string) $taxonomy;
$screen->is_user = ( 'user' === $in_admin );
$screen->is_network = ( 'network' === $in_admin );
$screen->in_admin = $in_admin;
$screen->is_block_editor = $is_block_editor;
self::$_registry[ $id ] = $screen;
return $screen;
}
```
[apply\_filters( 'replace\_editor', bool $replace, WP\_Post $post )](../../hooks/replace_editor)
Allows replacement of the editor.
| Uses | Description |
| --- | --- |
| [use\_block\_editor\_for\_post\_type()](../../functions/use_block_editor_for_post_type) wp-includes/post.php | Returns whether a post type is compatible with the block editor. |
| [use\_block\_editor\_for\_post()](../../functions/use_block_editor_for_post) wp-includes/post.php | Returns whether the post can be edited in the block editor. |
| [get\_current\_screen()](../../functions/get_current_screen) wp-admin/includes/screen.php | Get the current screen object |
| [WP\_Screen::\_\_construct()](__construct) wp-admin/includes/class-wp-screen.php | Constructor |
| [is\_object\_in\_taxonomy()](../../functions/is_object_in_taxonomy) wp-includes/taxonomy.php | Determines if the given object type is associated with the given taxonomy. |
| [taxonomy\_exists()](../../functions/taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| [post\_type\_exists()](../../functions/post_type_exists) wp-includes/post.php | Determines whether a post type is registered. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [sanitize\_key()](../../functions/sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menus\_Panel::render\_screen\_options()](../wp_customize_nav_menus_panel/render_screen_options) wp-includes/customize/class-wp-customize-nav-menus-panel.php | Render screen options for Menus. |
| [set\_current\_screen()](../../functions/set_current_screen) wp-admin/includes/screen.php | Set the current screen object |
| [convert\_to\_screen()](../../functions/convert_to_screen) wp-admin/includes/template.php | Converts a screen string to a screen object. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Screen::get_help_sidebar(): string WP\_Screen::get\_help\_sidebar(): string
========================================
Gets the content from a contextual help sidebar.
string Contents of the help sidebar.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function get_help_sidebar() {
return $this->_help_sidebar;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_screen\_meta()](render_screen_meta) wp-admin/includes/class-wp-screen.php | Renders the screen’s help section. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Screen::render_screen_options( array $options = array() ) WP\_Screen::render\_screen\_options( array $options = array() )
===============================================================
Renders the screen options tab.
`$options` array Optional Options for the tab.
* `wrap`boolWhether the screen-options-wrap div will be included. Defaults to true.
Default: `array()`
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function render_screen_options( $options = array() ) {
$options = wp_parse_args(
$options,
array(
'wrap' => true,
)
);
$wrapper_start = '';
$wrapper_end = '';
$form_start = '';
$form_end = '';
// Output optional wrapper.
if ( $options['wrap'] ) {
$wrapper_start = '<div id="screen-options-wrap" class="hidden" tabindex="-1" aria-label="' . esc_attr__( 'Screen Options Tab' ) . '">';
$wrapper_end = '</div>';
}
// Don't output the form and nonce for the widgets accessibility mode links.
if ( 'widgets' !== $this->base ) {
$form_start = "\n<form id='adv-settings' method='post'>\n";
$form_end = "\n" . wp_nonce_field( 'screen-options-nonce', 'screenoptionnonce', false, false ) . "\n</form>\n";
}
echo $wrapper_start . $form_start;
$this->render_meta_boxes_preferences();
$this->render_list_table_columns_preferences();
$this->render_screen_layout();
$this->render_per_page_options();
$this->render_view_mode();
echo $this->_screen_settings;
/**
* Filters whether to show the Screen Options submit button.
*
* @since 4.4.0
*
* @param bool $show_button Whether to show Screen Options submit button.
* Default false.
* @param WP_Screen $screen Current WP_Screen instance.
*/
$show_button = apply_filters( 'screen_options_show_submit', false, $this );
if ( $show_button ) {
submit_button( __( 'Apply' ), 'primary', 'screen-options-apply', true );
}
echo $form_end . $wrapper_end;
}
```
[apply\_filters( 'screen\_options\_show\_submit', bool $show\_button, WP\_Screen $screen )](../../hooks/screen_options_show_submit)
Filters whether to show the Screen Options submit button.
| Uses | Description |
| --- | --- |
| [WP\_Screen::render\_meta\_boxes\_preferences()](render_meta_boxes_preferences) wp-admin/includes/class-wp-screen.php | Renders the meta boxes preferences. |
| [WP\_Screen::render\_list\_table\_columns\_preferences()](render_list_table_columns_preferences) wp-admin/includes/class-wp-screen.php | Renders the list table columns preferences. |
| [WP\_Screen::render\_view\_mode()](render_view_mode) wp-admin/includes/class-wp-screen.php | Renders the list table view mode preferences. |
| [WP\_Screen::render\_screen\_layout()](render_screen_layout) wp-admin/includes/class-wp-screen.php | Renders the option for number of columns on the page. |
| [WP\_Screen::render\_per\_page\_options()](render_per_page_options) wp-admin/includes/class-wp-screen.php | Renders the items per page option. |
| [submit\_button()](../../functions/submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [esc\_attr\_\_()](../../functions/esc_attr__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in an attribute. |
| [wp\_nonce\_field()](../../functions/wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Screen::render\_screen\_meta()](render_screen_meta) wp-admin/includes/class-wp-screen.php | Renders the screen’s help section. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
| programming_docs |
wordpress WP_Screen::in_admin( string $admin = null ): bool WP\_Screen::in\_admin( string $admin = null ): bool
===================================================
Indicates whether the screen is in a particular admin.
`$admin` string Optional The admin to check against (network | user | site).
If empty any of the three admins will result in true. Default: `null`
bool True if the screen is in the indicated admin, false otherwise.
File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/)
```
public function in_admin( $admin = null ) {
if ( empty( $admin ) ) {
return (bool) $this->in_admin;
}
return ( $admin === $this->in_admin );
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress Requests_Exception_HTTP_Unknown::__construct( string|null $reason = null, mixed $data = null ) Requests\_Exception\_HTTP\_Unknown::\_\_construct( string|null $reason = null, mixed $data = null )
===================================================================================================
Create a new exception
If `$data` is an instance of [Requests\_Response](../requests_response), uses the status code from it. Otherwise, sets as 0
`$reason` string|null Optional Reason phrase Default: `null`
`$data` mixed Optional Associated data Default: `null`
File: `wp-includes/Requests/Exception/HTTP/Unknown.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/unknown.php/)
```
public function __construct($reason = null, $data = null) {
if ($data instanceof Requests_Response) {
$this->code = $data->status_code;
}
parent::__construct($reason, $data);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception\_HTTP::\_\_construct()](../requests_exception_http/__construct) wp-includes/Requests/Exception/HTTP.php | Create a new exception |
wordpress Custom_Background::ajax_background_add() Custom\_Background::ajax\_background\_add()
===========================================
Handles Ajax request for adding custom background context to an attachment.
Triggers when the user adds a new background image from the Media Manager.
File: `wp-admin/includes/class-custom-background.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-background.php/)
```
public function ajax_background_add() {
check_ajax_referer( 'background-add', 'nonce' );
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_send_json_error();
}
$attachment_id = absint( $_POST['attachment_id'] );
if ( $attachment_id < 1 ) {
wp_send_json_error();
}
update_post_meta( $attachment_id, '_wp_attachment_is_custom_background', get_stylesheet() );
wp_send_json_success();
}
```
| Uses | Description |
| --- | --- |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| [get\_stylesheet()](../../functions/get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [check\_ajax\_referer()](../../functions/check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [wp\_send\_json\_error()](../../functions/wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [wp\_send\_json\_success()](../../functions/wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress Custom_Background::init() Custom\_Background::init()
==========================
Sets up the hooks for the Custom Background admin page.
File: `wp-admin/includes/class-custom-background.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-background.php/)
```
public function init() {
$page = add_theme_page( __( 'Background' ), __( 'Background' ), 'edit_theme_options', 'custom-background', array( $this, 'admin_page' ) );
if ( ! $page ) {
return;
}
add_action( "load-{$page}", array( $this, 'admin_load' ) );
add_action( "load-{$page}", array( $this, 'take_action' ), 49 );
add_action( "load-{$page}", array( $this, 'handle_upload' ), 49 );
if ( $this->admin_header_callback ) {
add_action( "admin_head-{$page}", $this->admin_header_callback, 51 );
}
}
```
| Uses | Description |
| --- | --- |
| [add\_theme\_page()](../../functions/add_theme_page) wp-admin/includes/plugin.php | Adds a submenu page to the Appearance main menu. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress Custom_Background::handle_upload() Custom\_Background::handle\_upload()
====================================
Handles an Image upload for the background image.
File: `wp-admin/includes/class-custom-background.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-background.php/)
```
public function handle_upload() {
if ( empty( $_FILES ) ) {
return;
}
check_admin_referer( 'custom-background-upload', '_wpnonce-custom-background-upload' );
$overrides = array( 'test_form' => false );
$uploaded_file = $_FILES['import'];
$wp_filetype = wp_check_filetype_and_ext( $uploaded_file['tmp_name'], $uploaded_file['name'] );
if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) ) {
wp_die( __( 'The uploaded file is not a valid image. Please try again.' ) );
}
$file = wp_handle_upload( $uploaded_file, $overrides );
if ( isset( $file['error'] ) ) {
wp_die( $file['error'] );
}
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$filename = wp_basename( $file );
// Construct the attachment array.
$attachment = array(
'post_title' => $filename,
'post_content' => $url,
'post_mime_type' => $type,
'guid' => $url,
'context' => 'custom-background',
);
// Save the data.
$id = wp_insert_attachment( $attachment, $file );
// Add the metadata.
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
update_post_meta( $id, '_wp_attachment_is_custom_background', get_option( 'stylesheet' ) );
set_theme_mod( 'background_image', sanitize_url( $url ) );
$thumbnail = wp_get_attachment_image_src( $id, 'thumbnail' );
set_theme_mod( 'background_image_thumb', sanitize_url( $thumbnail[0] ) );
/** This action is documented in wp-admin/includes/class-custom-image-header.php */
do_action( 'wp_create_file_in_uploads', $file, $id ); // For replication.
$this->updated = true;
}
```
[do\_action( 'wp\_create\_file\_in\_uploads', string $file, int $attachment\_id )](../../hooks/wp_create_file_in_uploads)
Fires after the header image is set or an error is returned.
| Uses | Description |
| --- | --- |
| [wp\_generate\_attachment\_metadata()](../../functions/wp_generate_attachment_metadata) wp-admin/includes/image.php | Generates attachment meta data and create image sub-sizes for images. |
| [wp\_handle\_upload()](../../functions/wp_handle_upload) wp-admin/includes/file.php | Wrapper for [\_wp\_handle\_upload()](../../functions/_wp_handle_upload) . |
| [set\_theme\_mod()](../../functions/set_theme_mod) wp-includes/theme.php | Updates theme modification value for the active theme. |
| [check\_admin\_referer()](../../functions/check_admin_referer) wp-includes/pluggable.php | Ensures intent by verifying that a user was referred from another admin page with the correct security nonce. |
| [sanitize\_url()](../../functions/sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [wp\_check\_filetype\_and\_ext()](../../functions/wp_check_filetype_and_ext) wp-includes/functions.php | Attempts to determine the real file type of a file. |
| [wp\_get\_attachment\_image\_src()](../../functions/wp_get_attachment_image_src) wp-includes/media.php | Retrieves an image to represent an attachment. |
| [wp\_insert\_attachment()](../../functions/wp_insert_attachment) wp-includes/post.php | Inserts an attachment. |
| [wp\_update\_attachment\_metadata()](../../functions/wp_update_attachment_metadata) wp-includes/post.php | Updates metadata for an attachment. |
| [wp\_match\_mime\_types()](../../functions/wp_match_mime_types) wp-includes/post.php | Checks a MIME-Type against a list. |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress Custom_Background::take_action() Custom\_Background::take\_action()
==================================
Executes custom background modification.
File: `wp-admin/includes/class-custom-background.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-background.php/)
```
public function take_action() {
if ( empty( $_POST ) ) {
return;
}
if ( isset( $_POST['reset-background'] ) ) {
check_admin_referer( 'custom-background-reset', '_wpnonce-custom-background-reset' );
remove_theme_mod( 'background_image' );
remove_theme_mod( 'background_image_thumb' );
$this->updated = true;
return;
}
if ( isset( $_POST['remove-background'] ) ) {
// @todo Uploaded files are not removed here.
check_admin_referer( 'custom-background-remove', '_wpnonce-custom-background-remove' );
set_theme_mod( 'background_image', '' );
set_theme_mod( 'background_image_thumb', '' );
$this->updated = true;
wp_safe_redirect( $_POST['_wp_http_referer'] );
return;
}
if ( isset( $_POST['background-preset'] ) ) {
check_admin_referer( 'custom-background' );
if ( in_array( $_POST['background-preset'], array( 'default', 'fill', 'fit', 'repeat', 'custom' ), true ) ) {
$preset = $_POST['background-preset'];
} else {
$preset = 'default';
}
set_theme_mod( 'background_preset', $preset );
}
if ( isset( $_POST['background-position'] ) ) {
check_admin_referer( 'custom-background' );
$position = explode( ' ', $_POST['background-position'] );
if ( in_array( $position[0], array( 'left', 'center', 'right' ), true ) ) {
$position_x = $position[0];
} else {
$position_x = 'left';
}
if ( in_array( $position[1], array( 'top', 'center', 'bottom' ), true ) ) {
$position_y = $position[1];
} else {
$position_y = 'top';
}
set_theme_mod( 'background_position_x', $position_x );
set_theme_mod( 'background_position_y', $position_y );
}
if ( isset( $_POST['background-size'] ) ) {
check_admin_referer( 'custom-background' );
if ( in_array( $_POST['background-size'], array( 'auto', 'contain', 'cover' ), true ) ) {
$size = $_POST['background-size'];
} else {
$size = 'auto';
}
set_theme_mod( 'background_size', $size );
}
if ( isset( $_POST['background-repeat'] ) ) {
check_admin_referer( 'custom-background' );
$repeat = $_POST['background-repeat'];
if ( 'no-repeat' !== $repeat ) {
$repeat = 'repeat';
}
set_theme_mod( 'background_repeat', $repeat );
}
if ( isset( $_POST['background-attachment'] ) ) {
check_admin_referer( 'custom-background' );
$attachment = $_POST['background-attachment'];
if ( 'fixed' !== $attachment ) {
$attachment = 'scroll';
}
set_theme_mod( 'background_attachment', $attachment );
}
if ( isset( $_POST['background-color'] ) ) {
check_admin_referer( 'custom-background' );
$color = preg_replace( '/[^0-9a-fA-F]/', '', $_POST['background-color'] );
if ( strlen( $color ) === 6 || strlen( $color ) === 3 ) {
set_theme_mod( 'background_color', $color );
} else {
set_theme_mod( 'background_color', '' );
}
}
$this->updated = true;
}
```
| Uses | Description |
| --- | --- |
| [remove\_theme\_mod()](../../functions/remove_theme_mod) wp-includes/theme.php | Removes theme modification name from active theme list. |
| [set\_theme\_mod()](../../functions/set_theme_mod) wp-includes/theme.php | Updates theme modification value for the active theme. |
| [wp\_safe\_redirect()](../../functions/wp_safe_redirect) wp-includes/pluggable.php | Performs a safe (local) redirect, using [wp\_redirect()](../../functions/wp_redirect) . |
| [check\_admin\_referer()](../../functions/check_admin_referer) wp-includes/pluggable.php | Ensures intent by verifying that a user was referred from another admin page with the correct security nonce. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress Custom_Background::attachment_fields_to_edit( array $form_fields ): array Custom\_Background::attachment\_fields\_to\_edit( array $form\_fields ): array
==============================================================================
This method has been deprecated.
`$form_fields` array Required array $form\_fields
File: `wp-admin/includes/class-custom-background.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-background.php/)
```
public function attachment_fields_to_edit( $form_fields ) {
return $form_fields;
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | This method has been deprecated. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress Custom_Background::__construct( callable $admin_header_callback = '', callable $admin_image_div_callback = '' ) Custom\_Background::\_\_construct( callable $admin\_header\_callback = '', callable $admin\_image\_div\_callback = '' )
=======================================================================================================================
Constructor – Registers administration header callback.
`$admin_header_callback` callable Optional Default: `''`
`$admin_image_div_callback` callable Optional custom image div output callback. Default: `''`
File: `wp-admin/includes/class-custom-background.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-background.php/)
```
public function __construct( $admin_header_callback = '', $admin_image_div_callback = '' ) {
$this->admin_header_callback = $admin_header_callback;
$this->admin_image_div_callback = $admin_image_div_callback;
add_action( 'admin_menu', array( $this, 'init' ) );
add_action( 'wp_ajax_custom-background-add', array( $this, 'ajax_background_add' ) );
// Unused since 3.5.0.
add_action( 'wp_ajax_set-background-image', array( $this, 'wp_set_background_image' ) );
}
```
| Uses | Description |
| --- | --- |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Used By | Description |
| --- | --- |
| [\_custom\_header\_background\_just\_in\_time()](../../functions/_custom_header_background_just_in_time) wp-includes/theme.php | Registers the internal custom header and background routines. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress Custom_Background::filter_upload_tabs( array $tabs ): array Custom\_Background::filter\_upload\_tabs( array $tabs ): array
==============================================================
This method has been deprecated.
`$tabs` array Required array $tabs
File: `wp-admin/includes/class-custom-background.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-background.php/)
```
public function filter_upload_tabs( $tabs ) {
return $tabs;
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | This method has been deprecated. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress Custom_Background::admin_page() Custom\_Background::admin\_page()
=================================
Displays the custom background page.
File: `wp-admin/includes/class-custom-background.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-background.php/)
```
public function admin_page() {
?>
<div class="wrap" id="custom-background">
<h1><?php _e( 'Custom Background' ); ?></h1>
<?php if ( current_user_can( 'customize' ) ) { ?>
<div class="notice notice-info hide-if-no-customize">
<p>
<?php
printf(
/* translators: %s: URL to background image configuration in Customizer. */
__( 'You can now manage and live-preview Custom Backgrounds in the <a href="%s">Customizer</a>.' ),
admin_url( 'customize.php?autofocus[control]=background_image' )
);
?>
</p>
</div>
<?php } ?>
<?php if ( ! empty( $this->updated ) ) { ?>
<div id="message" class="updated">
<p>
<?php
/* translators: %s: Home URL. */
printf( __( 'Background updated. <a href="%s">Visit your site</a> to see how it looks.' ), esc_url( home_url( '/' ) ) );
?>
</p>
</div>
<?php } ?>
<h2><?php _e( 'Background Image' ); ?></h2>
<table class="form-table" role="presentation">
<tbody>
<tr>
<th scope="row"><?php _e( 'Preview' ); ?></th>
<td>
<?php
if ( $this->admin_image_div_callback ) {
call_user_func( $this->admin_image_div_callback );
} else {
$background_styles = '';
$bgcolor = get_background_color();
if ( $bgcolor ) {
$background_styles .= 'background-color: #' . $bgcolor . ';';
}
$background_image_thumb = get_background_image();
if ( $background_image_thumb ) {
$background_image_thumb = esc_url( set_url_scheme( get_theme_mod( 'background_image_thumb', str_replace( '%', '%%', $background_image_thumb ) ) ) );
$background_position_x = get_theme_mod( 'background_position_x', get_theme_support( 'custom-background', 'default-position-x' ) );
$background_position_y = get_theme_mod( 'background_position_y', get_theme_support( 'custom-background', 'default-position-y' ) );
$background_size = get_theme_mod( 'background_size', get_theme_support( 'custom-background', 'default-size' ) );
$background_repeat = get_theme_mod( 'background_repeat', get_theme_support( 'custom-background', 'default-repeat' ) );
$background_attachment = get_theme_mod( 'background_attachment', get_theme_support( 'custom-background', 'default-attachment' ) );
// Background-image URL must be single quote, see below.
$background_styles .= " background-image: url('$background_image_thumb');"
. " background-size: $background_size;"
. " background-position: $background_position_x $background_position_y;"
. " background-repeat: $background_repeat;"
. " background-attachment: $background_attachment;";
}
?>
<div id="custom-background-image" style="<?php echo $background_styles; ?>"><?php // Must be double quote, see above. ?>
<?php if ( $background_image_thumb ) { ?>
<img class="custom-background-image" src="<?php echo $background_image_thumb; ?>" style="visibility:hidden;" alt="" /><br />
<img class="custom-background-image" src="<?php echo $background_image_thumb; ?>" style="visibility:hidden;" alt="" />
<?php } ?>
</div>
<?php } ?>
</td>
</tr>
<?php if ( get_background_image() ) : ?>
<tr>
<th scope="row"><?php _e( 'Remove Image' ); ?></th>
<td>
<form method="post">
<?php wp_nonce_field( 'custom-background-remove', '_wpnonce-custom-background-remove' ); ?>
<?php submit_button( __( 'Remove Background Image' ), '', 'remove-background', false ); ?><br />
<?php _e( 'This will remove the background image. You will not be able to restore any customizations.' ); ?>
</form>
</td>
</tr>
<?php endif; ?>
<?php $default_image = get_theme_support( 'custom-background', 'default-image' ); ?>
<?php if ( $default_image && get_background_image() !== $default_image ) : ?>
<tr>
<th scope="row"><?php _e( 'Restore Original Image' ); ?></th>
<td>
<form method="post">
<?php wp_nonce_field( 'custom-background-reset', '_wpnonce-custom-background-reset' ); ?>
<?php submit_button( __( 'Restore Original Image' ), '', 'reset-background', false ); ?><br />
<?php _e( 'This will restore the original background image. You will not be able to restore any customizations.' ); ?>
</form>
</td>
</tr>
<?php endif; ?>
<?php if ( current_user_can( 'upload_files' ) ) : ?>
<tr>
<th scope="row"><?php _e( 'Select Image' ); ?></th>
<td><form enctype="multipart/form-data" id="upload-form" class="wp-upload-form" method="post">
<p>
<label for="upload"><?php _e( 'Choose an image from your computer:' ); ?></label><br />
<input type="file" id="upload" name="import" />
<input type="hidden" name="action" value="save" />
<?php wp_nonce_field( 'custom-background-upload', '_wpnonce-custom-background-upload' ); ?>
<?php submit_button( __( 'Upload' ), '', 'submit', false ); ?>
</p>
<p>
<label for="choose-from-library-link"><?php _e( 'Or choose an image from your media library:' ); ?></label><br />
<button id="choose-from-library-link" class="button"
data-choose="<?php esc_attr_e( 'Choose a Background Image' ); ?>"
data-update="<?php esc_attr_e( 'Set as background' ); ?>"><?php _e( 'Choose Image' ); ?></button>
</p>
</form>
</td>
</tr>
<?php endif; ?>
</tbody>
</table>
<h2><?php _e( 'Display Options' ); ?></h2>
<form method="post">
<table class="form-table" role="presentation">
<tbody>
<?php if ( get_background_image() ) : ?>
<input name="background-preset" type="hidden" value="custom">
<?php
$background_position = sprintf(
'%s %s',
get_theme_mod( 'background_position_x', get_theme_support( 'custom-background', 'default-position-x' ) ),
get_theme_mod( 'background_position_y', get_theme_support( 'custom-background', 'default-position-y' ) )
);
$background_position_options = array(
array(
'left top' => array(
'label' => __( 'Top Left' ),
'icon' => 'dashicons dashicons-arrow-left-alt',
),
'center top' => array(
'label' => __( 'Top' ),
'icon' => 'dashicons dashicons-arrow-up-alt',
),
'right top' => array(
'label' => __( 'Top Right' ),
'icon' => 'dashicons dashicons-arrow-right-alt',
),
),
array(
'left center' => array(
'label' => __( 'Left' ),
'icon' => 'dashicons dashicons-arrow-left-alt',
),
'center center' => array(
'label' => __( 'Center' ),
'icon' => 'background-position-center-icon',
),
'right center' => array(
'label' => __( 'Right' ),
'icon' => 'dashicons dashicons-arrow-right-alt',
),
),
array(
'left bottom' => array(
'label' => __( 'Bottom Left' ),
'icon' => 'dashicons dashicons-arrow-left-alt',
),
'center bottom' => array(
'label' => __( 'Bottom' ),
'icon' => 'dashicons dashicons-arrow-down-alt',
),
'right bottom' => array(
'label' => __( 'Bottom Right' ),
'icon' => 'dashicons dashicons-arrow-right-alt',
),
),
);
?>
<tr>
<th scope="row"><?php _e( 'Image Position' ); ?></th>
<td><fieldset><legend class="screen-reader-text"><span><?php _e( 'Image Position' ); ?></span></legend>
<div class="background-position-control">
<?php foreach ( $background_position_options as $group ) : ?>
<div class="button-group">
<?php foreach ( $group as $value => $input ) : ?>
<label>
<input class="ui-helper-hidden-accessible" name="background-position" type="radio" value="<?php echo esc_attr( $value ); ?>"<?php checked( $value, $background_position ); ?>>
<span class="button display-options position"><span class="<?php echo esc_attr( $input['icon'] ); ?>" aria-hidden="true"></span></span>
<span class="screen-reader-text"><?php echo $input['label']; ?></span>
</label>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</div>
</fieldset></td>
</tr>
<tr>
<th scope="row"><label for="background-size"><?php _e( 'Image Size' ); ?></label></th>
<td><fieldset><legend class="screen-reader-text"><span><?php _e( 'Image Size' ); ?></span></legend>
<select id="background-size" name="background-size">
<option value="auto"<?php selected( 'auto', get_theme_mod( 'background_size', get_theme_support( 'custom-background', 'default-size' ) ) ); ?>><?php _ex( 'Original', 'Original Size' ); ?></option>
<option value="contain"<?php selected( 'contain', get_theme_mod( 'background_size', get_theme_support( 'custom-background', 'default-size' ) ) ); ?>><?php _e( 'Fit to Screen' ); ?></option>
<option value="cover"<?php selected( 'cover', get_theme_mod( 'background_size', get_theme_support( 'custom-background', 'default-size' ) ) ); ?>><?php _e( 'Fill Screen' ); ?></option>
</select>
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _ex( 'Repeat', 'Background Repeat' ); ?></th>
<td><fieldset><legend class="screen-reader-text"><span><?php _ex( 'Repeat', 'Background Repeat' ); ?></span></legend>
<input name="background-repeat" type="hidden" value="no-repeat">
<label><input type="checkbox" name="background-repeat" value="repeat"<?php checked( 'repeat', get_theme_mod( 'background_repeat', get_theme_support( 'custom-background', 'default-repeat' ) ) ); ?>> <?php _e( 'Repeat Background Image' ); ?></label>
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _ex( 'Scroll', 'Background Scroll' ); ?></th>
<td><fieldset><legend class="screen-reader-text"><span><?php _ex( 'Scroll', 'Background Scroll' ); ?></span></legend>
<input name="background-attachment" type="hidden" value="fixed">
<label><input name="background-attachment" type="checkbox" value="scroll" <?php checked( 'scroll', get_theme_mod( 'background_attachment', get_theme_support( 'custom-background', 'default-attachment' ) ) ); ?>> <?php _e( 'Scroll with Page' ); ?></label>
</fieldset></td>
</tr>
<?php endif; // get_background_image() ?>
<tr>
<th scope="row"><?php _e( 'Background Color' ); ?></th>
<td><fieldset><legend class="screen-reader-text"><span><?php _e( 'Background Color' ); ?></span></legend>
<?php
$default_color = '';
if ( current_theme_supports( 'custom-background', 'default-color' ) ) {
$default_color = ' data-default-color="#' . esc_attr( get_theme_support( 'custom-background', 'default-color' ) ) . '"';
}
?>
<input type="text" name="background-color" id="background-color" value="#<?php echo esc_attr( get_background_color() ); ?>"<?php echo $default_color; ?>>
</fieldset></td>
</tr>
</tbody>
</table>
<?php wp_nonce_field( 'custom-background' ); ?>
<?php submit_button( null, 'primary', 'save-background-options' ); ?>
</form>
</div>
<?php
}
```
| Uses | Description |
| --- | --- |
| [submit\_button()](../../functions/submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [\_ex()](../../functions/_ex) wp-includes/l10n.php | Displays translated string with gettext context. |
| [set\_url\_scheme()](../../functions/set_url_scheme) wp-includes/link-template.php | Sets the scheme for a URL. |
| [wp\_nonce\_field()](../../functions/wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [selected()](../../functions/selected) wp-includes/general-template.php | Outputs the HTML selected attribute. |
| [checked()](../../functions/checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [esc\_attr\_e()](../../functions/esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [get\_background\_image()](../../functions/get_background_image) wp-includes/theme.php | Retrieves background image for custom background. |
| [get\_theme\_mod()](../../functions/get_theme_mod) wp-includes/theme.php | Retrieves theme modification value for the active theme. |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [get\_background\_color()](../../functions/get_background_color) wp-includes/theme.php | Retrieves value for custom background color. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
| programming_docs |
wordpress Custom_Background::admin_load() Custom\_Background::admin\_load()
=================================
Sets up the enqueue for the CSS & JavaScript files.
File: `wp-admin/includes/class-custom-background.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-background.php/)
```
public function admin_load() {
get_current_screen()->add_help_tab(
array(
'id' => 'overview',
'title' => __( 'Overview' ),
'content' =>
'<p>' . __( 'You can customize the look of your site without touching any of your theme’s code by using a custom background. Your background can be an image or a color.' ) . '</p>' .
'<p>' . __( 'To use a background image, simply upload it or choose an image that has already been uploaded to your Media Library by clicking the “Choose Image” button. You can display a single instance of your image, or tile it to fill the screen. You can have your background fixed in place, so your site content moves on top of it, or you can have it scroll with your site.' ) . '</p>' .
'<p>' . __( 'You can also choose a background color by clicking the Select Color button and either typing in a legitimate HTML hex value, e.g. “#ff0000” for red, or by choosing a color using the color picker.' ) . '</p>' .
'<p>' . __( 'Do not forget to click on the Save Changes button when you are finished.' ) . '</p>',
)
);
get_current_screen()->set_help_sidebar(
'<p><strong>' . __( 'For more information:' ) . '</strong></p>' .
'<p>' . __( '<a href="https://codex.wordpress.org/Appearance_Background_Screen">Documentation on Custom Background</a>' ) . '</p>' .
'<p>' . __( '<a href="https://wordpress.org/support/">Support</a>' ) . '</p>'
);
wp_enqueue_media();
wp_enqueue_script( 'custom-background' );
wp_enqueue_style( 'wp-color-picker' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Screen::add\_help\_tab()](../wp_screen/add_help_tab) wp-admin/includes/class-wp-screen.php | Adds a help tab to the contextual help for the screen. |
| [WP\_Screen::set\_help\_sidebar()](../wp_screen/set_help_sidebar) wp-admin/includes/class-wp-screen.php | Adds a sidebar to the contextual help for the screen. |
| [get\_current\_screen()](../../functions/get_current_screen) wp-admin/includes/screen.php | Get the current screen object |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [wp\_enqueue\_style()](../../functions/wp_enqueue_style) wp-includes/functions.wp-styles.php | Enqueue a CSS stylesheet. |
| [wp\_enqueue\_media()](../../functions/wp_enqueue_media) wp-includes/media.php | Enqueues all scripts, styles, settings, and templates necessary to use all media JS APIs. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress Custom_Background::wp_set_background_image() Custom\_Background::wp\_set\_background\_image()
================================================
This method has been deprecated.
File: `wp-admin/includes/class-custom-background.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-background.php/)
```
public function wp_set_background_image() {
check_ajax_referer( 'custom-background' );
if ( ! current_user_can( 'edit_theme_options' ) || ! isset( $_POST['attachment_id'] ) ) {
exit;
}
$attachment_id = absint( $_POST['attachment_id'] );
$sizes = array_keys(
/** This filter is documented in wp-admin/includes/media.php */
apply_filters(
'image_size_names_choose',
array(
'thumbnail' => __( 'Thumbnail' ),
'medium' => __( 'Medium' ),
'large' => __( 'Large' ),
'full' => __( 'Full Size' ),
)
)
);
$size = 'thumbnail';
if ( in_array( $_POST['size'], $sizes, true ) ) {
$size = esc_attr( $_POST['size'] );
}
update_post_meta( $attachment_id, '_wp_attachment_is_custom_background', get_option( 'stylesheet' ) );
$url = wp_get_attachment_image_src( $attachment_id, $size );
$thumbnail = wp_get_attachment_image_src( $attachment_id, 'thumbnail' );
set_theme_mod( 'background_image', sanitize_url( $url[0] ) );
set_theme_mod( 'background_image_thumb', sanitize_url( $thumbnail[0] ) );
exit;
}
```
[apply\_filters( 'image\_size\_names\_choose', string[] $size\_names )](../../hooks/image_size_names_choose)
Filters the names and labels of the default image sizes.
| Uses | Description |
| --- | --- |
| [set\_theme\_mod()](../../functions/set_theme_mod) wp-includes/theme.php | Updates theme modification value for the active theme. |
| [sanitize\_url()](../../functions/sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [wp\_get\_attachment\_image\_src()](../../functions/wp_get_attachment_image_src) wp-includes/media.php | Retrieves an image to represent an attachment. |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [check\_ajax\_referer()](../../functions/check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | This method has been deprecated. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress _WP_List_Table_Compat::get_columns(): array \_WP\_List\_Table\_Compat::get\_columns(): array
================================================
Gets a list of columns.
array
File: `wp-admin/includes/class-wp-list-table-compat.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table-compat.php/)
```
public function get_columns() {
return $this->_columns;
}
```
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress _WP_List_Table_Compat::__construct( string|WP_Screen $screen, string[] $columns = array() ) \_WP\_List\_Table\_Compat::\_\_construct( string|WP\_Screen $screen, string[] $columns = array() )
==================================================================================================
Constructor.
`$screen` string|[WP\_Screen](../wp_screen) Required The screen hook name or screen object. `$columns` string[] Optional An array of columns with column IDs as the keys and translated column names as the values. Default: `array()`
File: `wp-admin/includes/class-wp-list-table-compat.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table-compat.php/)
```
public function __construct( $screen, $columns = array() ) {
if ( is_string( $screen ) ) {
$screen = convert_to_screen( $screen );
}
$this->_screen = $screen;
if ( ! empty( $columns ) ) {
$this->_columns = $columns;
add_filter( 'manage_' . $screen->id . '_columns', array( $this, 'get_columns' ), 0 );
}
}
```
| Uses | Description |
| --- | --- |
| [convert\_to\_screen()](../../functions/convert_to_screen) wp-admin/includes/template.php | Converts a screen string to a screen object. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Used By | Description |
| --- | --- |
| [register\_column\_headers()](../../functions/register_column_headers) wp-admin/includes/list-table.php | Register column headers for a particular screen. |
| [print\_column\_headers()](../../functions/print_column_headers) wp-admin/includes/list-table.php | Prints column headers for a particular screen. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress _WP_List_Table_Compat::get_column_info(): array \_WP\_List\_Table\_Compat::get\_column\_info(): array
=====================================================
Gets a list of all, hidden, and sortable columns.
array
File: `wp-admin/includes/class-wp-list-table-compat.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table-compat.php/)
```
protected function get_column_info() {
$columns = get_column_headers( $this->_screen );
$hidden = get_hidden_columns( $this->_screen );
$sortable = array();
$primary = $this->get_default_primary_column_name();
return array( $columns, $hidden, $sortable, $primary );
}
```
| Uses | Description |
| --- | --- |
| [get\_column\_headers()](../../functions/get_column_headers) wp-admin/includes/screen.php | Get the column headers for a screen |
| [get\_hidden\_columns()](../../functions/get_hidden_columns) wp-admin/includes/screen.php | Get a list of hidden columns. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress Requests_Auth_Basic::curl_before_send( resource $handle ) Requests\_Auth\_Basic::curl\_before\_send( resource $handle )
=============================================================
Set cURL parameters before the data is sent
`$handle` resource Required cURL resource File: `wp-includes/Requests/Auth/Basic.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/auth/basic.php/)
```
public function curl_before_send(&$handle) {
curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($handle, CURLOPT_USERPWD, $this->getAuthString());
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Auth\_Basic::getAuthString()](getauthstring) wp-includes/Requests/Auth/Basic.php | Get the authentication string (user:pass) |
wordpress Requests_Auth_Basic::getAuthString(): string Requests\_Auth\_Basic::getAuthString(): string
==============================================
Get the authentication string (user:pass)
string
File: `wp-includes/Requests/Auth/Basic.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/auth/basic.php/)
```
public function getAuthString() {
return $this->user . ':' . $this->pass;
}
```
| Used By | Description |
| --- | --- |
| [Requests\_Auth\_Basic::curl\_before\_send()](curl_before_send) wp-includes/Requests/Auth/Basic.php | Set cURL parameters before the data is sent |
| [Requests\_Auth\_Basic::fsockopen\_header()](fsockopen_header) wp-includes/Requests/Auth/Basic.php | Add extra headers to the request before sending |
wordpress Requests_Auth_Basic::register( Requests_Hooks $hooks ) Requests\_Auth\_Basic::register( Requests\_Hooks $hooks )
=========================================================
Register the necessary callbacks
* [curl\_before\_send](../../functions/curl_before_send)
* [fsockopen\_header](../../functions/fsockopen_header)
`$hooks` [Requests\_Hooks](../requests_hooks) Required Hook system File: `wp-includes/Requests/Auth/Basic.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/auth/basic.php/)
```
public function register(Requests_Hooks $hooks) {
$hooks->register('curl.before_send', array($this, 'curl_before_send'));
$hooks->register('fsockopen.after_headers', array($this, 'fsockopen_header'));
}
```
wordpress Requests_Auth_Basic::fsockopen_header( string $out ) Requests\_Auth\_Basic::fsockopen\_header( string $out )
=======================================================
Add extra headers to the request before sending
`$out` string Required HTTP header string File: `wp-includes/Requests/Auth/Basic.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/auth/basic.php/)
```
public function fsockopen_header(&$out) {
$out .= sprintf("Authorization: Basic %s\r\n", base64_encode($this->getAuthString()));
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Auth\_Basic::getAuthString()](getauthstring) wp-includes/Requests/Auth/Basic.php | Get the authentication string (user:pass) |
wordpress Requests_Auth_Basic::__construct( array|null $args = null ) Requests\_Auth\_Basic::\_\_construct( array|null $args = null )
===============================================================
Constructor
`$args` array|null Optional Array of user and password. Must have exactly two elements Default: `null`
File: `wp-includes/Requests/Auth/Basic.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/auth/basic.php/)
```
public function __construct($args = null) {
if (is_array($args)) {
if (count($args) !== 2) {
throw new Requests_Exception('Invalid number of arguments', 'authbasicbadargs');
}
list($this->user, $this->pass) = $args;
}
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
| Used By | Description |
| --- | --- |
| [Requests::set\_defaults()](../requests/set_defaults) wp-includes/class-requests.php | Set the default values |
wordpress WP_Privacy_Data_Export_Requests_Table::column_email( WP_User_Request $item ): string WP\_Privacy\_Data\_Export\_Requests\_Table::column\_email( WP\_User\_Request $item ): string
============================================================================================
Actions column.
`$item` [WP\_User\_Request](../wp_user_request) Required Item being shown. string Email column markup.
File: `wp-admin/includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/user.php/)
[View on Trac](https://core.trac.wordpress.org/browser/tags/6.1/src/wp-admin/includes/user.php#L1517)
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Data_Export_Requests_Table::__construct( $args ) WP\_Privacy\_Data\_Export\_Requests\_Table::\_\_construct( $args )
==================================================================
File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/)
```
function __construct( $args ) {
_deprecated_function( __CLASS__, '5.3.0', 'WP_Privacy_Data_Export_Requests_List_Table' );
if ( ! isset( $args['screen'] ) || $args['screen'] === 'export_personal_data' ) {
$args['screen'] = 'export-personal-data';
}
parent::__construct( $args );
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
wordpress WP_Privacy_Data_Export_Requests_Table::column_next_steps( WP_User_Request $item ) WP\_Privacy\_Data\_Export\_Requests\_Table::column\_next\_steps( WP\_User\_Request $item )
==========================================================================================
Displays the next steps column.
`$item` [WP\_User\_Request](../wp_user_request) Required Item being shown. File: `wp-admin/includes/user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/user.php/)
[View on Trac](https://core.trac.wordpress.org/browser/tags/6.1/src/wp-admin/includes/user.php#L1551)
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress Requests_Response_Headers::getIterator(): ArrayIterator Requests\_Response\_Headers::getIterator(): ArrayIterator
=========================================================
Get an iterator for the data
Converts the internal
ArrayIterator
File: `wp-includes/Requests/Response/Headers.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/response/headers.php/)
```
public function getIterator() {
return new Requests_Utility_FilteredIterator($this->data, array($this, 'flatten'));
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Utility\_FilteredIterator::\_\_construct()](../requests_utility_filterediterator/__construct) wp-includes/Requests/Utility/FilteredIterator.php | Create a new iterator |
wordpress Requests_Response_Headers::offsetGet( string $key ): string|null Requests\_Response\_Headers::offsetGet( string $key ): string|null
==================================================================
Get the given header
Unlike [self::getValues()](../self/getvalues), this returns a string. If there are multiple values, it concatenates them with a comma as per RFC2616.
Avoid using this where commas may be used unquoted in values, such as Set-Cookie headers.
`$key` string Required string|null Header value
File: `wp-includes/Requests/Response/Headers.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/response/headers.php/)
```
public function offsetGet($key) {
$key = strtolower($key);
if (!isset($this->data[$key])) {
return null;
}
return $this->flatten($this->data[$key]);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Response\_Headers::flatten()](flatten) wp-includes/Requests/Response/Headers.php | Flattens a value into a string |
wordpress Requests_Response_Headers::offsetSet( string $key, string $value ) Requests\_Response\_Headers::offsetSet( string $key, string $value )
====================================================================
Set the given item
`$key` string Required Item name `$value` string Required Item value File: `wp-includes/Requests/Response/Headers.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/response/headers.php/)
```
public function offsetSet($key, $value) {
if ($key === null) {
throw new Requests_Exception('Object is a dictionary, not a list', 'invalidset');
}
$key = strtolower($key);
if (!isset($this->data[$key])) {
$this->data[$key] = array();
}
$this->data[$key][] = $value;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
wordpress Requests_Response_Headers::flatten( string|array $value ): string Requests\_Response\_Headers::flatten( string|array $value ): string
===================================================================
Flattens a value into a string
Converts an array into a string by imploding values with a comma, as per RFC2616’s rules for folding headers.
`$value` string|array Required Value to flatten string Flattened value
File: `wp-includes/Requests/Response/Headers.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/response/headers.php/)
```
public function flatten($value) {
if (is_array($value)) {
$value = implode(',', $value);
}
return $value;
}
```
| Used By | Description |
| --- | --- |
| [Requests\_Response\_Headers::offsetGet()](offsetget) wp-includes/Requests/Response/Headers.php | Get the given header |
| programming_docs |
wordpress Requests_Response_Headers::getValues( string $key ): array|null Requests\_Response\_Headers::getValues( string $key ): array|null
=================================================================
Get all values for a given header
`$key` string Required array|null Header values
File: `wp-includes/Requests/Response/Headers.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/response/headers.php/)
```
public function getValues($key) {
$key = strtolower($key);
if (!isset($this->data[$key])) {
return null;
}
return $this->data[$key];
}
```
wordpress WP_Sitemaps_Taxonomies::get_max_num_pages( string $object_subtype = '' ): int WP\_Sitemaps\_Taxonomies::get\_max\_num\_pages( string $object\_subtype = '' ): int
===================================================================================
Gets the max number of pages available for the object type.
`$object_subtype` string Optional Taxonomy name. Default: `''`
int Total number of pages.
File: `wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php/)
```
public function get_max_num_pages( $object_subtype = '' ) {
if ( empty( $object_subtype ) ) {
return 0;
}
// Restores the more descriptive, specific name for use within this method.
$taxonomy = $object_subtype;
/**
* Filters the max number of pages for a taxonomy sitemap before it is generated.
*
* Passing a non-null value will short-circuit the generation,
* returning that value instead.
*
* @since 5.5.0
*
* @param int|null $max_num_pages The maximum number of pages. Default null.
* @param string $taxonomy Taxonomy name.
*/
$max_num_pages = apply_filters( 'wp_sitemaps_taxonomies_pre_max_num_pages', null, $taxonomy );
if ( null !== $max_num_pages ) {
return $max_num_pages;
}
$term_count = wp_count_terms( $this->get_taxonomies_query_args( $taxonomy ) );
return (int) ceil( $term_count / wp_sitemaps_get_max_urls( $this->object_type ) );
}
```
[apply\_filters( 'wp\_sitemaps\_taxonomies\_pre\_max\_num\_pages', int|null $max\_num\_pages, string $taxonomy )](../../hooks/wp_sitemaps_taxonomies_pre_max_num_pages)
Filters the max number of pages for a taxonomy sitemap before it is generated.
| Uses | Description |
| --- | --- |
| [wp\_sitemaps\_get\_max\_urls()](../../functions/wp_sitemaps_get_max_urls) wp-includes/sitemaps.php | Gets the maximum number of URLs for a sitemap. |
| [WP\_Sitemaps\_Taxonomies::get\_taxonomies\_query\_args()](get_taxonomies_query_args) wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php | Returns the query args for retrieving taxonomy terms to list in the sitemap. |
| [wp\_count\_terms()](../../functions/wp_count_terms) wp-includes/taxonomy.php | Counts how many terms are in taxonomy. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$taxonomy` to `$object_subtype` to match parent class for PHP 8 named parameter support. |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps_Taxonomies::get_taxonomies_query_args( string $taxonomy ): array WP\_Sitemaps\_Taxonomies::get\_taxonomies\_query\_args( string $taxonomy ): array
=================================================================================
Returns the query args for retrieving taxonomy terms to list in the sitemap.
`$taxonomy` string Required Taxonomy name. array Array of [WP\_Term\_Query](../wp_term_query) arguments.
File: `wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php/)
```
protected function get_taxonomies_query_args( $taxonomy ) {
/**
* Filters the taxonomy terms query arguments.
*
* Allows modification of the taxonomy query arguments before querying.
*
* @see WP_Term_Query for a full list of arguments
*
* @since 5.5.0
*
* @param array $args Array of WP_Term_Query arguments.
* @param string $taxonomy Taxonomy name.
*/
$args = apply_filters(
'wp_sitemaps_taxonomies_query_args',
array(
'taxonomy' => $taxonomy,
'orderby' => 'term_order',
'number' => wp_sitemaps_get_max_urls( $this->object_type ),
'hide_empty' => true,
'hierarchical' => false,
'update_term_meta_cache' => false,
),
$taxonomy
);
return $args;
}
```
[apply\_filters( 'wp\_sitemaps\_taxonomies\_query\_args', array $args, string $taxonomy )](../../hooks/wp_sitemaps_taxonomies_query_args)
Filters the taxonomy terms query arguments.
| Uses | Description |
| --- | --- |
| [wp\_sitemaps\_get\_max\_urls()](../../functions/wp_sitemaps_get_max_urls) wp-includes/sitemaps.php | Gets the maximum number of URLs for a sitemap. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Sitemaps\_Taxonomies::get\_url\_list()](get_url_list) wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php | Gets a URL list for a taxonomy sitemap. |
| [WP\_Sitemaps\_Taxonomies::get\_max\_num\_pages()](get_max_num_pages) wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php | Gets the max number of pages available for the object type. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps_Taxonomies::__construct() WP\_Sitemaps\_Taxonomies::\_\_construct()
=========================================
[WP\_Sitemaps\_Taxonomies](../wp_sitemaps_taxonomies) constructor.
File: `wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php/)
```
public function __construct() {
$this->name = 'taxonomies';
$this->object_type = 'term';
}
```
| Used By | Description |
| --- | --- |
| [WP\_Sitemaps::register\_sitemaps()](../wp_sitemaps/register_sitemaps) wp-includes/sitemaps/class-wp-sitemaps.php | Registers and sets up the functionality for all supported sitemaps. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps_Taxonomies::get_url_list( int $page_num, string $object_subtype = '' ): array[] WP\_Sitemaps\_Taxonomies::get\_url\_list( int $page\_num, string $object\_subtype = '' ): array[]
=================================================================================================
Gets a URL list for a taxonomy sitemap.
`$page_num` int Required Page of results. `$object_subtype` string Optional Taxonomy name. Default: `''`
array[] Array of URL information for a sitemap.
File: `wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php/)
```
public function get_url_list( $page_num, $object_subtype = '' ) {
// Restores the more descriptive, specific name for use within this method.
$taxonomy = $object_subtype;
$supported_types = $this->get_object_subtypes();
// Bail early if the queried taxonomy is not supported.
if ( ! isset( $supported_types[ $taxonomy ] ) ) {
return array();
}
/**
* Filters the taxonomies URL list before it is generated.
*
* Returning a non-null value will effectively short-circuit the generation,
* returning that value instead.
*
* @since 5.5.0
*
* @param array[]|null $url_list The URL list. Default null.
* @param string $taxonomy Taxonomy name.
* @param int $page_num Page of results.
*/
$url_list = apply_filters(
'wp_sitemaps_taxonomies_pre_url_list',
null,
$taxonomy,
$page_num
);
if ( null !== $url_list ) {
return $url_list;
}
$url_list = array();
// Offset by how many terms should be included in previous pages.
$offset = ( $page_num - 1 ) * wp_sitemaps_get_max_urls( $this->object_type );
$args = $this->get_taxonomies_query_args( $taxonomy );
$args['fields'] = 'all';
$args['offset'] = $offset;
$taxonomy_terms = new WP_Term_Query( $args );
if ( ! empty( $taxonomy_terms->terms ) ) {
foreach ( $taxonomy_terms->terms as $term ) {
$term_link = get_term_link( $term, $taxonomy );
if ( is_wp_error( $term_link ) ) {
continue;
}
$sitemap_entry = array(
'loc' => $term_link,
);
/**
* Filters the sitemap entry for an individual term.
*
* @since 5.5.0
* @since 6.0.0 Added `$term` argument containing the term object.
*
* @param array $sitemap_entry Sitemap entry for the term.
* @param int $term_id Term ID.
* @param string $taxonomy Taxonomy name.
* @param WP_Term $term Term object.
*/
$sitemap_entry = apply_filters( 'wp_sitemaps_taxonomies_entry', $sitemap_entry, $term->term_id, $taxonomy, $term );
$url_list[] = $sitemap_entry;
}
}
return $url_list;
}
```
[apply\_filters( 'wp\_sitemaps\_taxonomies\_entry', array $sitemap\_entry, int $term\_id, string $taxonomy, WP\_Term $term )](../../hooks/wp_sitemaps_taxonomies_entry)
Filters the sitemap entry for an individual term.
[apply\_filters( 'wp\_sitemaps\_taxonomies\_pre\_url\_list', array[]|null $url\_list, string $taxonomy, int $page\_num )](../../hooks/wp_sitemaps_taxonomies_pre_url_list)
Filters the taxonomies URL list before it is generated.
| Uses | Description |
| --- | --- |
| [wp\_sitemaps\_get\_max\_urls()](../../functions/wp_sitemaps_get_max_urls) wp-includes/sitemaps.php | Gets the maximum number of URLs for a sitemap. |
| [WP\_Sitemaps\_Taxonomies::get\_object\_subtypes()](get_object_subtypes) wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php | Returns all public, registered taxonomies. |
| [WP\_Sitemaps\_Taxonomies::get\_taxonomies\_query\_args()](get_taxonomies_query_args) wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php | Returns the query args for retrieving taxonomy terms to list in the sitemap. |
| [WP\_Term\_Query::\_\_construct()](../wp_term_query/__construct) wp-includes/class-wp-term-query.php | Constructor. |
| [get\_term\_link()](../../functions/get_term_link) wp-includes/taxonomy.php | Generates a permalink for a taxonomy term archive. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$taxonomy` to `$object_subtype` to match parent class for PHP 8 named parameter support. |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps_Taxonomies::get_object_subtypes(): WP_Taxonomy[] WP\_Sitemaps\_Taxonomies::get\_object\_subtypes(): WP\_Taxonomy[]
=================================================================
Returns all public, registered taxonomies.
[WP\_Taxonomy](../wp_taxonomy)[] Array of registered taxonomy objects keyed by their name.
File: `wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php/)
```
public function get_object_subtypes() {
$taxonomies = get_taxonomies( array( 'public' => true ), 'objects' );
$taxonomies = array_filter( $taxonomies, 'is_taxonomy_viewable' );
/**
* Filters the list of taxonomy object subtypes available within the sitemap.
*
* @since 5.5.0
*
* @param WP_Taxonomy[] $taxonomies Array of registered taxonomy objects keyed by their name.
*/
return apply_filters( 'wp_sitemaps_taxonomies', $taxonomies );
}
```
[apply\_filters( 'wp\_sitemaps\_taxonomies', WP\_Taxonomy[] $taxonomies )](../../hooks/wp_sitemaps_taxonomies)
Filters the list of taxonomy object subtypes available within the sitemap.
| Uses | Description |
| --- | --- |
| [get\_taxonomies()](../../functions/get_taxonomies) wp-includes/taxonomy.php | Retrieves a list of registered taxonomy names or objects. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Sitemaps\_Taxonomies::get\_url\_list()](get_url_list) wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php | Gets a URL list for a taxonomy sitemap. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Comment_Meta_Fields::get_meta_subtype(): string WP\_REST\_Comment\_Meta\_Fields::get\_meta\_subtype(): string
=============================================================
Retrieves the comment meta subtype.
string `'comment'` There are no subtypes.
File: `wp-includes/rest-api/fields/class-wp-rest-comment-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-comment-meta-fields.php/)
```
protected function get_meta_subtype() {
return 'comment';
}
```
| Version | Description |
| --- | --- |
| [4.9.8](https://developer.wordpress.org/reference/since/4.9.8/) | Introduced. |
wordpress WP_REST_Comment_Meta_Fields::get_rest_field_type(): string WP\_REST\_Comment\_Meta\_Fields::get\_rest\_field\_type(): string
=================================================================
Retrieves the type for [register\_rest\_field()](../../functions/register_rest_field) in the context of comments.
string The REST field type.
File: `wp-includes/rest-api/fields/class-wp-rest-comment-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-comment-meta-fields.php/)
```
public function get_rest_field_type() {
return 'comment';
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Comment_Meta_Fields::get_meta_type(): string WP\_REST\_Comment\_Meta\_Fields::get\_meta\_type(): string
==========================================================
Retrieves the comment type for comment meta.
string The meta type.
File: `wp-includes/rest-api/fields/class-wp-rest-comment-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-comment-meta-fields.php/)
```
protected function get_meta_type() {
return 'comment';
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress IXR_Date::getTimestamp() IXR\_Date::getTimestamp()
=========================
File: `wp-includes/IXR/class-IXR-date.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-date.php/)
```
function getTimestamp()
{
return mktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year);
}
```
wordpress IXR_Date::IXR_Date( $time ) IXR\_Date::IXR\_Date( $time )
=============================
PHP4 constructor.
File: `wp-includes/IXR/class-IXR-date.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-date.php/)
```
public function IXR_Date( $time ) {
self::__construct( $time );
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Date::\_\_construct()](__construct) wp-includes/IXR/class-IXR-date.php | PHP5 constructor. |
wordpress IXR_Date::parseIso( $iso ) IXR\_Date::parseIso( $iso )
===========================
File: `wp-includes/IXR/class-IXR-date.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-date.php/)
```
function parseIso($iso)
{
$this->year = substr($iso, 0, 4);
$this->month = substr($iso, 4, 2);
$this->day = substr($iso, 6, 2);
$this->hour = substr($iso, 9, 2);
$this->minute = substr($iso, 12, 2);
$this->second = substr($iso, 15, 2);
$this->timezone = substr($iso, 17);
}
```
| Used By | Description |
| --- | --- |
| [IXR\_Date::\_\_construct()](__construct) wp-includes/IXR/class-IXR-date.php | PHP5 constructor. |
wordpress IXR_Date::parseTimestamp( $timestamp ) IXR\_Date::parseTimestamp( $timestamp )
=======================================
File: `wp-includes/IXR/class-IXR-date.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-date.php/)
```
function parseTimestamp($timestamp)
{
$this->year = gmdate('Y', $timestamp);
$this->month = gmdate('m', $timestamp);
$this->day = gmdate('d', $timestamp);
$this->hour = gmdate('H', $timestamp);
$this->minute = gmdate('i', $timestamp);
$this->second = gmdate('s', $timestamp);
$this->timezone = '';
}
```
| Used By | Description |
| --- | --- |
| [IXR\_Date::\_\_construct()](__construct) wp-includes/IXR/class-IXR-date.php | PHP5 constructor. |
wordpress IXR_Date::getXml() IXR\_Date::getXml()
===================
File: `wp-includes/IXR/class-IXR-date.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-date.php/)
```
function getXml()
{
return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>';
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Date::getIso()](getiso) wp-includes/IXR/class-IXR-date.php | |
wordpress IXR_Date::__construct( $time ) IXR\_Date::\_\_construct( $time )
=================================
PHP5 constructor.
File: `wp-includes/IXR/class-IXR-date.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-date.php/)
```
function __construct( $time )
{
// $time can be a PHP timestamp or an ISO one
if (is_numeric($time)) {
$this->parseTimestamp($time);
} else {
$this->parseIso($time);
}
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Date::parseIso()](parseiso) wp-includes/IXR/class-IXR-date.php | |
| [IXR\_Date::parseTimestamp()](parsetimestamp) wp-includes/IXR/class-IXR-date.php | |
| Used By | Description |
| --- | --- |
| [IXR\_IntrospectionServer::methodSignature()](../ixr_introspectionserver/methodsignature) wp-includes/IXR/class-IXR-introspectionserver.php | |
| [IXR\_Message::tag\_close()](../ixr_message/tag_close) wp-includes/IXR/class-IXR-message.php | |
| [IXR\_Date::IXR\_Date()](ixr_date) wp-includes/IXR/class-IXR-date.php | PHP4 constructor. |
| [wp\_xmlrpc\_server::\_convert\_date()](../wp_xmlrpc_server/_convert_date) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress date string to an [IXR\_Date](../ixr_date) object. |
| [wp\_xmlrpc\_server::\_convert\_date\_gmt()](../wp_xmlrpc_server/_convert_date_gmt) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress GMT date string to an [IXR\_Date](../ixr_date) object. |
wordpress IXR_Date::getIso() IXR\_Date::getIso()
===================
File: `wp-includes/IXR/class-IXR-date.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-date.php/)
```
function getIso()
{
return $this->year.$this->month.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second.$this->timezone;
}
```
| Used By | Description |
| --- | --- |
| [IXR\_Date::getXml()](getxml) wp-includes/IXR/class-IXR-date.php | |
| programming_docs |
wordpress Gettext_Translations::nplurals_and_expression_from_header( string $header ): array Gettext\_Translations::nplurals\_and\_expression\_from\_header( string $header ): array
=======================================================================================
`$header` string Required array
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function nplurals_and_expression_from_header( $header ) {
if ( preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s+plural\s*=\s*(.+)$/', $header, $matches ) ) {
$nplurals = (int) $matches[1];
$expression = trim( $matches[2] );
return array( $nplurals, $expression );
} else {
return array( 2, 'n != 1' );
}
}
```
| Used By | Description |
| --- | --- |
| [Gettext\_Translations::gettext\_select\_plural\_form()](gettext_select_plural_form) wp-includes/pomo/translations.php | The gettext implementation of select\_plural\_form. |
| [Gettext\_Translations::set\_header()](set_header) wp-includes/pomo/translations.php | |
wordpress Gettext_Translations::gettext_select_plural_form( int $count ) Gettext\_Translations::gettext\_select\_plural\_form( int $count )
==================================================================
The gettext implementation of select\_plural\_form.
It lives in this class, because there are more than one descendand, which will use it and they can’t share it effectively.
`$count` int Required File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function gettext_select_plural_form( $count ) {
if ( ! isset( $this->_gettext_select_plural_form ) || is_null( $this->_gettext_select_plural_form ) ) {
list( $nplurals, $expression ) = $this->nplurals_and_expression_from_header( $this->get_header( 'Plural-Forms' ) );
$this->_nplurals = $nplurals;
$this->_gettext_select_plural_form = $this->make_plural_form_function( $nplurals, $expression );
}
return call_user_func( $this->_gettext_select_plural_form, $count );
}
```
| Uses | Description |
| --- | --- |
| [Gettext\_Translations::nplurals\_and\_expression\_from\_header()](nplurals_and_expression_from_header) wp-includes/pomo/translations.php | |
| [Gettext\_Translations::make\_plural\_form\_function()](make_plural_form_function) wp-includes/pomo/translations.php | Makes a function, which will return the right translation index, according to the plural forms header |
wordpress Gettext_Translations::make_plural_form_function( int $nplurals, string $expression ) Gettext\_Translations::make\_plural\_form\_function( int $nplurals, string $expression )
========================================================================================
Makes a function, which will return the right translation index, according to the plural forms header
`$nplurals` int Required `$expression` string Required File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function make_plural_form_function( $nplurals, $expression ) {
try {
$handler = new Plural_Forms( rtrim( $expression, ';' ) );
return array( $handler, 'get' );
} catch ( Exception $e ) {
// Fall back to default plural-form function.
return $this->make_plural_form_function( 2, 'n != 1' );
}
}
```
| Uses | Description |
| --- | --- |
| [Plural\_Forms::\_\_construct()](../plural_forms/__construct) wp-includes/pomo/plural-forms.php | Constructor. |
| [Gettext\_Translations::make\_plural\_form\_function()](make_plural_form_function) wp-includes/pomo/translations.php | Makes a function, which will return the right translation index, according to the plural forms header |
| Used By | Description |
| --- | --- |
| [Gettext\_Translations::gettext\_select\_plural\_form()](gettext_select_plural_form) wp-includes/pomo/translations.php | The gettext implementation of select\_plural\_form. |
| [Gettext\_Translations::make\_plural\_form\_function()](make_plural_form_function) wp-includes/pomo/translations.php | Makes a function, which will return the right translation index, according to the plural forms header |
| [Gettext\_Translations::set\_header()](set_header) wp-includes/pomo/translations.php | |
wordpress Gettext_Translations::set_header( string $header, string $value ) Gettext\_Translations::set\_header( string $header, string $value )
===================================================================
`$header` string Required `$value` string Required File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function set_header( $header, $value ) {
parent::set_header( $header, $value );
if ( 'Plural-Forms' === $header ) {
list( $nplurals, $expression ) = $this->nplurals_and_expression_from_header( $this->get_header( 'Plural-Forms' ) );
$this->_nplurals = $nplurals;
$this->_gettext_select_plural_form = $this->make_plural_form_function( $nplurals, $expression );
}
}
```
| Uses | Description |
| --- | --- |
| [Gettext\_Translations::nplurals\_and\_expression\_from\_header()](nplurals_and_expression_from_header) wp-includes/pomo/translations.php | |
| [Gettext\_Translations::make\_plural\_form\_function()](make_plural_form_function) wp-includes/pomo/translations.php | Makes a function, which will return the right translation index, according to the plural forms header |
| [Translations::set\_header()](../translations/set_header) wp-includes/pomo/translations.php | Sets $header PO header to $value |
wordpress Gettext_Translations::parenthesize_plural_exression( string $expression ): string Gettext\_Translations::parenthesize\_plural\_exression( string $expression ): string
====================================================================================
Adds parentheses to the inner parts of ternary operators in plural expressions, because PHP evaluates ternary oerators from left to right
`$expression` string Required the expression without parentheses string the expression with parentheses added
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function parenthesize_plural_exression( $expression ) {
$expression .= ';';
$res = '';
$depth = 0;
for ( $i = 0; $i < strlen( $expression ); ++$i ) {
$char = $expression[ $i ];
switch ( $char ) {
case '?':
$res .= ' ? (';
$depth++;
break;
case ':':
$res .= ') : (';
break;
case ';':
$res .= str_repeat( ')', $depth ) . ';';
$depth = 0;
break;
default:
$res .= $char;
}
}
return rtrim( $res, ';' );
}
```
wordpress Gettext_Translations::make_headers( string $translation ): array Gettext\_Translations::make\_headers( string $translation ): array
==================================================================
`$translation` string Required array
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function make_headers( $translation ) {
$headers = array();
// Sometimes \n's are used instead of real new lines.
$translation = str_replace( '\n', "\n", $translation );
$lines = explode( "\n", $translation );
foreach ( $lines as $line ) {
$parts = explode( ':', $line, 2 );
if ( ! isset( $parts[1] ) ) {
continue;
}
$headers[ trim( $parts[0] ) ] = trim( $parts[1] );
}
return $headers;
}
```
wordpress WP_Filesystem_Base::search_for_folder( string $folder, string $base = '.', bool $loop = false ): string|false WP\_Filesystem\_Base::search\_for\_folder( string $folder, string $base = '.', bool $loop = false ): string|false
=================================================================================================================
Locates a folder on the remote filesystem.
Expects Windows sanitized path.
`$folder` string Required The folder to locate. `$base` string Optional The folder to start searching from. Default: `'.'`
`$loop` bool Optional If the function has recursed. Internal use only. Default: `false`
string|false The location of the remote path, false to cease looping.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function search_for_folder( $folder, $base = '.', $loop = false ) {
if ( empty( $base ) || '.' === $base ) {
$base = trailingslashit( $this->cwd() );
}
$folder = untrailingslashit( $folder );
if ( $this->verbose ) {
/* translators: 1: Folder to locate, 2: Folder to start searching from. */
printf( "\n" . __( 'Looking for %1$s in %2$s' ) . "<br />\n", $folder, $base );
}
$folder_parts = explode( '/', $folder );
$folder_part_keys = array_keys( $folder_parts );
$last_index = array_pop( $folder_part_keys );
$last_path = $folder_parts[ $last_index ];
$files = $this->dirlist( $base );
foreach ( $folder_parts as $index => $key ) {
if ( $index === $last_index ) {
continue; // We want this to be caught by the next code block.
}
/*
* Working from /home/ to /user/ to /wordpress/ see if that file exists within
* the current folder, If it's found, change into it and follow through looking
* for it. If it can't find WordPress down that route, it'll continue onto the next
* folder level, and see if that matches, and so on. If it reaches the end, and still
* can't find it, it'll return false for the entire function.
*/
if ( isset( $files[ $key ] ) ) {
// Let's try that folder:
$newdir = trailingslashit( path_join( $base, $key ) );
if ( $this->verbose ) {
/* translators: %s: Directory name. */
printf( "\n" . __( 'Changing to %s' ) . "<br />\n", $newdir );
}
// Only search for the remaining path tokens in the directory, not the full path again.
$newfolder = implode( '/', array_slice( $folder_parts, $index + 1 ) );
$ret = $this->search_for_folder( $newfolder, $newdir, $loop );
if ( $ret ) {
return $ret;
}
}
}
// Only check this as a last resort, to prevent locating the incorrect install.
// All above procedures will fail quickly if this is the right branch to take.
if ( isset( $files[ $last_path ] ) ) {
if ( $this->verbose ) {
/* translators: %s: Directory name. */
printf( "\n" . __( 'Found %s' ) . "<br />\n", $base . $last_path );
}
return trailingslashit( $base . $last_path );
}
// Prevent this function from looping again.
// No need to proceed if we've just searched in `/`.
if ( $loop || '/' === $base ) {
return false;
}
// As an extra last resort, Change back to / if the folder wasn't found.
// This comes into effect when the CWD is /home/user/ but WP is at /var/www/....
return $this->search_for_folder( $folder, '/', true );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Base::dirlist()](dirlist) wp-admin/includes/class-wp-filesystem-base.php | Gets details for files in a directory or a specific file. |
| [WP\_Filesystem\_Base::cwd()](cwd) wp-admin/includes/class-wp-filesystem-base.php | Gets the current working directory. |
| [WP\_Filesystem\_Base::search\_for\_folder()](search_for_folder) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| [untrailingslashit()](../../functions/untrailingslashit) wp-includes/formatting.php | Removes trailing forward slashes and backslashes if they exist. |
| [path\_join()](../../functions/path_join) wp-includes/functions.php | Joins two filesystem paths together. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Base::find\_folder()](find_folder) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| [WP\_Filesystem\_Base::search\_for\_folder()](search_for_folder) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_Filesystem_Base::chmod( string $file, int|false $mode = false, bool $recursive = false ): bool WP\_Filesystem\_Base::chmod( string $file, int|false $mode = false, bool $recursive = false ): bool
===================================================================================================
Changes filesystem permissions.
`$file` string Required Path to the file. `$mode` int|false Optional The permissions as octal number, usually 0644 for files, 0755 for directories. Default: `false`
`$recursive` bool Optional If set to true, changes file permissions recursively.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function chmod( $file, $mode = false, $recursive = false ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::size( string $file ): int|false WP\_Filesystem\_Base::size( string $file ): int|false
=====================================================
Gets the file size (in bytes).
`$file` string Required Path to file. int|false Size of the file in bytes on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function size( $file ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::getchmod( string $file ): string WP\_Filesystem\_Base::getchmod( string $file ): string
======================================================
Gets the permissions of the specified file or filepath in their octal format.
`$file` string Required Path to the file. string Mode of the file (the last 3 digits).
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function getchmod( $file ) {
return '777';
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Base::gethchmod()](gethchmod) wp-admin/includes/class-wp-filesystem-base.php | Returns the \*nix-style file permissions for a file. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::exists( string $path ): bool WP\_Filesystem\_Base::exists( string $path ): bool
==================================================
Checks if a file or directory exists.
`$path` string Required Path to file or directory. bool Whether $path exists or not.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function exists( $path ) {
return false;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Base::find\_folder()](find_folder) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::chdir( string $dir ): bool WP\_Filesystem\_Base::chdir( string $dir ): bool
================================================
Changes current directory.
`$dir` string Required The new current directory. bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function chdir( $dir ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::rmdir( string $path, bool $recursive = false ): bool WP\_Filesystem\_Base::rmdir( string $path, bool $recursive = false ): bool
==========================================================================
Deletes a directory.
`$path` string Required Path to directory. `$recursive` bool Optional Whether to recursively remove files/directories.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function rmdir( $path, $recursive = false ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::wp_plugins_dir(): string WP\_Filesystem\_Base::wp\_plugins\_dir(): string
================================================
Returns the path on the remote filesystem of WP\_PLUGIN\_DIR.
string The location of the remote path.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function wp_plugins_dir() {
return $this->find_folder( WP_PLUGIN_DIR );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Base::find\_folder()](../wp_filesystem_base/find_folder) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_Filesystem_Base::get_contents( string $file ): string|false WP\_Filesystem\_Base::get\_contents( string $file ): string|false
=================================================================
Reads entire file into a string.
`$file` string Required Name of the file to read. string|false Read data on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function get_contents( $file ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::wp_themes_dir( string|false $theme = false ): string WP\_Filesystem\_Base::wp\_themes\_dir( string|false $theme = false ): string
============================================================================
Returns the path on the remote filesystem of the Themes Directory.
`$theme` string|false Optional The theme stylesheet or template for the directory.
Default: `false`
string The location of the remote path.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function wp_themes_dir( $theme = false ) {
$theme_root = get_theme_root( $theme );
// Account for relative theme roots.
if ( '/themes' === $theme_root || ! is_dir( $theme_root ) ) {
$theme_root = WP_CONTENT_DIR . $theme_root;
}
return $this->find_folder( $theme_root );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Base::find\_folder()](find_folder) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| [get\_theme\_root()](../../functions/get_theme_root) wp-includes/theme.php | Retrieves path to themes directory. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Filesystem_Base::chown( string $file, string|int $owner, bool $recursive = false ): bool WP\_Filesystem\_Base::chown( string $file, string|int $owner, bool $recursive = false ): bool
=============================================================================================
Changes the owner of a file or directory.
Default behavior is to do nothing, override this in your subclass, if desired.
`$file` string Required Path to the file or directory. `$owner` string|int Required A user name or number. `$recursive` bool Optional If set to true, changes file owner recursively.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function chown( $file, $owner, $recursive = false ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::is_writable( string $path ): bool WP\_Filesystem\_Base::is\_writable( string $path ): bool
========================================================
Checks if a file or directory is writable.
`$path` string Required Path to file or directory. bool Whether $path is writable.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function is_writable( $path ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::group( string $file ): string|false WP\_Filesystem\_Base::group( string $file ): string|false
=========================================================
Gets the file’s group.
`$file` string Required Path to the file. string|false The group on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function group( $file ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::chgrp( string $file, string|int $group, bool $recursive = false ): bool WP\_Filesystem\_Base::chgrp( string $file, string|int $group, bool $recursive = false ): bool
=============================================================================================
Changes the file group.
`$file` string Required Path to the file. `$group` string|int Required A group name or number. `$recursive` bool Optional If set to true, changes file group recursively.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function chgrp( $file, $group, $recursive = false ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::put_contents( string $file, string $contents, int|false $mode = false ): bool WP\_Filesystem\_Base::put\_contents( string $file, string $contents, int|false $mode = false ): bool
====================================================================================================
Writes a string to a file.
`$file` string Required Remote path to the file where to write the data. `$contents` string Required The data to write. `$mode` int|false Optional The file permissions as octal number, usually 0644.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function put_contents( $file, $contents, $mode = false ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::wp_lang_dir(): string WP\_Filesystem\_Base::wp\_lang\_dir(): string
=============================================
Returns the path on the remote filesystem of WP\_LANG\_DIR.
string The location of the remote path.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function wp_lang_dir() {
return $this->find_folder( WP_LANG_DIR );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Base::find\_folder()](../wp_filesystem_base/find_folder) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| Version | Description |
| --- | --- |
| [3.2.0](https://developer.wordpress.org/reference/since/3.2.0/) | Introduced. |
wordpress WP_Filesystem_Base::is_dir( string $path ): bool WP\_Filesystem\_Base::is\_dir( string $path ): bool
===================================================
Checks if resource is a directory.
`$path` string Required Directory path. bool Whether $path is a directory.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function is_dir( $path ) {
return false;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Base::abspath()](abspath) wp-admin/includes/class-wp-filesystem-base.php | Returns the path on the remote filesystem of ABSPATH. |
| [WP\_Filesystem\_Base::find\_folder()](find_folder) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::abspath(): string WP\_Filesystem\_Base::abspath(): string
=======================================
Returns the path on the remote filesystem of ABSPATH.
string The location of the remote path.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function abspath() {
$folder = $this->find_folder( ABSPATH );
// Perhaps the FTP folder is rooted at the WordPress install.
// Check for wp-includes folder in root. Could have some false positives, but rare.
if ( ! $folder && $this->is_dir( '/' . WPINC ) ) {
$folder = '/';
}
return $folder;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Base::is\_dir()](../wp_filesystem_base/is_dir) wp-admin/includes/class-wp-filesystem-base.php | Checks if resource is a directory. |
| [WP\_Filesystem\_Base::find\_folder()](../wp_filesystem_base/find_folder) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Base::find\_base\_dir()](../wp_filesystem_base/find_base_dir) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| [WP\_Filesystem\_Base::get\_base\_dir()](../wp_filesystem_base/get_base_dir) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_Filesystem_Base::get_base_dir( string $base = '.', bool $verbose = false ): string WP\_Filesystem\_Base::get\_base\_dir( string $base = '.', bool $verbose = false ): string
=========================================================================================
This method has been deprecated. Use [WP\_Filesystem\_Base::abspath()](../wp_filesystem_base/abspath) instead.
Locates a folder on the remote filesystem.
* [WP\_Filesystem\_Base::abspath()](../wp_filesystem_base/abspath)
* [WP\_Filesystem\_Base::wp\_content\_dir()](../wp_filesystem_base/wp_content_dir)
* [WP\_Filesystem\_Base::wp\_plugins\_dir()](../wp_filesystem_base/wp_plugins_dir)
* [WP\_Filesystem\_Base::wp\_themes\_dir()](../wp_filesystem_base/wp_themes_dir)
* [WP\_Filesystem\_Base::wp\_lang\_dir()](../wp_filesystem_base/wp_lang_dir)
`$base` string Optional The folder to start searching from. Default `'.'`. Default: `'.'`
`$verbose` bool Optional True to display debug information. Default: `false`
string The location of the remote path.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function get_base_dir( $base = '.', $verbose = false ) {
_deprecated_function( __FUNCTION__, '2.7.0', 'WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir()' );
$this->verbose = $verbose;
return $this->abspath();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Base::abspath()](abspath) wp-admin/includes/class-wp-filesystem-base.php | Returns the path on the remote filesystem of ABSPATH. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | use [WP\_Filesystem\_Base::abspath()](abspath) or WP\_Filesystem\*Base::wp\*\*\_dir() methods instead. |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::find_folder( string $folder ): string|false WP\_Filesystem\_Base::find\_folder( string $folder ): string|false
==================================================================
Locates a folder on the remote filesystem.
Assumes that on Windows systems, Stripping off the Drive letter is OK Sanitizes \ to / in Windows filepaths.
`$folder` string Required the folder to locate. string|false The location of the remote path, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function find_folder( $folder ) {
if ( isset( $this->cache[ $folder ] ) ) {
return $this->cache[ $folder ];
}
if ( stripos( $this->method, 'ftp' ) !== false ) {
$constant_overrides = array(
'FTP_BASE' => ABSPATH,
'FTP_CONTENT_DIR' => WP_CONTENT_DIR,
'FTP_PLUGIN_DIR' => WP_PLUGIN_DIR,
'FTP_LANG_DIR' => WP_LANG_DIR,
);
// Direct matches ( folder = CONSTANT/ ).
foreach ( $constant_overrides as $constant => $dir ) {
if ( ! defined( $constant ) ) {
continue;
}
if ( $folder === $dir ) {
return trailingslashit( constant( $constant ) );
}
}
// Prefix matches ( folder = CONSTANT/subdir ),
foreach ( $constant_overrides as $constant => $dir ) {
if ( ! defined( $constant ) ) {
continue;
}
if ( 0 === stripos( $folder, $dir ) ) { // $folder starts with $dir.
$potential_folder = preg_replace( '#^' . preg_quote( $dir, '#' ) . '/#i', trailingslashit( constant( $constant ) ), $folder );
$potential_folder = trailingslashit( $potential_folder );
if ( $this->is_dir( $potential_folder ) ) {
$this->cache[ $folder ] = $potential_folder;
return $potential_folder;
}
}
}
} elseif ( 'direct' === $this->method ) {
$folder = str_replace( '\\', '/', $folder ); // Windows path sanitisation.
return trailingslashit( $folder );
}
$folder = preg_replace( '|^([a-z]{1}):|i', '', $folder ); // Strip out Windows drive letter if it's there.
$folder = str_replace( '\\', '/', $folder ); // Windows path sanitisation.
if ( isset( $this->cache[ $folder ] ) ) {
return $this->cache[ $folder ];
}
if ( $this->exists( $folder ) ) { // Folder exists at that absolute path.
$folder = trailingslashit( $folder );
$this->cache[ $folder ] = $folder;
return $folder;
}
$return = $this->search_for_folder( $folder );
if ( $return ) {
$this->cache[ $folder ] = $return;
}
return $return;
}
```
| Uses | Description |
| --- | --- |
| [stripos()](../../functions/stripos) wp-includes/class-pop3.php | |
| [WP\_Filesystem\_Base::is\_dir()](is_dir) wp-admin/includes/class-wp-filesystem-base.php | Checks if resource is a directory. |
| [WP\_Filesystem\_Base::exists()](exists) wp-admin/includes/class-wp-filesystem-base.php | Checks if a file or directory exists. |
| [WP\_Filesystem\_Base::search\_for\_folder()](search_for_folder) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Base::abspath()](abspath) wp-admin/includes/class-wp-filesystem-base.php | Returns the path on the remote filesystem of ABSPATH. |
| [WP\_Filesystem\_Base::wp\_content\_dir()](wp_content_dir) wp-admin/includes/class-wp-filesystem-base.php | Returns the path on the remote filesystem of WP\_CONTENT\_DIR. |
| [WP\_Filesystem\_Base::wp\_plugins\_dir()](wp_plugins_dir) wp-admin/includes/class-wp-filesystem-base.php | Returns the path on the remote filesystem of WP\_PLUGIN\_DIR. |
| [WP\_Filesystem\_Base::wp\_themes\_dir()](wp_themes_dir) wp-admin/includes/class-wp-filesystem-base.php | Returns the path on the remote filesystem of the Themes Directory. |
| [WP\_Filesystem\_Base::wp\_lang\_dir()](wp_lang_dir) wp-admin/includes/class-wp-filesystem-base.php | Returns the path on the remote filesystem of WP\_LANG\_DIR. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_Filesystem_Base::is_readable( string $file ): bool WP\_Filesystem\_Base::is\_readable( string $file ): bool
========================================================
Checks if a file is readable.
`$file` string Required Path to file. bool Whether $file is readable.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function is_readable( $file ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::is_file( string $file ): bool WP\_Filesystem\_Base::is\_file( string $file ): bool
====================================================
Checks if resource is a file.
`$file` string Required File path. bool Whether $file is a file.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function is_file( $file ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::mtime( string $file ): int|false WP\_Filesystem\_Base::mtime( string $file ): int|false
======================================================
Gets the file modification time.
`$file` string Required Path to file. int|false Unix timestamp representing modification time, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function mtime( $file ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::is_binary( string $text ): bool WP\_Filesystem\_Base::is\_binary( string $text ): bool
======================================================
Determines if the string provided contains binary characters.
`$text` string Required String to test against. bool True if string is binary, false otherwise.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function is_binary( $text ) {
return (bool) preg_match( '|[^\x20-\x7E]|', $text ); // chr(32)..chr(127)
}
```
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_Filesystem_Base::mkdir( string $path, int|false $chmod = false, string|int|false $chown = false, string|int|false $chgrp = false ): bool WP\_Filesystem\_Base::mkdir( string $path, int|false $chmod = false, string|int|false $chown = false, string|int|false $chgrp = false ): bool
=============================================================================================================================================
Creates a directory.
`$path` string Required Path for new directory. `$chmod` int|false Optional The permissions as octal number (or false to skip chmod).
Default: `false`
`$chown` string|int|false Optional A user name or number (or false to skip chown).
Default: `false`
`$chgrp` string|int|false Optional A group name or number (or false to skip chgrp).
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::owner( string $file ): string|false WP\_Filesystem\_Base::owner( string $file ): string|false
=========================================================
Gets the file owner.
`$file` string Required Path to the file. string|false Username of the owner on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function owner( $file ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::cwd(): string|false WP\_Filesystem\_Base::cwd(): string|false
=========================================
Gets the current working directory.
string|false The current working directory on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function cwd() {
return false;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Base::search\_for\_folder()](search_for_folder) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress WP_Filesystem_Base::getnumchmodfromh( string $mode ): string WP\_Filesystem\_Base::getnumchmodfromh( string $mode ): string
==============================================================
Converts \*nix-style file permissions to a octal number.
Converts ‘-rw-r–r–‘ to 0644 From "info at rvgate dot nl"’s comment on the PHP documentation for chmod()
`$mode` string Required string The \*nix-style file permissions. string Octal representation of permissions.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function getnumchmodfromh( $mode ) {
$realmode = '';
$legal = array( '', 'w', 'r', 'x', '-' );
$attarray = preg_split( '//', $mode );
for ( $i = 0, $c = count( $attarray ); $i < $c; $i++ ) {
$key = array_search( $attarray[ $i ], $legal, true );
if ( $key ) {
$realmode .= $legal[ $key ];
}
}
$mode = str_pad( $realmode, 10, '-', STR_PAD_LEFT );
$trans = array(
'-' => '0',
'r' => '4',
'w' => '2',
'x' => '1',
);
$mode = strtr( $mode, $trans );
$newmode = $mode[0];
$newmode .= $mode[1] + $mode[2] + $mode[3];
$newmode .= $mode[4] + $mode[5] + $mode[6];
$newmode .= $mode[7] + $mode[8] + $mode[9];
return $newmode;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::copy( string $source, string $destination, bool $overwrite = false, int|false $mode = false ): bool WP\_Filesystem\_Base::copy( string $source, string $destination, bool $overwrite = false, int|false $mode = false ): bool
=========================================================================================================================
Copies a file.
`$source` string Required Path to the source file. `$destination` string Required Path to the destination file. `$overwrite` bool Optional Whether to overwrite the destination file if it exists.
Default: `false`
`$mode` int|false Optional The permissions as octal number, usually 0644 for files, 0755 for dirs. Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function copy( $source, $destination, $overwrite = false, $mode = false ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::get_contents_array( string $file ): array|false WP\_Filesystem\_Base::get\_contents\_array( string $file ): array|false
=======================================================================
Reads entire file into an array.
`$file` string Required Path to the file. array|false File contents in an array on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function get_contents_array( $file ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::dirlist( string $path, bool $include_hidden = true, bool $recursive = false ): array|false WP\_Filesystem\_Base::dirlist( string $path, bool $include\_hidden = true, bool $recursive = false ): array|false
=================================================================================================================
Gets details for files in a directory or a specific file.
`$path` string Required Path to directory or file. `$include_hidden` bool Optional Whether to include details of hidden ("." prefixed) files.
Default: `true`
`$recursive` bool Optional Whether to recursively include file details in nested directories.
Default: `false`
array|false Array of files. False if unable to list directory contents.
* `name`stringName of the file or directory.
* `perms`string\*nix representation of permissions.
* `permsn`stringOctal representation of permissions.
* `owner`stringOwner name or ID.
* `size`intSize of file in bytes.
* `lastmodunix`intLast modified unix timestamp.
* `lastmod`mixedLast modified month (3 letter) and day (without leading 0).
* `time`intLast modified time.
* `type`stringType of resource. `'f'` for file, `'d'` for directory.
* `files`mixedIf a directory and `$recursive` is true, contains another array of files.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function dirlist( $path, $include_hidden = true, $recursive = false ) {
return false;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_Base::search\_for\_folder()](search_for_folder) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::wp_content_dir(): string WP\_Filesystem\_Base::wp\_content\_dir(): string
================================================
Returns the path on the remote filesystem of WP\_CONTENT\_DIR.
string The location of the remote path.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function wp_content_dir() {
return $this->find_folder( WP_CONTENT_DIR );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Base::find\_folder()](../wp_filesystem_base/find_folder) wp-admin/includes/class-wp-filesystem-base.php | Locates a folder on the remote filesystem. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_Filesystem_Base::move( string $source, string $destination, bool $overwrite = false ): bool WP\_Filesystem\_Base::move( string $source, string $destination, bool $overwrite = false ): bool
================================================================================================
Moves a file.
`$source` string Required Path to the source file. `$destination` string Required Path to the destination file. `$overwrite` bool Optional Whether to overwrite the destination file if it exists.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function move( $source, $destination, $overwrite = false ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::find_base_dir( string $base = '.', bool $verbose = false ): string WP\_Filesystem\_Base::find\_base\_dir( string $base = '.', bool $verbose = false ): string
==========================================================================================
This method has been deprecated. Use [WP\_Filesystem\_Base::abspath()](../wp_filesystem_base/abspath) instead.
Locates a folder on the remote filesystem.
* [WP\_Filesystem\_Base::abspath()](../wp_filesystem_base/abspath)
* [WP\_Filesystem\_Base::wp\_content\_dir()](../wp_filesystem_base/wp_content_dir)
* [WP\_Filesystem\_Base::wp\_plugins\_dir()](../wp_filesystem_base/wp_plugins_dir)
* [WP\_Filesystem\_Base::wp\_themes\_dir()](../wp_filesystem_base/wp_themes_dir)
* [WP\_Filesystem\_Base::wp\_lang\_dir()](../wp_filesystem_base/wp_lang_dir)
`$base` string Optional The folder to start searching from. Default `'.'`. Default: `'.'`
`$verbose` bool Optional True to display debug information. Default: `false`
string The location of the remote path.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function find_base_dir( $base = '.', $verbose = false ) {
_deprecated_function( __FUNCTION__, '2.7.0', 'WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir()' );
$this->verbose = $verbose;
return $this->abspath();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Base::abspath()](abspath) wp-admin/includes/class-wp-filesystem-base.php | Returns the path on the remote filesystem of ABSPATH. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | use [WP\_Filesystem\_Base::abspath()](abspath) or WP\_Filesystem\*Base::wp\*\*\_dir() instead. |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::atime( string $file ): int|false WP\_Filesystem\_Base::atime( string $file ): int|false
======================================================
Gets the file’s last access time.
`$file` string Required Path to file. int|false Unix timestamp representing last access time, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function atime( $file ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::touch( string $file, int $time, int $atime ): bool WP\_Filesystem\_Base::touch( string $file, int $time, int $atime ): bool
========================================================================
Sets the access and modification times of a file.
Note: If $file doesn’t exist, it will be created.
`$file` string Required Path to file. `$time` int Optional Modified time to set for file.
Default 0. `$atime` int Optional Access time to set for file.
Default 0. bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function touch( $file, $time = 0, $atime = 0 ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::delete( string $file, bool $recursive = false, string|false $type = false ): bool WP\_Filesystem\_Base::delete( string $file, bool $recursive = false, string|false $type = false ): bool
=======================================================================================================
Deletes a file or directory.
`$file` string Required Path to the file or directory. `$recursive` bool Optional If set to true, deletes files and folders recursively.
Default: `false`
`$type` string|false Optional Type of resource. `'f'` for file, `'d'` for directory.
Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function delete( $file, $recursive = false, $type = false ) {
return false;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::connect(): bool WP\_Filesystem\_Base::connect(): bool
=====================================
Connects filesystem.
bool True on success, false on failure (always true for [WP\_Filesystem\_Direct](../wp_filesystem_direct)).
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function connect() {
return true;
}
```
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Filesystem_Base::gethchmod( string $file ): string WP\_Filesystem\_Base::gethchmod( string $file ): string
=======================================================
Returns the \*nix-style file permissions for a file.
From the PHP documentation page for fileperms().
`$file` string Required String filename. string The \*nix-style representation of permissions.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
public function gethchmod( $file ) {
$perms = intval( $this->getchmod( $file ), 8 );
if ( ( $perms & 0xC000 ) === 0xC000 ) { // Socket.
$info = 's';
} elseif ( ( $perms & 0xA000 ) === 0xA000 ) { // Symbolic Link.
$info = 'l';
} elseif ( ( $perms & 0x8000 ) === 0x8000 ) { // Regular.
$info = '-';
} elseif ( ( $perms & 0x6000 ) === 0x6000 ) { // Block special.
$info = 'b';
} elseif ( ( $perms & 0x4000 ) === 0x4000 ) { // Directory.
$info = 'd';
} elseif ( ( $perms & 0x2000 ) === 0x2000 ) { // Character special.
$info = 'c';
} elseif ( ( $perms & 0x1000 ) === 0x1000 ) { // FIFO pipe.
$info = 'p';
} else { // Unknown.
$info = 'u';
}
// Owner.
$info .= ( ( $perms & 0x0100 ) ? 'r' : '-' );
$info .= ( ( $perms & 0x0080 ) ? 'w' : '-' );
$info .= ( ( $perms & 0x0040 ) ?
( ( $perms & 0x0800 ) ? 's' : 'x' ) :
( ( $perms & 0x0800 ) ? 'S' : '-' ) );
// Group.
$info .= ( ( $perms & 0x0020 ) ? 'r' : '-' );
$info .= ( ( $perms & 0x0010 ) ? 'w' : '-' );
$info .= ( ( $perms & 0x0008 ) ?
( ( $perms & 0x0400 ) ? 's' : 'x' ) :
( ( $perms & 0x0400 ) ? 'S' : '-' ) );
// World.
$info .= ( ( $perms & 0x0004 ) ? 'r' : '-' );
$info .= ( ( $perms & 0x0002 ) ? 'w' : '-' );
$info .= ( ( $perms & 0x0001 ) ?
( ( $perms & 0x0200 ) ? 't' : 'x' ) :
( ( $perms & 0x0200 ) ? 'T' : '-' ) );
return $info;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem\_Base::getchmod()](getchmod) wp-admin/includes/class-wp-filesystem-base.php | Gets the permissions of the specified file or filepath in their octal format. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress WP_Style_Engine_Processor::add_store( WP_Style_Engine_CSS_Rules_Store $store ): WP_Style_Engine_Processor WP\_Style\_Engine\_Processor::add\_store( WP\_Style\_Engine\_CSS\_Rules\_Store $store ): WP\_Style\_Engine\_Processor
=====================================================================================================================
Adds a store to the processor.
`$store` [WP\_Style\_Engine\_CSS\_Rules\_Store](../wp_style_engine_css_rules_store) Required The store to add. [WP\_Style\_Engine\_Processor](../wp_style_engine_processor) Returns the object to allow chaining methods.
File: `wp-includes/style-engine/class-wp-style-engine-processor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-processor.php/)
```
public function add_store( $store ) {
if ( ! $store instanceof WP_Style_Engine_CSS_Rules_Store ) {
_doing_it_wrong(
__METHOD__,
__( '$store must be an instance of WP_Style_Engine_CSS_Rules_Store' ),
'6.1.0'
);
return $this;
}
$this->stores[ $store->get_name() ] = $store;
return $this;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](../../functions/_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine_Processor::get_css( array $options = array() ): string WP\_Style\_Engine\_Processor::get\_css( array $options = array() ): string
==========================================================================
Gets the CSS rules as a string.
`$options` array Optional An array of options.
* `optimize`boolWhether to optimize the CSS output, e.g., combine rules. Default is `false`.
* `prettify`boolWhether to add new lines and indents to output. Default is the test of whether the global constant `SCRIPT_DEBUG` is defined.
Default: `array()`
string The computed CSS.
File: `wp-includes/style-engine/class-wp-style-engine-processor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-processor.php/)
```
public function get_css( $options = array() ) {
$defaults = array(
'optimize' => true,
'prettify' => defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG,
);
$options = wp_parse_args( $options, $defaults );
// If we have stores, get the rules from them.
foreach ( $this->stores as $store ) {
$this->add_rules( $store->get_all_rules() );
}
// Combine CSS selectors that have identical declarations.
if ( true === $options['optimize'] ) {
$this->combine_rules_selectors();
}
// Build the CSS.
$css = '';
foreach ( $this->css_rules as $rule ) {
$css .= $rule->get_css( $options['prettify'] );
$css .= $options['prettify'] ? "\n" : '';
}
return $css;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Style\_Engine\_Processor::combine\_rules\_selectors()](combine_rules_selectors) wp-includes/style-engine/class-wp-style-engine-processor.php | Combines selectors from the rules store when they have the same styles. |
| [WP\_Style\_Engine\_Processor::add\_rules()](add_rules) wp-includes/style-engine/class-wp-style-engine-processor.php | Adds rules to be processed. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine_Processor::add_rules( WP_Style_Engine_CSS_Rule|WP_Style_Engine_CSS_Rule[] $css_rules ): WP_Style_Engine_Processor WP\_Style\_Engine\_Processor::add\_rules( WP\_Style\_Engine\_CSS\_Rule|WP\_Style\_Engine\_CSS\_Rule[] $css\_rules ): WP\_Style\_Engine\_Processor
=================================================================================================================================================
Adds rules to be processed.
`$css_rules` [WP\_Style\_Engine\_CSS\_Rule](../wp_style_engine_css_rule)|[WP\_Style\_Engine\_CSS\_Rule](../wp_style_engine_css_rule)[] Required A single, or an array of, [WP\_Style\_Engine\_CSS\_Rule](../wp_style_engine_css_rule) objects from a store or otherwise. [WP\_Style\_Engine\_Processor](../wp_style_engine_processor) Returns the object to allow chaining methods.
File: `wp-includes/style-engine/class-wp-style-engine-processor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-processor.php/)
```
public function add_rules( $css_rules ) {
if ( ! is_array( $css_rules ) ) {
$css_rules = array( $css_rules );
}
foreach ( $css_rules as $rule ) {
$selector = $rule->get_selector();
if ( isset( $this->css_rules[ $selector ] ) ) {
$this->css_rules[ $selector ]->add_declarations( $rule->get_declarations() );
continue;
}
$this->css_rules[ $rule->get_selector() ] = $rule;
}
return $this;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Style\_Engine\_Processor::get\_css()](get_css) wp-includes/style-engine/class-wp-style-engine-processor.php | Gets the CSS rules as a string. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Style_Engine_Processor::combine_rules_selectors(): void WP\_Style\_Engine\_Processor::combine\_rules\_selectors(): void
===============================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Combines selectors from the rules store when they have the same styles.
void
File: `wp-includes/style-engine/class-wp-style-engine-processor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-processor.php/)
```
private function combine_rules_selectors() {
// Build an array of selectors along with the JSON-ified styles to make comparisons easier.
$selectors_json = array();
foreach ( $this->css_rules as $rule ) {
$declarations = $rule->get_declarations()->get_declarations();
ksort( $declarations );
$selectors_json[ $rule->get_selector() ] = wp_json_encode( $declarations );
}
// Combine selectors that have the same styles.
foreach ( $selectors_json as $selector => $json ) {
// Get selectors that use the same styles.
$duplicates = array_keys( $selectors_json, $json, true );
// Skip if there are no duplicates.
if ( 1 >= count( $duplicates ) ) {
continue;
}
$declarations = $this->css_rules[ $selector ]->get_declarations();
foreach ( $duplicates as $key ) {
// Unset the duplicates from the $selectors_json array to avoid looping through them as well.
unset( $selectors_json[ $key ] );
// Remove the rules from the rules collection.
unset( $this->css_rules[ $key ] );
}
// Create a new rule with the combined selectors.
$duplicate_selectors = implode( ',', $duplicates );
$this->css_rules[ $duplicate_selectors ] = new WP_Style_Engine_CSS_Rule( $duplicate_selectors, $declarations );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Rule::\_\_construct()](../wp_style_engine_css_rule/__construct) wp-includes/style-engine/class-wp-style-engine-css-rule.php | Constructor |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| Used By | Description |
| --- | --- |
| [WP\_Style\_Engine\_Processor::get\_css()](get_css) wp-includes/style-engine/class-wp-style-engine-processor.php | Gets the CSS rules as a string. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Widget_Form_Customize_Control::to_json() WP\_Widget\_Form\_Customize\_Control::to\_json()
================================================
Gather control params for exporting to JavaScript.
File: `wp-includes/customize/class-wp-widget-form-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-widget-form-customize-control.php/)
```
public function to_json() {
global $wp_registered_widgets;
parent::to_json();
$exported_properties = array( 'widget_id', 'widget_id_base', 'sidebar_id', 'width', 'height', 'is_wide' );
foreach ( $exported_properties as $key ) {
$this->json[ $key ] = $this->$key;
}
// Get the widget_control and widget_content.
require_once ABSPATH . 'wp-admin/includes/widgets.php';
$widget = $wp_registered_widgets[ $this->widget_id ];
if ( ! isset( $widget['params'][0] ) ) {
$widget['params'][0] = array();
}
$args = array(
'widget_id' => $widget['id'],
'widget_name' => $widget['name'],
);
$args = wp_list_widget_controls_dynamic_sidebar(
array(
0 => $args,
1 => $widget['params'][0],
)
);
$widget_control_parts = $this->manager->widgets->get_widget_control_parts( $args );
$this->json['widget_control'] = $widget_control_parts['control'];
$this->json['widget_content'] = $widget_control_parts['content'];
}
```
| Uses | Description |
| --- | --- |
| [wp\_list\_widget\_controls\_dynamic\_sidebar()](../../functions/wp_list_widget_controls_dynamic_sidebar) wp-admin/includes/widgets.php | Retrieves the widget control arguments. |
| [WP\_Customize\_Control::to\_json()](../wp_customize_control/to_json) wp-includes/class-wp-customize-control.php | Refresh the parameters passed to the JavaScript via JSON. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Widget_Form_Customize_Control::active_callback(): bool WP\_Widget\_Form\_Customize\_Control::active\_callback(): bool
==============================================================
Whether the current widget is rendered on the page.
bool Whether the widget is rendered.
File: `wp-includes/customize/class-wp-widget-form-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-widget-form-customize-control.php/)
```
public function active_callback() {
return $this->manager->widgets->is_widget_rendered( $this->widget_id );
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Widget_Form_Customize_Control::render_content() WP\_Widget\_Form\_Customize\_Control::render\_content()
=======================================================
Override render\_content to be no-op since content is exported via to\_json for deferred embedding.
File: `wp-includes/customize/class-wp-widget-form-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-widget-form-customize-control.php/)
```
public function render_content() {}
```
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress Translations::add_entry_or_merge( array|Translation_Entry $entry ): bool Translations::add\_entry\_or\_merge( array|Translation\_Entry $entry ): bool
============================================================================
`$entry` array|[Translation\_Entry](../translation_entry) Required bool
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function add_entry_or_merge( $entry ) {
if ( is_array( $entry ) ) {
$entry = new Translation_Entry( $entry );
}
$key = $entry->key();
if ( false === $key ) {
return false;
}
if ( isset( $this->entries[ $key ] ) ) {
$this->entries[ $key ]->merge_with( $entry );
} else {
$this->entries[ $key ] = &$entry;
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [Translation\_Entry::\_\_construct()](../translation_entry/__construct) wp-includes/pomo/entry.php | |
wordpress Translations::get_plural_forms_count(): int Translations::get\_plural\_forms\_count(): int
==============================================
int
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function get_plural_forms_count() {
return 2;
}
```
| Used By | Description |
| --- | --- |
| [Translations::translate\_plural()](translate_plural) wp-includes/pomo/translations.php | |
wordpress Translations::add_entry( array|Translation_Entry $entry ): bool Translations::add\_entry( array|Translation\_Entry $entry ): bool
=================================================================
Add entry to the PO structure
`$entry` array|[Translation\_Entry](../translation_entry) Required bool true on success, false if the entry doesn't have a key
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function add_entry( $entry ) {
if ( is_array( $entry ) ) {
$entry = new Translation_Entry( $entry );
}
$key = $entry->key();
if ( false === $key ) {
return false;
}
$this->entries[ $key ] = &$entry;
return true;
}
```
| Uses | Description |
| --- | --- |
| [Translation\_Entry::\_\_construct()](../translation_entry/__construct) wp-includes/pomo/entry.php | |
wordpress Translations::translate_plural( string $singular, string $plural, int $count, string $context = null ) Translations::translate\_plural( string $singular, string $plural, int $count, string $context = null )
=======================================================================================================
`$singular` string Required `$plural` string Required `$count` int Required `$context` string Optional Default: `null`
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function translate_plural( $singular, $plural, $count, $context = null ) {
$entry = new Translation_Entry(
array(
'singular' => $singular,
'plural' => $plural,
'context' => $context,
)
);
$translated = $this->translate_entry( $entry );
$index = $this->select_plural_form( $count );
$total_plural_forms = $this->get_plural_forms_count();
if ( $translated && 0 <= $index && $index < $total_plural_forms &&
is_array( $translated->translations ) &&
isset( $translated->translations[ $index ] ) ) {
return $translated->translations[ $index ];
} else {
return 1 == $count ? $singular : $plural;
}
}
```
| Uses | Description |
| --- | --- |
| [Translation\_Entry::\_\_construct()](../translation_entry/__construct) wp-includes/pomo/entry.php | |
| [Translations::translate\_entry()](translate_entry) wp-includes/pomo/translations.php | |
| [Translations::select\_plural\_form()](select_plural_form) wp-includes/pomo/translations.php | Given the number of items, returns the 0-based index of the plural form to use |
| [Translations::get\_plural\_forms\_count()](get_plural_forms_count) wp-includes/pomo/translations.php | |
| Used By | Description |
| --- | --- |
| [\_n()](../../functions/_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [\_nx()](../../functions/_nx) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number, with gettext context. |
wordpress Translations::translate_entry( Translation_Entry $entry ) Translations::translate\_entry( Translation\_Entry $entry )
===========================================================
`$entry` [Translation\_Entry](../translation_entry) Required File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function translate_entry( &$entry ) {
$key = $entry->key();
return isset( $this->entries[ $key ] ) ? $this->entries[ $key ] : false;
}
```
| Used By | Description |
| --- | --- |
| [Translations::translate()](translate) wp-includes/pomo/translations.php | |
| [Translations::translate\_plural()](translate_plural) wp-includes/pomo/translations.php | |
wordpress Translations::get_header( string $header ) Translations::get\_header( string $header )
===========================================
`$header` string Required File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function get_header( $header ) {
return isset( $this->headers[ $header ] ) ? $this->headers[ $header ] : false;
}
```
wordpress Translations::set_headers( array $headers ) Translations::set\_headers( array $headers )
============================================
`$headers` array Required File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function set_headers( $headers ) {
foreach ( $headers as $header => $value ) {
$this->set_header( $header, $value );
}
}
```
| Uses | Description |
| --- | --- |
| [Translations::set\_header()](set_header) wp-includes/pomo/translations.php | Sets $header PO header to $value |
wordpress Translations::merge_with( Object $other ) Translations::merge\_with( Object $other )
==========================================
Merge $other in the current object.
`$other` Object Required Another Translation object, whose translations will be merged in this one (passed by reference). File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function merge_with( &$other ) {
foreach ( $other->entries as $entry ) {
$this->entries[ $entry->key() ] = $entry;
}
}
```
wordpress Translations::set_header( string $header, string $value ) Translations::set\_header( string $header, string $value )
==========================================================
Sets $header PO header to $value
If the header already exists, it will be overwritten
TODO: this should be out of this class, it is gettext specific
`$header` string Required header name, without trailing : `$value` string Required header value, without trailing n File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function set_header( $header, $value ) {
$this->headers[ $header ] = $value;
}
```
| Used By | Description |
| --- | --- |
| [Gettext\_Translations::set\_header()](../gettext_translations/set_header) wp-includes/pomo/translations.php | |
| [Translations::set\_headers()](set_headers) wp-includes/pomo/translations.php | |
wordpress Translations::select_plural_form( int $count ) Translations::select\_plural\_form( int $count )
================================================
Given the number of items, returns the 0-based index of the plural form to use
Here, in the base Translations class, the common logic for English is implemented: 0 if there is one element, 1 otherwise
This function should be overridden by the subclasses. For example MO/PO can derive the logic from their headers.
`$count` int Required number of items File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function select_plural_form( $count ) {
return 1 == $count ? 0 : 1;
}
```
| Used By | Description |
| --- | --- |
| [Translations::translate\_plural()](translate_plural) wp-includes/pomo/translations.php | |
wordpress Translations::translate( string $singular, string $context = null ): string Translations::translate( string $singular, string $context = null ): string
===========================================================================
`$singular` string Required `$context` string Optional Default: `null`
string
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function translate( $singular, $context = null ) {
$entry = new Translation_Entry(
array(
'singular' => $singular,
'context' => $context,
)
);
$translated = $this->translate_entry( $entry );
return ( $translated && ! empty( $translated->translations ) ) ? $translated->translations[0] : $singular;
}
```
| Uses | Description |
| --- | --- |
| [Translation\_Entry::\_\_construct()](../translation_entry/__construct) wp-includes/pomo/entry.php | |
| [Translations::translate\_entry()](translate_entry) wp-includes/pomo/translations.php | |
| Used By | Description |
| --- | --- |
| [translate()](../../functions/translate) wp-includes/l10n.php | Retrieves the translation of $text. |
| [translate\_with\_gettext\_context()](../../functions/translate_with_gettext_context) wp-includes/l10n.php | Retrieves the translation of $text in the context defined in $context. |
wordpress Translations::merge_originals_with( object $other ) Translations::merge\_originals\_with( object $other )
=====================================================
`$other` object Required File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
public function merge_originals_with( &$other ) {
foreach ( $other->entries as $entry ) {
if ( ! isset( $this->entries[ $entry->key() ] ) ) {
$this->entries[ $entry->key() ] = $entry;
} else {
$this->entries[ $entry->key() ]->merge_with( $entry );
}
}
}
```
wordpress WP_REST_Menu_Locations_Controller::get_item( WP_REST_Request $request ): WP_Error|WP_REST_Response WP\_REST\_Menu\_Locations\_Controller::get\_item( WP\_REST\_Request $request ): WP\_Error|WP\_REST\_Response
============================================================================================================
Retrieves a specific menu location.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_Error](../wp_error)|[WP\_REST\_Response](../wp_rest_response) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php/)
```
public function get_item( $request ) {
$registered_menus = get_registered_nav_menus();
if ( ! array_key_exists( $request['location'], $registered_menus ) ) {
return new WP_Error( 'rest_menu_location_invalid', __( 'Invalid menu location.' ), array( 'status' => 404 ) );
}
$location = new stdClass();
$location->name = $request['location'];
$location->description = $registered_menus[ $location->name ];
$data = $this->prepare_item_for_response( $location, $request );
return rest_ensure_response( $data );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Menu\_Locations\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php | Prepares a menu location object for serialization. |
| [get\_registered\_nav\_menus()](../../functions/get_registered_nav_menus) wp-includes/nav-menu.php | Retrieves all registered navigation menu locations in a theme. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menu_Locations_Controller::prepare_item_for_response( stdClass $item, WP_REST_Request $request ): WP_REST_Response WP\_REST\_Menu\_Locations\_Controller::prepare\_item\_for\_response( stdClass $item, WP\_REST\_Request $request ): WP\_REST\_Response
=====================================================================================================================================
Prepares a menu location object for serialization.
`$item` stdClass Required Post status data. `$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response) Menu location data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php/)
```
public function prepare_item_for_response( $item, $request ) {
// Restores the more descriptive, specific name for use within this method.
$location = $item;
$locations = get_nav_menu_locations();
$menu = isset( $locations[ $location->name ] ) ? $locations[ $location->name ] : 0;
$fields = $this->get_fields_for_response( $request );
$data = array();
if ( rest_is_field_included( 'name', $fields ) ) {
$data['name'] = $location->name;
}
if ( rest_is_field_included( 'description', $fields ) ) {
$data['description'] = $location->description;
}
if ( rest_is_field_included( 'menu', $fields ) ) {
$data['menu'] = (int) $menu;
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
$response = rest_ensure_response( $data );
if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
$response->add_links( $this->prepare_links( $location ) );
}
/**
* Filters menu location data returned from the REST API.
*
* @since 5.9.0
*
* @param WP_REST_Response $response The response object.
* @param object $location The original location object.
* @param WP_REST_Request $request Request used to generate the response.
*/
return apply_filters( 'rest_prepare_menu_location', $response, $location, $request );
}
```
[apply\_filters( 'rest\_prepare\_menu\_location', WP\_REST\_Response $response, object $location, WP\_REST\_Request $request )](../../hooks/rest_prepare_menu_location)
Filters menu location data returned from the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Menu\_Locations\_Controller::prepare\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php | Prepares links for the request. |
| [rest\_is\_field\_included()](../../functions/rest_is_field_included) wp-includes/rest-api.php | Given an array of fields to include in a response, some of which may be `nested.fields`, determine whether the provided field should be included in the response body. |
| [get\_nav\_menu\_locations()](../../functions/get_nav_menu_locations) wp-includes/nav-menu.php | Retrieves all registered navigation menu locations and the menus assigned to them. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menu\_Locations\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php | Retrieves all menu locations, depending on user context. |
| [WP\_REST\_Menu\_Locations\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php | Retrieves a specific menu location. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Menu_Locations_Controller::prepare_links( stdClass $location ): array WP\_REST\_Menu\_Locations\_Controller::prepare\_links( stdClass $location ): array
==================================================================================
Prepares links for the request.
`$location` stdClass Required Menu location. array Links for the given menu location.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php/)
```
protected function prepare_links( $location ) {
$base = sprintf( '%s/%s', $this->namespace, $this->rest_base );
// Entity meta.
$links = array(
'self' => array(
'href' => rest_url( trailingslashit( $base ) . $location->name ),
),
'collection' => array(
'href' => rest_url( $base ),
),
);
$locations = get_nav_menu_locations();
$menu = isset( $locations[ $location->name ] ) ? $locations[ $location->name ] : 0;
if ( $menu ) {
$path = rest_get_route_for_term( $menu );
if ( $path ) {
$url = rest_url( $path );
$links['https://api.w.org/menu'][] = array(
'href' => $url,
'embeddable' => true,
);
}
}
return $links;
}
```
| Uses | Description |
| --- | --- |
| [rest\_get\_route\_for\_term()](../../functions/rest_get_route_for_term) wp-includes/rest-api.php | Gets the REST API route for a term. |
| [get\_nav\_menu\_locations()](../../functions/get_nav_menu_locations) wp-includes/nav-menu.php | Retrieves all registered navigation menu locations and the menus assigned to them. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menu\_Locations\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php | Prepares a menu location object for serialization. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menu_Locations_Controller::get_items( WP_REST_Request $request ): WP_Error|WP_REST_Response WP\_REST\_Menu\_Locations\_Controller::get\_items( WP\_REST\_Request $request ): WP\_Error|WP\_REST\_Response
=============================================================================================================
Retrieves all menu locations, depending on user context.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_Error](../wp_error)|[WP\_REST\_Response](../wp_rest_response) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php/)
```
public function get_items( $request ) {
$data = array();
foreach ( get_registered_nav_menus() as $name => $description ) {
$location = new stdClass();
$location->name = $name;
$location->description = $description;
$location = $this->prepare_item_for_response( $location, $request );
$data[ $name ] = $this->prepare_response_for_collection( $location );
}
return rest_ensure_response( $data );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Menu\_Locations\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php | Prepares a menu location object for serialization. |
| [get\_registered\_nav\_menus()](../../functions/get_registered_nav_menus) wp-includes/nav-menu.php | Retrieves all registered navigation menu locations in a theme. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menu_Locations_Controller::get_items_permissions_check( WP_REST_Request $request ): WP_Error|bool WP\_REST\_Menu\_Locations\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): WP\_Error|bool
===================================================================================================================
Checks whether a given request has permission to read menu locations.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_Error](../wp_error)|bool True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php/)
```
public function get_items_permissions_check( $request ) {
if ( ! current_user_can( 'edit_theme_options' ) ) {
return new WP_Error(
'rest_cannot_view',
__( 'Sorry, you are not allowed to view menu locations.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menu_Locations_Controller::register_routes() WP\_REST\_Menu\_Locations\_Controller::register\_routes()
=========================================================
Registers the routes for the objects of the controller.
* [register\_rest\_route()](../../functions/register_rest_route)
File: `wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php/)
```
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base,
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => $this->get_collection_params(),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/(?P<location>[\w-]+)',
array(
'args' => array(
'location' => array(
'description' => __( 'An alphanumeric identifier for the menu location.' ),
'type' => 'string',
),
),
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this, 'get_item_permissions_check' ),
'args' => array(
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Menu\_Locations\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php | Retrieves the query params for collections. |
| [register\_rest\_route()](../../functions/register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menu_Locations_Controller::get_collection_params(): array WP\_REST\_Menu\_Locations\_Controller::get\_collection\_params(): array
=======================================================================
Retrieves the query params for collections.
array Collection parameters.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php/)
```
public function get_collection_params() {
return array(
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
);
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menu\_Locations\_Controller::register\_routes()](register_routes) wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php | Registers the routes for the objects of the controller. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menu_Locations_Controller::__construct() WP\_REST\_Menu\_Locations\_Controller::\_\_construct()
======================================================
Menu Locations Constructor.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php/)
```
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'menu-locations';
}
```
| Used By | Description |
| --- | --- |
| [create\_initial\_rest\_routes()](../../functions/create_initial_rest_routes) wp-includes/rest-api.php | Registers default REST API routes. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menu_Locations_Controller::get_item_permissions_check( WP_REST_Request $request ): WP_Error|bool WP\_REST\_Menu\_Locations\_Controller::get\_item\_permissions\_check( WP\_REST\_Request $request ): WP\_Error|bool
==================================================================================================================
Checks if a given request has access to read a menu location.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_Error](../wp_error)|bool True if the request has read access for the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php/)
```
public function get_item_permissions_check( $request ) {
if ( ! current_user_can( 'edit_theme_options' ) ) {
return new WP_Error(
'rest_cannot_view',
__( 'Sorry, you are not allowed to view menu locations.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Menu_Locations_Controller::get_item_schema(): array WP\_REST\_Menu\_Locations\_Controller::get\_item\_schema(): array
=================================================================
Retrieves the menu location’s schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php/)
```
public function get_item_schema() {
if ( $this->schema ) {
return $this->add_additional_fields_schema( $this->schema );
}
$this->schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'menu-location',
'type' => 'object',
'properties' => array(
'name' => array(
'description' => __( 'The name of the menu location.' ),
'type' => 'string',
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
'description' => array(
'description' => __( 'The description of the menu location.' ),
'type' => 'string',
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
'menu' => array(
'description' => __( 'The ID of the assigned menu.' ),
'type' => 'integer',
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
),
);
return $this->add_additional_fields_schema( $this->schema );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Http_Curl::stream_headers( resource $handle, string $headers ): int WP\_Http\_Curl::stream\_headers( resource $handle, string $headers ): int
=========================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Grabs the headers of the cURL request.
Each header is sent individually to this callback, so we append to the `$header` property for temporary storage
`$handle` resource Required cURL handle. `$headers` string Required cURL request headers. int Length of the request headers.
File: `wp-includes/class-wp-http-curl.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-curl.php/)
```
private function stream_headers( $handle, $headers ) {
$this->headers .= $headers;
return strlen( $headers );
}
```
| Version | Description |
| --- | --- |
| [3.2.0](https://developer.wordpress.org/reference/since/3.2.0/) | Introduced. |
wordpress WP_Http_Curl::test( array $args = array() ): bool WP\_Http\_Curl::test( array $args = array() ): bool
===================================================
Determines whether this class can be used for retrieving a URL.
`$args` array Optional Array of request arguments. Default: `array()`
bool False means this class can not be used, true means it can.
File: `wp-includes/class-wp-http-curl.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-curl.php/)
```
public static function test( $args = array() ) {
if ( ! function_exists( 'curl_init' ) || ! function_exists( 'curl_exec' ) ) {
return false;
}
$is_ssl = isset( $args['ssl'] ) && $args['ssl'];
if ( $is_ssl ) {
$curl_version = curl_version();
// Check whether this cURL version support SSL requests.
if ( ! ( CURL_VERSION_SSL & $curl_version['features'] ) ) {
return false;
}
}
/**
* Filters whether cURL can be used as a transport for retrieving a URL.
*
* @since 2.7.0
*
* @param bool $use_class Whether the class can be used. Default true.
* @param array $args An array of request arguments.
*/
return apply_filters( 'use_curl_transport', true, $args );
}
```
[apply\_filters( 'use\_curl\_transport', bool $use\_class, array $args )](../../hooks/use_curl_transport)
Filters whether cURL can be used as a transport for retrieving a URL.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_Http_Curl::stream_body( resource $handle, string $data ): int WP\_Http\_Curl::stream\_body( resource $handle, string $data ): int
===================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Grabs the body of the cURL request.
The contents of the document are passed in chunks, so we append to the `$body` property for temporary storage. Returning a length shorter than the length of `$data` passed in will cause cURL to abort the request with `CURLE_WRITE_ERROR`.
`$handle` resource Required cURL handle. `$data` string Required cURL request body. int Total bytes of data written.
File: `wp-includes/class-wp-http-curl.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-curl.php/)
```
private function stream_body( $handle, $data ) {
$data_length = strlen( $data );
if ( $this->max_body_length && ( $this->bytes_written_total + $data_length ) > $this->max_body_length ) {
$data_length = ( $this->max_body_length - $this->bytes_written_total );
$data = substr( $data, 0, $data_length );
}
if ( $this->stream_handle ) {
$bytes_written = fwrite( $this->stream_handle, $data );
} else {
$this->body .= $data;
$bytes_written = $data_length;
}
$this->bytes_written_total += $bytes_written;
// Upon event of this function returning less than strlen( $data ) curl will error with CURLE_WRITE_ERROR.
return $bytes_written;
}
```
| Version | Description |
| --- | --- |
| [3.6.0](https://developer.wordpress.org/reference/since/3.6.0/) | Introduced. |
wordpress WP_Http_Curl::request( string $url, string|array $args = array() ): array|WP_Error WP\_Http\_Curl::request( string $url, string|array $args = array() ): array|WP\_Error
=====================================================================================
Send a HTTP request to a URI using cURL extension.
`$url` string Required The request URL. `$args` string|array Optional Override the defaults. Default: `array()`
array|[WP\_Error](../wp_error) Array containing `'headers'`, `'body'`, `'response'`, `'cookies'`, `'filename'`. A [WP\_Error](../wp_error) instance upon error
File: `wp-includes/class-wp-http-curl.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-curl.php/)
```
public function request( $url, $args = array() ) {
$defaults = array(
'method' => 'GET',
'timeout' => 5,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => null,
'cookies' => array(),
);
$parsed_args = wp_parse_args( $args, $defaults );
if ( isset( $parsed_args['headers']['User-Agent'] ) ) {
$parsed_args['user-agent'] = $parsed_args['headers']['User-Agent'];
unset( $parsed_args['headers']['User-Agent'] );
} elseif ( isset( $parsed_args['headers']['user-agent'] ) ) {
$parsed_args['user-agent'] = $parsed_args['headers']['user-agent'];
unset( $parsed_args['headers']['user-agent'] );
}
// Construct Cookie: header if any cookies are set.
WP_Http::buildCookieHeader( $parsed_args );
$handle = curl_init();
// cURL offers really easy proxy support.
$proxy = new WP_HTTP_Proxy();
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
if ( $proxy->use_authentication() ) {
curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
}
}
$is_local = isset( $parsed_args['local'] ) && $parsed_args['local'];
$ssl_verify = isset( $parsed_args['sslverify'] ) && $parsed_args['sslverify'];
if ( $is_local ) {
/** This filter is documented in wp-includes/class-wp-http-streams.php */
$ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify, $url );
} elseif ( ! $is_local ) {
/** This filter is documented in wp-includes/class-wp-http.php */
$ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify, $url );
}
/*
* CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since.
* a value of 0 will allow an unlimited timeout.
*/
$timeout = (int) ceil( $parsed_args['timeout'] );
curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $handle, CURLOPT_URL, $url );
curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( true === $ssl_verify ) ? 2 : false );
curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
if ( $ssl_verify ) {
curl_setopt( $handle, CURLOPT_CAINFO, $parsed_args['sslcertificates'] );
}
curl_setopt( $handle, CURLOPT_USERAGENT, $parsed_args['user-agent'] );
/*
* The option doesn't work with safe mode or when open_basedir is set, and there's
* a bug #17490 with redirected POST requests, so handle redirections outside Curl.
*/
curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, false );
curl_setopt( $handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
switch ( $parsed_args['method'] ) {
case 'HEAD':
curl_setopt( $handle, CURLOPT_NOBODY, true );
break;
case 'POST':
curl_setopt( $handle, CURLOPT_POST, true );
curl_setopt( $handle, CURLOPT_POSTFIELDS, $parsed_args['body'] );
break;
case 'PUT':
curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
curl_setopt( $handle, CURLOPT_POSTFIELDS, $parsed_args['body'] );
break;
default:
curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, $parsed_args['method'] );
if ( ! is_null( $parsed_args['body'] ) ) {
curl_setopt( $handle, CURLOPT_POSTFIELDS, $parsed_args['body'] );
}
break;
}
if ( true === $parsed_args['blocking'] ) {
curl_setopt( $handle, CURLOPT_HEADERFUNCTION, array( $this, 'stream_headers' ) );
curl_setopt( $handle, CURLOPT_WRITEFUNCTION, array( $this, 'stream_body' ) );
}
curl_setopt( $handle, CURLOPT_HEADER, false );
if ( isset( $parsed_args['limit_response_size'] ) ) {
$this->max_body_length = (int) $parsed_args['limit_response_size'];
} else {
$this->max_body_length = false;
}
// If streaming to a file open a file handle, and setup our curl streaming handler.
if ( $parsed_args['stream'] ) {
if ( ! WP_DEBUG ) {
$this->stream_handle = @fopen( $parsed_args['filename'], 'w+' );
} else {
$this->stream_handle = fopen( $parsed_args['filename'], 'w+' );
}
if ( ! $this->stream_handle ) {
return new WP_Error(
'http_request_failed',
sprintf(
/* translators: 1: fopen(), 2: File name. */
__( 'Could not open handle for %1$s to %2$s.' ),
'fopen()',
$parsed_args['filename']
)
);
}
} else {
$this->stream_handle = false;
}
if ( ! empty( $parsed_args['headers'] ) ) {
// cURL expects full header strings in each element.
$headers = array();
foreach ( $parsed_args['headers'] as $name => $value ) {
$headers[] = "{$name}: $value";
}
curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
}
if ( '1.0' === $parsed_args['httpversion'] ) {
curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
} else {
curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
}
/**
* Fires before the cURL request is executed.
*
* Cookies are not currently handled by the HTTP API. This action allows
* plugins to handle cookies themselves.
*
* @since 2.8.0
*
* @param resource $handle The cURL handle returned by curl_init() (passed by reference).
* @param array $parsed_args The HTTP request arguments.
* @param string $url The request URL.
*/
do_action_ref_array( 'http_api_curl', array( &$handle, $parsed_args, $url ) );
// We don't need to return the body, so don't. Just execute request and return.
if ( ! $parsed_args['blocking'] ) {
curl_exec( $handle );
$curl_error = curl_error( $handle );
if ( $curl_error ) {
curl_close( $handle );
return new WP_Error( 'http_request_failed', $curl_error );
}
if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ), true ) ) {
curl_close( $handle );
return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
}
curl_close( $handle );
return array(
'headers' => array(),
'body' => '',
'response' => array(
'code' => false,
'message' => false,
),
'cookies' => array(),
);
}
curl_exec( $handle );
$processed_headers = WP_Http::processHeaders( $this->headers, $url );
$body = $this->body;
$bytes_written_total = $this->bytes_written_total;
$this->headers = '';
$this->body = '';
$this->bytes_written_total = 0;
$curl_error = curl_errno( $handle );
// If an error occurred, or, no response.
if ( $curl_error || ( 0 === strlen( $body ) && empty( $processed_headers['headers'] ) ) ) {
if ( CURLE_WRITE_ERROR /* 23 */ === $curl_error ) {
if ( ! $this->max_body_length || $this->max_body_length !== $bytes_written_total ) {
if ( $parsed_args['stream'] ) {
curl_close( $handle );
fclose( $this->stream_handle );
return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
} else {
curl_close( $handle );
return new WP_Error( 'http_request_failed', curl_error( $handle ) );
}
}
} else {
$curl_error = curl_error( $handle );
if ( $curl_error ) {
curl_close( $handle );
return new WP_Error( 'http_request_failed', $curl_error );
}
}
if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ), true ) ) {
curl_close( $handle );
return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
}
}
curl_close( $handle );
if ( $parsed_args['stream'] ) {
fclose( $this->stream_handle );
}
$response = array(
'headers' => $processed_headers['headers'],
'body' => null,
'response' => $processed_headers['response'],
'cookies' => $processed_headers['cookies'],
'filename' => $parsed_args['filename'],
);
// Handle redirects.
$redirect_response = WP_Http::handle_redirects( $url, $parsed_args, $response );
if ( false !== $redirect_response ) {
return $redirect_response;
}
if ( true === $parsed_args['decompress']
&& true === WP_Http_Encoding::should_decode( $processed_headers['headers'] )
) {
$body = WP_Http_Encoding::decompress( $body );
}
$response['body'] = $body;
return $response;
}
```
[apply\_filters( 'https\_local\_ssl\_verify', bool $ssl\_verify, string $url )](../../hooks/https_local_ssl_verify)
Filters whether SSL should be verified for local HTTP API requests.
[apply\_filters( 'https\_ssl\_verify', bool $ssl\_verify, string $url )](../../hooks/https_ssl_verify)
Filters whether SSL should be verified for non-local requests.
[do\_action\_ref\_array( 'http\_api\_curl', resource $handle, array $parsed\_args, string $url )](../../hooks/http_api_curl)
Fires before the cURL request is executed.
| Uses | Description |
| --- | --- |
| [WP\_Http\_Encoding::should\_decode()](../wp_http_encoding/should_decode) wp-includes/class-wp-http-encoding.php | Whether the content be decoded based on the headers. |
| [WP\_Http\_Encoding::decompress()](../wp_http_encoding/decompress) wp-includes/class-wp-http-encoding.php | Decompression of deflated string. |
| [WP\_Http::handle\_redirects()](../wp_http/handle_redirects) wp-includes/class-wp-http.php | Handles an HTTP redirect and follows it if appropriate. |
| [WP\_Http::buildCookieHeader()](../wp_http/buildcookieheader) wp-includes/class-wp-http.php | Takes the arguments for a ::request() and checks for the cookie array. |
| [WP\_Http::processHeaders()](../wp_http/processheaders) wp-includes/class-wp-http.php | Transforms header string into an array. |
| [do\_action\_ref\_array()](../../functions/do_action_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook, specifying arguments in an array. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Meta_Fields::default_additional_properties_to_false( array $schema ): array WP\_REST\_Meta\_Fields::default\_additional\_properties\_to\_false( array $schema ): array
==========================================================================================
This method has been deprecated. Use [rest\_default\_additional\_properties\_to\_false()](../../functions/rest_default_additional_properties_to_false) instead.
Recursively add additionalProperties = false to all objects in a schema if no additionalProperties setting is specified.
This is needed to restrict properties of objects in meta values to only registered items, as the REST API will allow additional properties by default.
`$schema` array Required The schema array. array
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
protected function default_additional_properties_to_false( $schema ) {
_deprecated_function( __METHOD__, '5.6.0', 'rest_default_additional_properties_to_false()' );
return rest_default_additional_properties_to_false( $schema );
}
```
| Uses | Description |
| --- | --- |
| [rest\_default\_additional\_properties\_to\_false()](../../functions/rest_default_additional_properties_to_false) wp-includes/rest-api.php | Sets the “additionalProperties” to false by default for all object definitions in the schema. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Use [rest\_default\_additional\_properties\_to\_false()](../../functions/rest_default_additional_properties_to_false) instead. |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::prepare_value_for_response( mixed $value, WP_REST_Request $request, array $args ): mixed WP\_REST\_Meta\_Fields::prepare\_value\_for\_response( mixed $value, WP\_REST\_Request $request, array $args ): mixed
=====================================================================================================================
Prepares a meta value for a response.
This is required because some native types cannot be stored correctly in the database, such as booleans. We need to cast back to the relevant type before passing back to JSON.
`$value` mixed Required Meta value to prepare. `$request` [WP\_REST\_Request](../wp_rest_request) Required Current request object. `$args` array Required Options for the field. mixed Prepared value.
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
protected function prepare_value_for_response( $value, $request, $args ) {
if ( ! empty( $args['prepare_callback'] ) ) {
$value = call_user_func( $args['prepare_callback'], $value, $request, $args );
}
return $value;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::get\_value()](get_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the meta field value. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::get_registered_fields(): array WP\_REST\_Meta\_Fields::get\_registered\_fields(): array
========================================================
Retrieves all the registered meta fields.
array Registered fields.
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
protected function get_registered_fields() {
$registered = array();
$meta_type = $this->get_meta_type();
$meta_subtype = $this->get_meta_subtype();
$meta_keys = get_registered_meta_keys( $meta_type );
if ( ! empty( $meta_subtype ) ) {
$meta_keys = array_merge( $meta_keys, get_registered_meta_keys( $meta_type, $meta_subtype ) );
}
foreach ( $meta_keys as $name => $args ) {
if ( empty( $args['show_in_rest'] ) ) {
continue;
}
$rest_args = array();
if ( is_array( $args['show_in_rest'] ) ) {
$rest_args = $args['show_in_rest'];
}
$default_args = array(
'name' => $name,
'single' => $args['single'],
'type' => ! empty( $args['type'] ) ? $args['type'] : null,
'schema' => array(),
'prepare_callback' => array( $this, 'prepare_value' ),
);
$default_schema = array(
'type' => $default_args['type'],
'description' => empty( $args['description'] ) ? '' : $args['description'],
'default' => isset( $args['default'] ) ? $args['default'] : null,
);
$rest_args = array_merge( $default_args, $rest_args );
$rest_args['schema'] = array_merge( $default_schema, $rest_args['schema'] );
$type = ! empty( $rest_args['type'] ) ? $rest_args['type'] : null;
$type = ! empty( $rest_args['schema']['type'] ) ? $rest_args['schema']['type'] : $type;
if ( null === $rest_args['schema']['default'] ) {
$rest_args['schema']['default'] = static::get_empty_value_for_type( $type );
}
$rest_args['schema'] = rest_default_additional_properties_to_false( $rest_args['schema'] );
if ( ! in_array( $type, array( 'string', 'boolean', 'integer', 'number', 'array', 'object' ), true ) ) {
continue;
}
if ( empty( $rest_args['single'] ) ) {
$rest_args['schema'] = array(
'type' => 'array',
'items' => $rest_args['schema'],
);
}
$registered[ $name ] = $rest_args;
}
return $registered;
}
```
| Uses | Description |
| --- | --- |
| [rest\_default\_additional\_properties\_to\_false()](../../functions/rest_default_additional_properties_to_false) wp-includes/rest-api.php | Sets the “additionalProperties” to false by default for all object definitions in the schema. |
| [WP\_REST\_Meta\_Fields::get\_meta\_subtype()](get_meta_subtype) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the object meta subtype. |
| [WP\_REST\_Meta\_Fields::get\_meta\_type()](get_meta_type) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the object meta type. |
| [get\_registered\_meta\_keys()](../../functions/get_registered_meta_keys) wp-includes/meta.php | Retrieves a list of registered metadata args for an object type, keyed by their meta keys. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::is\_meta\_value\_same\_as\_stored\_value()](is_meta_value_same_as_stored_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Checks if the user provided value is equivalent to a stored value for the given meta key. |
| [WP\_REST\_Meta\_Fields::get\_field\_schema()](get_field_schema) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the object’s meta schema, conforming to JSON Schema. |
| [WP\_REST\_Meta\_Fields::update\_value()](update_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates meta values. |
| [WP\_REST\_Meta\_Fields::get\_value()](get_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the meta field value. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::is_meta_value_same_as_stored_value( string $meta_key, string $subtype, mixed $stored_value, mixed $user_value ): bool WP\_REST\_Meta\_Fields::is\_meta\_value\_same\_as\_stored\_value( string $meta\_key, string $subtype, mixed $stored\_value, mixed $user\_value ): bool
======================================================================================================================================================
Checks if the user provided value is equivalent to a stored value for the given meta key.
`$meta_key` string Required The meta key being checked. `$subtype` string Required The object subtype. `$stored_value` mixed Required The currently stored value retrieved from [get\_metadata()](../../functions/get_metadata) . `$user_value` mixed Required The value provided by the user. bool
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
protected function is_meta_value_same_as_stored_value( $meta_key, $subtype, $stored_value, $user_value ) {
$args = $this->get_registered_fields()[ $meta_key ];
$sanitized = sanitize_meta( $meta_key, $user_value, $this->get_meta_type(), $subtype );
if ( in_array( $args['type'], array( 'string', 'number', 'integer', 'boolean' ), true ) ) {
// The return value of get_metadata will always be a string for scalar types.
$sanitized = (string) $sanitized;
}
return $sanitized === $stored_value;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::get\_registered\_fields()](get_registered_fields) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves all the registered meta fields. |
| [WP\_REST\_Meta\_Fields::get\_meta\_type()](get_meta_type) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the object meta type. |
| [sanitize\_meta()](../../functions/sanitize_meta) wp-includes/meta.php | Sanitizes meta value. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::update\_multi\_meta\_value()](update_multi_meta_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates multiple meta values for an object. |
| [WP\_REST\_Meta\_Fields::update\_meta\_value()](update_meta_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates a meta value for an object. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::register_field() WP\_REST\_Meta\_Fields::register\_field()
=========================================
This method has been deprecated. Use [register\_rest\_field()](../../functions/register_rest_field) instead.
Registers the meta field.
* [register\_rest\_field()](../../functions/register_rest_field)
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
public function register_field() {
_deprecated_function( __METHOD__, '5.6.0' );
register_rest_field(
$this->get_rest_field_type(),
'meta',
array(
'get_callback' => array( $this, 'get_value' ),
'update_callback' => array( $this, 'update_value' ),
'schema' => $this->get_field_schema(),
)
);
}
```
| Uses | Description |
| --- | --- |
| [register\_rest\_field()](../../functions/register_rest_field) wp-includes/rest-api.php | Registers a new field on an existing WordPress object type. |
| [WP\_REST\_Meta\_Fields::get\_field\_schema()](get_field_schema) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the object’s meta schema, conforming to JSON Schema. |
| [WP\_REST\_Meta\_Fields::get\_rest\_field\_type()](get_rest_field_type) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the object type for [register\_rest\_field()](../../functions/register_rest_field) . |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | This method has been deprecated. Use [register\_rest\_field()](../../functions/register_rest_field) instead. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::get_meta_subtype(): string WP\_REST\_Meta\_Fields::get\_meta\_subtype(): string
====================================================
Retrieves the object meta subtype.
string Subtype for the meta type, or empty string if no specific subtype.
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
protected function get_meta_subtype() {
return '';
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::get\_registered\_fields()](get_registered_fields) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves all the registered meta fields. |
| Version | Description |
| --- | --- |
| [4.9.8](https://developer.wordpress.org/reference/since/4.9.8/) | Introduced. |
wordpress WP_REST_Meta_Fields::update_multi_meta_value( int $object_id, string $meta_key, string $name, array $values ): true|WP_Error WP\_REST\_Meta\_Fields::update\_multi\_meta\_value( int $object\_id, string $meta\_key, string $name, array $values ): true|WP\_Error
=====================================================================================================================================
Updates multiple meta values for an object.
Alters the list of values in the database to match the list of provided values.
`$object_id` int Required Object ID to update. `$meta_key` string Required Key for the custom field. `$name` string Required Name for the field that is exposed in the REST API. `$values` array Required List of values to update to. true|[WP\_Error](../wp_error) True if meta fields are updated, [WP\_Error](../wp_error) otherwise.
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
protected function update_multi_meta_value( $object_id, $meta_key, $name, $values ) {
$meta_type = $this->get_meta_type();
if ( ! current_user_can( "edit_{$meta_type}_meta", $object_id, $meta_key ) ) {
return new WP_Error(
'rest_cannot_update',
/* translators: %s: Custom field key. */
sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
array(
'key' => $name,
'status' => rest_authorization_required_code(),
)
);
}
$current_values = get_metadata( $meta_type, $object_id, $meta_key, false );
$subtype = get_object_subtype( $meta_type, $object_id );
if ( ! is_array( $current_values ) ) {
$current_values = array();
}
$to_remove = $current_values;
$to_add = $values;
foreach ( $to_add as $add_key => $value ) {
$remove_keys = array_keys(
array_filter(
$current_values,
function ( $stored_value ) use ( $meta_key, $subtype, $value ) {
return $this->is_meta_value_same_as_stored_value( $meta_key, $subtype, $stored_value, $value );
}
)
);
if ( empty( $remove_keys ) ) {
continue;
}
if ( count( $remove_keys ) > 1 ) {
// To remove, we need to remove first, then add, so don't touch.
continue;
}
$remove_key = $remove_keys[0];
unset( $to_remove[ $remove_key ] );
unset( $to_add[ $add_key ] );
}
/*
* `delete_metadata` removes _all_ instances of the value, so only call once. Otherwise,
* `delete_metadata` will return false for subsequent calls of the same value.
* Use serialization to produce a predictable string that can be used by array_unique.
*/
$to_remove = array_map( 'maybe_unserialize', array_unique( array_map( 'maybe_serialize', $to_remove ) ) );
foreach ( $to_remove as $value ) {
if ( ! delete_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash( $value ) ) ) {
return new WP_Error(
'rest_meta_database_error',
/* translators: %s: Custom field key. */
sprintf( __( 'Could not update the meta value of %s in database.' ), $meta_key ),
array(
'key' => $name,
'status' => WP_Http::INTERNAL_SERVER_ERROR,
)
);
}
}
foreach ( $to_add as $value ) {
if ( ! add_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash( $value ) ) ) {
return new WP_Error(
'rest_meta_database_error',
/* translators: %s: Custom field key. */
sprintf( __( 'Could not update the meta value of %s in database.' ), $meta_key ),
array(
'key' => $name,
'status' => WP_Http::INTERNAL_SERVER_ERROR,
)
);
}
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::is\_meta\_value\_same\_as\_stored\_value()](is_meta_value_same_as_stored_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Checks if the user provided value is equivalent to a stored value for the given meta key. |
| [get\_object\_subtype()](../../functions/get_object_subtype) wp-includes/meta.php | Returns the object subtype for a given object ID of a specific type. |
| [WP\_REST\_Meta\_Fields::get\_meta\_type()](get_meta_type) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the object meta type. |
| [get\_metadata()](../../functions/get_metadata) wp-includes/meta.php | Retrieves the value of a metadata field for the specified object type and ID. |
| [delete\_metadata()](../../functions/delete_metadata) wp-includes/meta.php | Deletes metadata for the specified object. |
| [add\_metadata()](../../functions/add_metadata) wp-includes/meta.php | Adds metadata for the specified object. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::update\_value()](update_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates meta values. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::get_value( int $object_id, WP_REST_Request $request ): array WP\_REST\_Meta\_Fields::get\_value( int $object\_id, WP\_REST\_Request $request ): array
========================================================================================
Retrieves the meta field value.
`$object_id` int Required Object ID to fetch meta for. `$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. array Array containing the meta values keyed by name.
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
public function get_value( $object_id, $request ) {
$fields = $this->get_registered_fields();
$response = array();
foreach ( $fields as $meta_key => $args ) {
$name = $args['name'];
$all_values = get_metadata( $this->get_meta_type(), $object_id, $meta_key, false );
if ( $args['single'] ) {
if ( empty( $all_values ) ) {
$value = $args['schema']['default'];
} else {
$value = $all_values[0];
}
$value = $this->prepare_value_for_response( $value, $request, $args );
} else {
$value = array();
if ( is_array( $all_values ) ) {
foreach ( $all_values as $row ) {
$value[] = $this->prepare_value_for_response( $row, $request, $args );
}
}
}
$response[ $name ] = $value;
}
return $response;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::get\_registered\_fields()](get_registered_fields) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves all the registered meta fields. |
| [WP\_REST\_Meta\_Fields::prepare\_value\_for\_response()](prepare_value_for_response) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Prepares a meta value for a response. |
| [WP\_REST\_Meta\_Fields::get\_meta\_type()](get_meta_type) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the object meta type. |
| [get\_metadata()](../../functions/get_metadata) wp-includes/meta.php | Retrieves the value of a metadata field for the specified object type and ID. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Meta_Fields::prepare_value( mixed $value, WP_REST_Request $request, array $args ): mixed WP\_REST\_Meta\_Fields::prepare\_value( mixed $value, WP\_REST\_Request $request, array $args ): mixed
======================================================================================================
Prepares a meta value for output.
Default preparation for meta fields. Override by passing the `prepare_callback` in your `show_in_rest` options.
`$value` mixed Required Meta value from the database. `$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. `$args` array Required REST-specific options for the meta key. mixed Value prepared for output. If a non-JsonSerializable object, null.
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
public static function prepare_value( $value, $request, $args ) {
if ( $args['single'] ) {
$schema = $args['schema'];
} else {
$schema = $args['schema']['items'];
}
if ( '' === $value && in_array( $schema['type'], array( 'boolean', 'integer', 'number' ), true ) ) {
$value = static::get_empty_value_for_type( $schema['type'] );
}
if ( is_wp_error( rest_validate_value_from_schema( $value, $schema ) ) ) {
return null;
}
return rest_sanitize_value_from_schema( $value, $schema );
}
```
| Uses | Description |
| --- | --- |
| [rest\_sanitize\_value\_from\_schema()](../../functions/rest_sanitize_value_from_schema) wp-includes/rest-api.php | Sanitize a value based on a schema. |
| [rest\_validate\_value\_from\_schema()](../../functions/rest_validate_value_from_schema) wp-includes/rest-api.php | Validate a value based on a schema. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::check_meta_is_array( mixed $value, WP_REST_Request $request, string $param ): array|false WP\_REST\_Meta\_Fields::check\_meta\_is\_array( mixed $value, WP\_REST\_Request $request, string $param ): array|false
======================================================================================================================
Check the ‘meta’ value of a request is an associative array.
`$value` mixed Required The meta value submitted in the request. `$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. `$param` string Required The parameter name. array|false The meta array, if valid, false otherwise.
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
public function check_meta_is_array( $value, $request, $param ) {
if ( ! is_array( $value ) ) {
return false;
}
return $value;
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::update_meta_value( int $object_id, string $meta_key, string $name, mixed $value ): true|WP_Error WP\_REST\_Meta\_Fields::update\_meta\_value( int $object\_id, string $meta\_key, string $name, mixed $value ): true|WP\_Error
=============================================================================================================================
Updates a meta value for an object.
`$object_id` int Required Object ID to update. `$meta_key` string Required Key for the custom field. `$name` string Required Name for the field that is exposed in the REST API. `$value` mixed Required Updated value. true|[WP\_Error](../wp_error) True if the meta field was updated, [WP\_Error](../wp_error) otherwise.
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
protected function update_meta_value( $object_id, $meta_key, $name, $value ) {
$meta_type = $this->get_meta_type();
if ( ! current_user_can( "edit_{$meta_type}_meta", $object_id, $meta_key ) ) {
return new WP_Error(
'rest_cannot_update',
/* translators: %s: Custom field key. */
sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
array(
'key' => $name,
'status' => rest_authorization_required_code(),
)
);
}
// Do the exact same check for a duplicate value as in update_metadata() to avoid update_metadata() returning false.
$old_value = get_metadata( $meta_type, $object_id, $meta_key );
$subtype = get_object_subtype( $meta_type, $object_id );
if ( is_array( $old_value ) && 1 === count( $old_value )
&& $this->is_meta_value_same_as_stored_value( $meta_key, $subtype, $old_value[0], $value )
) {
return true;
}
if ( ! update_metadata( $meta_type, $object_id, wp_slash( $meta_key ), wp_slash( $value ) ) ) {
return new WP_Error(
'rest_meta_database_error',
/* translators: %s: Custom field key. */
sprintf( __( 'Could not update the meta value of %s in database.' ), $meta_key ),
array(
'key' => $name,
'status' => WP_Http::INTERNAL_SERVER_ERROR,
)
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::is\_meta\_value\_same\_as\_stored\_value()](is_meta_value_same_as_stored_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Checks if the user provided value is equivalent to a stored value for the given meta key. |
| [get\_object\_subtype()](../../functions/get_object_subtype) wp-includes/meta.php | Returns the object subtype for a given object ID of a specific type. |
| [WP\_REST\_Meta\_Fields::get\_meta\_type()](get_meta_type) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the object meta type. |
| [get\_metadata()](../../functions/get_metadata) wp-includes/meta.php | Retrieves the value of a metadata field for the specified object type and ID. |
| [update\_metadata()](../../functions/update_metadata) wp-includes/meta.php | Updates metadata for the specified object. If no value already exists for the specified object ID and metadata key, the metadata will be added. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::update\_value()](update_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates meta values. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::get_rest_field_type(): string WP\_REST\_Meta\_Fields::get\_rest\_field\_type(): string
========================================================
Retrieves the object type for [register\_rest\_field()](../../functions/register_rest_field) .
string The REST field type, such as post type name, taxonomy name, `'comment'`, or `user`.
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
abstract protected function get_rest_field_type();
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::register\_field()](register_field) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Registers the meta field. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::get_empty_value_for_type( string $type ): mixed WP\_REST\_Meta\_Fields::get\_empty\_value\_for\_type( string $type ): mixed
===========================================================================
Gets the empty value for a schema type.
`$type` string Required The schema type. mixed
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
protected static function get_empty_value_for_type( $type ) {
switch ( $type ) {
case 'string':
return '';
case 'boolean':
return false;
case 'integer':
return 0;
case 'number':
return 0.0;
case 'array':
case 'object':
return array();
default:
return null;
}
}
```
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::get_meta_type(): string WP\_REST\_Meta\_Fields::get\_meta\_type(): string
=================================================
Retrieves the object meta type.
string One of `'post'`, `'comment'`, `'term'`, `'user'`, or anything else supported by `_get_meta_table()`.
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
abstract protected function get_meta_type();
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::is\_meta\_value\_same\_as\_stored\_value()](is_meta_value_same_as_stored_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Checks if the user provided value is equivalent to a stored value for the given meta key. |
| [WP\_REST\_Meta\_Fields::delete\_meta\_value()](delete_meta_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Deletes a meta value for an object. |
| [WP\_REST\_Meta\_Fields::update\_multi\_meta\_value()](update_multi_meta_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates multiple meta values for an object. |
| [WP\_REST\_Meta\_Fields::update\_meta\_value()](update_meta_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates a meta value for an object. |
| [WP\_REST\_Meta\_Fields::get\_registered\_fields()](get_registered_fields) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves all the registered meta fields. |
| [WP\_REST\_Meta\_Fields::update\_value()](update_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates meta values. |
| [WP\_REST\_Meta\_Fields::get\_value()](get_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the meta field value. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::get_field_schema(): array WP\_REST\_Meta\_Fields::get\_field\_schema(): array
===================================================
Retrieves the object’s meta schema, conforming to JSON Schema.
array Field schema data.
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
public function get_field_schema() {
$fields = $this->get_registered_fields();
$schema = array(
'description' => __( 'Meta fields.' ),
'type' => 'object',
'context' => array( 'view', 'edit' ),
'properties' => array(),
'arg_options' => array(
'sanitize_callback' => null,
'validate_callback' => array( $this, 'check_meta_is_array' ),
),
);
foreach ( $fields as $args ) {
$schema['properties'][ $args['name'] ] = $args['schema'];
}
return $schema;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::get\_registered\_fields()](get_registered_fields) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves all the registered meta fields. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::register\_field()](register_field) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Registers the meta field. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::update_value( array $meta, int $object_id ): null|WP_Error WP\_REST\_Meta\_Fields::update\_value( array $meta, int $object\_id ): null|WP\_Error
=====================================================================================
Updates meta values.
`$meta` array Required Array of meta parsed from the request. `$object_id` int Required Object ID to fetch meta for. null|[WP\_Error](../wp_error) Null on success, [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
public function update_value( $meta, $object_id ) {
$fields = $this->get_registered_fields();
foreach ( $fields as $meta_key => $args ) {
$name = $args['name'];
if ( ! array_key_exists( $name, $meta ) ) {
continue;
}
$value = $meta[ $name ];
/*
* A null value means reset the field, which is essentially deleting it
* from the database and then relying on the default value.
*
* Non-single meta can also be removed by passing an empty array.
*/
if ( is_null( $value ) || ( array() === $value && ! $args['single'] ) ) {
$args = $this->get_registered_fields()[ $meta_key ];
if ( $args['single'] ) {
$current = get_metadata( $this->get_meta_type(), $object_id, $meta_key, true );
if ( is_wp_error( rest_validate_value_from_schema( $current, $args['schema'] ) ) ) {
return new WP_Error(
'rest_invalid_stored_value',
/* translators: %s: Custom field key. */
sprintf( __( 'The %s property has an invalid stored value, and cannot be updated to null.' ), $name ),
array( 'status' => 500 )
);
}
}
$result = $this->delete_meta_value( $object_id, $meta_key, $name );
if ( is_wp_error( $result ) ) {
return $result;
}
continue;
}
if ( ! $args['single'] && is_array( $value ) && count( array_filter( $value, 'is_null' ) ) ) {
return new WP_Error(
'rest_invalid_stored_value',
/* translators: %s: Custom field key. */
sprintf( __( 'The %s property has an invalid stored value, and cannot be updated to null.' ), $name ),
array( 'status' => 500 )
);
}
$is_valid = rest_validate_value_from_schema( $value, $args['schema'], 'meta.' . $name );
if ( is_wp_error( $is_valid ) ) {
$is_valid->add_data( array( 'status' => 400 ) );
return $is_valid;
}
$value = rest_sanitize_value_from_schema( $value, $args['schema'] );
if ( $args['single'] ) {
$result = $this->update_meta_value( $object_id, $meta_key, $name, $value );
} else {
$result = $this->update_multi_meta_value( $object_id, $meta_key, $name, $value );
}
if ( is_wp_error( $result ) ) {
return $result;
}
}
return null;
}
```
| Uses | Description |
| --- | --- |
| [rest\_sanitize\_value\_from\_schema()](../../functions/rest_sanitize_value_from_schema) wp-includes/rest-api.php | Sanitize a value based on a schema. |
| [rest\_validate\_value\_from\_schema()](../../functions/rest_validate_value_from_schema) wp-includes/rest-api.php | Validate a value based on a schema. |
| [WP\_REST\_Meta\_Fields::get\_registered\_fields()](get_registered_fields) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves all the registered meta fields. |
| [WP\_REST\_Meta\_Fields::delete\_meta\_value()](delete_meta_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Deletes a meta value for an object. |
| [WP\_REST\_Meta\_Fields::update\_meta\_value()](update_meta_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates a meta value for an object. |
| [WP\_REST\_Meta\_Fields::update\_multi\_meta\_value()](update_multi_meta_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates multiple meta values for an object. |
| [WP\_REST\_Meta\_Fields::get\_meta\_type()](get_meta_type) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the object meta type. |
| [get\_metadata()](../../functions/get_metadata) wp-includes/meta.php | Retrieves the value of a metadata field for the specified object type and ID. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Meta_Fields::delete_meta_value( int $object_id, string $meta_key, string $name ): true|WP_Error WP\_REST\_Meta\_Fields::delete\_meta\_value( int $object\_id, string $meta\_key, string $name ): true|WP\_Error
===============================================================================================================
Deletes a meta value for an object.
`$object_id` int Required Object ID the field belongs to. `$meta_key` string Required Key for the field. `$name` string Required Name for the field that is exposed in the REST API. true|[WP\_Error](../wp_error) True if meta field is deleted, [WP\_Error](../wp_error) otherwise.
File: `wp-includes/rest-api/fields/class-wp-rest-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php/)
```
protected function delete_meta_value( $object_id, $meta_key, $name ) {
$meta_type = $this->get_meta_type();
if ( ! current_user_can( "delete_{$meta_type}_meta", $object_id, $meta_key ) ) {
return new WP_Error(
'rest_cannot_delete',
/* translators: %s: Custom field key. */
sprintf( __( 'Sorry, you are not allowed to edit the %s custom field.' ), $name ),
array(
'key' => $name,
'status' => rest_authorization_required_code(),
)
);
}
if ( null === get_metadata_raw( $meta_type, $object_id, wp_slash( $meta_key ) ) ) {
return true;
}
if ( ! delete_metadata( $meta_type, $object_id, wp_slash( $meta_key ) ) ) {
return new WP_Error(
'rest_meta_database_error',
__( 'Could not delete meta value from database.' ),
array(
'key' => $name,
'status' => WP_Http::INTERNAL_SERVER_ERROR,
)
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [get\_metadata\_raw()](../../functions/get_metadata_raw) wp-includes/meta.php | Retrieves raw metadata value for the specified object. |
| [WP\_REST\_Meta\_Fields::get\_meta\_type()](get_meta_type) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Retrieves the object meta type. |
| [delete\_metadata()](../../functions/delete_metadata) wp-includes/meta.php | Deletes metadata for the specified object. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Meta\_Fields::update\_value()](update_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates meta values. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress Requests_Utility_FilteredIterator::current(): string Requests\_Utility\_FilteredIterator::current(): string
======================================================
Get the current item’s value after filtering
string
File: `wp-includes/Requests/Utility/FilteredIterator.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/filterediterator.php/)
```
public function current() {
$value = parent::current();
if (is_callable($this->callback)) {
$value = call_user_func($this->callback, $value);
}
return $value;
}
```
wordpress Requests_Utility_FilteredIterator::__unserialize( $serialized ) Requests\_Utility\_FilteredIterator::\_\_unserialize( $serialized )
===================================================================
File: `wp-includes/Requests/Utility/FilteredIterator.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/filterediterator.php/)
```
public function __unserialize($serialized) {}
```
wordpress Requests_Utility_FilteredIterator::unserialize( $serialized ) Requests\_Utility\_FilteredIterator::unserialize( $serialized )
===============================================================
File: `wp-includes/Requests/Utility/FilteredIterator.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/filterediterator.php/)
```
public function unserialize($serialized) {}
```
wordpress Requests_Utility_FilteredIterator::__wakeup() Requests\_Utility\_FilteredIterator::\_\_wakeup()
=================================================
File: `wp-includes/Requests/Utility/FilteredIterator.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/filterediterator.php/)
```
public function __wakeup() {
unset($this->callback);
}
```
wordpress Requests_Utility_FilteredIterator::__construct( array $data, callable $callback ) Requests\_Utility\_FilteredIterator::\_\_construct( array $data, callable $callback )
=====================================================================================
Create a new iterator
`$data` array Required `$callback` callable Required Callback to be called on each value File: `wp-includes/Requests/Utility/FilteredIterator.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/filterediterator.php/)
```
public function __construct($data, $callback) {
parent::__construct($data);
$this->callback = $callback;
}
```
| Used By | Description |
| --- | --- |
| [Requests\_Response\_Headers::getIterator()](../requests_response_headers/getiterator) wp-includes/Requests/Response/Headers.php | Get an iterator for the data |
wordpress Walker::start_lvl( string $output, int $depth, array $args = array() ) Walker::start\_lvl( string $output, int $depth, array $args = array() )
=======================================================================
Starts the list before the elements are added.
The $args parameter holds additional values that may be used with the child class methods. This method is called at the start of the output list.
`$output` string Required Used to append additional content (passed by reference). `$depth` int Required Depth of the item. `$args` array Optional An array of additional arguments. Default: `array()`
This method is **abstract** and should be explicitly defined in the child class, as needed. Also note that $output is passed by reference, so any changes made to the variable within the following methods are automatically handled (no return, echo, or print needed).
This method “Start Level” is run when the walker reaches the **start** of a new “branch” in the tree structure. Generally, this method is used to add the opening tag of a *container* HTML element (such as <ol>, <ul>, or <div>) to $output.
File: `wp-includes/class-wp-walker.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-walker.php/)
```
public function start_lvl( &$output, $depth = 0, $args = array() ) {}
```
| Used By | Description |
| --- | --- |
| [Walker::display\_element()](../walker/display_element) wp-includes/class-wp-walker.php | Traverses elements to create list from elements. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Walker::start_el( string $output, object $data_object, int $depth, array $args = array(), int $current_object_id ) Walker::start\_el( string $output, object $data\_object, int $depth, array $args = array(), int $current\_object\_id )
======================================================================================================================
Starts the element output.
The $args parameter holds additional values that may be used with the child class methods. Also includes the element output.
`$output` string Required Used to append additional content (passed by reference). `$data_object` object Required The data object. `$depth` int Required Depth of the item. `$args` array Optional An array of additional arguments. Default: `array()`
`$current_object_id` int Optional ID of the current item. Default 0. This method is **abstract** and should be explicitly defined in the child class, as needed. Also note that $output is passed by reference, so any changes made to the variable within the following methods are automatically handled (no return, echo, or print needed).
“Start Element”. Generally, this method is used to add the opening HTML tag for a single tree item (such as <li>, <span>, or <a>) to $output.
File: `wp-includes/class-wp-walker.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-walker.php/)
```
public function start_el( &$output, $data_object, $depth = 0, $args = array(), $current_object_id = 0 ) {}
```
| Used By | Description |
| --- | --- |
| [Walker::display\_element()](../walker/display_element) wp-includes/class-wp-walker.php | Traverses elements to create list from elements. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$object` (a PHP reserved keyword) to `$data_object` for PHP 8 named parameter support. |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Walker::paged_walk( array $elements, int $max_depth, int $page_num, int $per_page, mixed $args ): string Walker::paged\_walk( array $elements, int $max\_depth, int $page\_num, int $per\_page, mixed $args ): string
============================================================================================================
Produces a page of nested elements.
Given an array of hierarchical elements, the maximum depth, a specific page number, and number of elements per page, this function first determines all top level root elements belonging to that page, then lists them and all of their children in hierarchical order.
$max\_depth = 0 means display all levels.
$max\_depth > 0 specifies the number of display levels.
`$elements` array Required An array of elements. `$max_depth` int Required The maximum hierarchical depth. `$page_num` int Required The specific page number, beginning with 1. `$per_page` int Required Number of elements per page. `$args` mixed Optional additional arguments. string XHTML of the specified page of elements.
This method can be used to initialize the [Walker](../walker) class. This function works like walk() but allows for pagination. $page\_num specifies the current page to render while $per\_page specifies the number of items to show per page. Any *additional* arguments passed to this method will be passed unchanged to the other methods.
File: `wp-includes/class-wp-walker.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-walker.php/)
```
public function paged_walk( $elements, $max_depth, $page_num, $per_page, ...$args ) {
if ( empty( $elements ) || $max_depth < -1 ) {
return '';
}
$output = '';
$parent_field = $this->db_fields['parent'];
$count = -1;
if ( -1 == $max_depth ) {
$total_top = count( $elements );
}
if ( $page_num < 1 || $per_page < 0 ) {
// No paging.
$paging = false;
$start = 0;
if ( -1 == $max_depth ) {
$end = $total_top;
}
$this->max_pages = 1;
} else {
$paging = true;
$start = ( (int) $page_num - 1 ) * (int) $per_page;
$end = $start + $per_page;
if ( -1 == $max_depth ) {
$this->max_pages = ceil( $total_top / $per_page );
}
}
// Flat display.
if ( -1 == $max_depth ) {
if ( ! empty( $args[0]['reverse_top_level'] ) ) {
$elements = array_reverse( $elements );
$oldstart = $start;
$start = $total_top - $end;
$end = $total_top - $oldstart;
}
$empty_array = array();
foreach ( $elements as $e ) {
$count++;
if ( $count < $start ) {
continue;
}
if ( $count >= $end ) {
break;
}
$this->display_element( $e, $empty_array, 1, 0, $args, $output );
}
return $output;
}
/*
* Separate elements into two buckets: top level and children elements.
* Children_elements is two dimensional array, e.g.
* $children_elements[10][] contains all sub-elements whose parent is 10.
*/
$top_level_elements = array();
$children_elements = array();
foreach ( $elements as $e ) {
if ( empty( $e->$parent_field ) ) {
$top_level_elements[] = $e;
} else {
$children_elements[ $e->$parent_field ][] = $e;
}
}
$total_top = count( $top_level_elements );
if ( $paging ) {
$this->max_pages = ceil( $total_top / $per_page );
} else {
$end = $total_top;
}
if ( ! empty( $args[0]['reverse_top_level'] ) ) {
$top_level_elements = array_reverse( $top_level_elements );
$oldstart = $start;
$start = $total_top - $end;
$end = $total_top - $oldstart;
}
if ( ! empty( $args[0]['reverse_children'] ) ) {
foreach ( $children_elements as $parent => $children ) {
$children_elements[ $parent ] = array_reverse( $children );
}
}
foreach ( $top_level_elements as $e ) {
$count++;
// For the last page, need to unset earlier children in order to keep track of orphans.
if ( $end >= $total_top && $count < $start ) {
$this->unset_children( $e, $children_elements );
}
if ( $count < $start ) {
continue;
}
if ( $count >= $end ) {
break;
}
$this->display_element( $e, $children_elements, $max_depth, 0, $args, $output );
}
if ( $end >= $total_top && count( $children_elements ) > 0 ) {
$empty_array = array();
foreach ( $children_elements as $orphans ) {
foreach ( $orphans as $op ) {
$this->display_element( $op, $empty_array, 1, 0, $args, $output );
}
}
}
return $output;
}
```
| Uses | Description |
| --- | --- |
| [Walker::display\_element()](display_element) wp-includes/class-wp-walker.php | Traverses elements to create list from elements. |
| [Walker::unset\_children()](unset_children) wp-includes/class-wp-walker.php | Unsets all the children for a given top level element. |
| Used By | Description |
| --- | --- |
| [wp\_list\_comments()](../../functions/wp_list_comments) wp-includes/comment-template.php | Displays a list of comments. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Formalized the existing `...$args` parameter by adding it to the function signature. |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress Walker::display_element( object $element, array $children_elements, int $max_depth, int $depth, array $args, string $output ) Walker::display\_element( object $element, array $children\_elements, int $max\_depth, int $depth, array $args, string $output )
================================================================================================================================
Traverses elements to create list from elements.
Display one element if the element doesn’t have any children otherwise, display the element and its children. Will only traverse up to the max depth and no ignore elements under that depth. It is possible to set the max depth to include all depths, see walk() method.
This method should not be called directly, use the walk() method instead.
`$element` object Required Data object. `$children_elements` array Required List of elements to continue traversing (passed by reference). `$max_depth` int Required Max depth to traverse. `$depth` int Required Depth of current element. `$args` array Required An array of arguments. `$output` string Required Used to append additional content (passed by reference). File: `wp-includes/class-wp-walker.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-walker.php/)
```
public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
if ( ! $element ) {
return;
}
$id_field = $this->db_fields['id'];
$id = $element->$id_field;
// Display this element.
$this->has_children = ! empty( $children_elements[ $id ] );
if ( isset( $args[0] ) && is_array( $args[0] ) ) {
$args[0]['has_children'] = $this->has_children; // Back-compat.
}
$this->start_el( $output, $element, $depth, ...array_values( $args ) );
// Descend only when the depth is right and there are children for this element.
if ( ( 0 == $max_depth || $max_depth > $depth + 1 ) && isset( $children_elements[ $id ] ) ) {
foreach ( $children_elements[ $id ] as $child ) {
if ( ! isset( $newlevel ) ) {
$newlevel = true;
// Start the child delimiter.
$this->start_lvl( $output, $depth, ...array_values( $args ) );
}
$this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output );
}
unset( $children_elements[ $id ] );
}
if ( isset( $newlevel ) && $newlevel ) {
// End the child delimiter.
$this->end_lvl( $output, $depth, ...array_values( $args ) );
}
// End this element.
$this->end_el( $output, $element, $depth, ...array_values( $args ) );
}
```
| Uses | Description |
| --- | --- |
| [Walker::start\_el()](start_el) wp-includes/class-wp-walker.php | Starts the element output. |
| [Walker::start\_lvl()](start_lvl) wp-includes/class-wp-walker.php | Starts the list before the elements are added. |
| [Walker::display\_element()](display_element) wp-includes/class-wp-walker.php | Traverses elements to create list from elements. |
| [Walker::end\_lvl()](end_lvl) wp-includes/class-wp-walker.php | Ends the list of after the elements are added. |
| [Walker::end\_el()](end_el) wp-includes/class-wp-walker.php | Ends the element output, if needed. |
| Used By | Description |
| --- | --- |
| [Walker::display\_element()](display_element) wp-includes/class-wp-walker.php | Traverses elements to create list from elements. |
| [Walker::walk()](walk) wp-includes/class-wp-walker.php | Displays array of elements hierarchically. |
| [Walker::paged\_walk()](paged_walk) wp-includes/class-wp-walker.php | Produces a page of nested elements. |
| [Walker\_Comment::display\_element()](../walker_comment/display_element) wp-includes/class-walker-comment.php | Traverses elements to create list from elements. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress Walker::end_lvl( string $output, int $depth, array $args = array() ) Walker::end\_lvl( string $output, int $depth, array $args = array() )
=====================================================================
Ends the list of after the elements are added.
The $args parameter holds additional values that may be used with the child class methods. This method finishes the list at the end of output of the elements.
`$output` string Required Used to append additional content (passed by reference). `$depth` int Required Depth of the item. `$args` array Optional An array of additional arguments. Default: `array()`
This method is **abstract** and should be explicitly defined in the child class, as needed. Also note that $output is passed by reference, so any changes made to the variable within the following methods are automatically handled (no return, echo, or print needed).
This method “End Level” is run when the walker reaches the **end** of a “branch” in the tree structure. Generally, this method is used to add the closing tag of a *container* HTML element (such as </ol>, </ul>, or </div>) to $output.
File: `wp-includes/class-wp-walker.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-walker.php/)
```
public function end_lvl( &$output, $depth = 0, $args = array() ) {}
```
| Used By | Description |
| --- | --- |
| [Walker::display\_element()](display_element) wp-includes/class-wp-walker.php | Traverses elements to create list from elements. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Walker::end_el( string $output, object $data_object, int $depth, array $args = array() ) Walker::end\_el( string $output, object $data\_object, int $depth, array $args = array() )
==========================================================================================
Ends the element output, if needed.
The $args parameter holds additional values that may be used with the child class methods.
`$output` string Required Used to append additional content (passed by reference). `$data_object` object Required The data object. `$depth` int Required Depth of the item. `$args` array Optional An array of additional arguments. Default: `array()`
This method is **abstract** and should be explicitly defined in the child class, as needed. Also note that $output is passed by reference, so any changes made to the variable within the following methods are automatically handled (no return, echo, or print needed).
“End Element”. Generally, this method is used to add any closing HTML tag for a single tree item (such as </li>, </span>, or </a>) to $output. Note that elements are not ended until after all of their children have been added.
File: `wp-includes/class-wp-walker.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-walker.php/)
```
public function end_el( &$output, $data_object, $depth = 0, $args = array() ) {}
```
| Used By | Description |
| --- | --- |
| [Walker::display\_element()](display_element) wp-includes/class-wp-walker.php | Traverses elements to create list from elements. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$object` (a PHP reserved keyword) to `$data_object` for PHP 8 named parameter support. |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Walker::walk( array $elements, int $max_depth, mixed $args ): string Walker::walk( array $elements, int $max\_depth, mixed $args ): string
=====================================================================
Displays array of elements hierarchically.
Does not assume any existing order of elements.
$max\_depth = -1 means flatly display every element.
$max\_depth = 0 means display all levels.
$max\_depth > 0 specifies the number of display levels.
`$elements` array Required An array of elements. `$max_depth` int Required The maximum hierarchical depth. `$args` mixed Optional additional arguments. string The hierarchical item output.
This method can be used to initialize the [Walker](../walker) class. It takes an array of elements ordered so that children occur below their parents. The $max\_depth parameter is an integer that specifies how deep into the tree structure the walker should render. By default, the `$max_depth` argument uses `0`, which will render every item in every branch, with no depth limit. You can also specify **-1** to render all objects as a “flattened” single-dimensional list. Any other number will limit the depth that [Walker](../walker) will render in any branch. Any *additional* arguments passed to this method will be passed unchanged to the other methods.
File: `wp-includes/class-wp-walker.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-walker.php/)
```
public function walk( $elements, $max_depth, ...$args ) {
$output = '';
// Invalid parameter or nothing to walk.
if ( $max_depth < -1 || empty( $elements ) ) {
return $output;
}
$parent_field = $this->db_fields['parent'];
// Flat display.
if ( -1 == $max_depth ) {
$empty_array = array();
foreach ( $elements as $e ) {
$this->display_element( $e, $empty_array, 1, 0, $args, $output );
}
return $output;
}
/*
* Need to display in hierarchical order.
* Separate elements into two buckets: top level and children elements.
* Children_elements is two dimensional array. Example:
* Children_elements[10][] contains all sub-elements whose parent is 10.
*/
$top_level_elements = array();
$children_elements = array();
foreach ( $elements as $e ) {
if ( empty( $e->$parent_field ) ) {
$top_level_elements[] = $e;
} else {
$children_elements[ $e->$parent_field ][] = $e;
}
}
/*
* When none of the elements is top level.
* Assume the first one must be root of the sub elements.
*/
if ( empty( $top_level_elements ) ) {
$first = array_slice( $elements, 0, 1 );
$root = $first[0];
$top_level_elements = array();
$children_elements = array();
foreach ( $elements as $e ) {
if ( $root->$parent_field == $e->$parent_field ) {
$top_level_elements[] = $e;
} else {
$children_elements[ $e->$parent_field ][] = $e;
}
}
}
foreach ( $top_level_elements as $e ) {
$this->display_element( $e, $children_elements, $max_depth, 0, $args, $output );
}
/*
* If we are displaying all levels, and remaining children_elements is not empty,
* then we got orphans, which should be displayed regardless.
*/
if ( ( 0 == $max_depth ) && count( $children_elements ) > 0 ) {
$empty_array = array();
foreach ( $children_elements as $orphans ) {
foreach ( $orphans as $op ) {
$this->display_element( $op, $empty_array, 1, 0, $args, $output );
}
}
}
return $output;
}
```
| Uses | Description |
| --- | --- |
| [Walker::display\_element()](display_element) wp-includes/class-wp-walker.php | Traverses elements to create list from elements. |
| Used By | Description |
| --- | --- |
| [wp\_terms\_checklist()](../../functions/wp_terms_checklist) wp-admin/includes/template.php | Outputs an unordered list of checkbox input elements labelled with term names. |
| [walk\_category\_tree()](../../functions/walk_category_tree) wp-includes/category-template.php | Retrieves HTML list content for category list. |
| [walk\_category\_dropdown\_tree()](../../functions/walk_category_dropdown_tree) wp-includes/category-template.php | Retrieves HTML dropdown (select) content for category list. |
| [walk\_nav\_menu\_tree()](../../functions/walk_nav_menu_tree) wp-includes/nav-menu-template.php | Retrieves the HTML list content for nav menu items. |
| [walk\_page\_tree()](../../functions/walk_page_tree) wp-includes/post-template.php | Retrieves HTML list content for page list. |
| [walk\_page\_dropdown\_tree()](../../functions/walk_page_dropdown_tree) wp-includes/post-template.php | Retrieves HTML dropdown (select) content for page list. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Formalized the existing `...$args` parameter by adding it to the function signature. |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
| programming_docs |
wordpress Walker::unset_children( object $element, array $children_elements ) Walker::unset\_children( object $element, array $children\_elements )
=====================================================================
Unsets all the children for a given top level element.
`$element` object Required The top level element. `$children_elements` array Required The children elements. File: `wp-includes/class-wp-walker.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-walker.php/)
```
public function unset_children( $element, &$children_elements ) {
if ( ! $element || ! $children_elements ) {
return;
}
$id_field = $this->db_fields['id'];
$id = $element->$id_field;
if ( ! empty( $children_elements[ $id ] ) && is_array( $children_elements[ $id ] ) ) {
foreach ( (array) $children_elements[ $id ] as $child ) {
$this->unset_children( $child, $children_elements );
}
}
unset( $children_elements[ $id ] );
}
```
| Uses | Description |
| --- | --- |
| [Walker::unset\_children()](unset_children) wp-includes/class-wp-walker.php | Unsets all the children for a given top level element. |
| Used By | Description |
| --- | --- |
| [Walker::paged\_walk()](paged_walk) wp-includes/class-wp-walker.php | Produces a page of nested elements. |
| [Walker::unset\_children()](unset_children) wp-includes/class-wp-walker.php | Unsets all the children for a given top level element. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress Walker::get_number_of_root_elements( array $elements ): int Walker::get\_number\_of\_root\_elements( array $elements ): int
===============================================================
Calculates the total number of root elements.
`$elements` array Required Elements to list. int Number of root elements.
Counts the number of top-level items (no children or descendants) in the provided array, and returns that count.
File: `wp-includes/class-wp-walker.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-walker.php/)
```
public function get_number_of_root_elements( $elements ) {
$num = 0;
$parent_field = $this->db_fields['parent'];
foreach ( $elements as $e ) {
if ( empty( $e->$parent_field ) ) {
$num++;
}
}
return $num;
}
```
| Used By | Description |
| --- | --- |
| [get\_comment\_pages\_count()](../../functions/get_comment_pages_count) wp-includes/comment.php | Calculates the total number of comment pages. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_Media_List_Table::extra_tablenav( string $which ) WP\_Media\_List\_Table::extra\_tablenav( string $which )
========================================================
`$which` string Required File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
protected function extra_tablenav( $which ) {
if ( 'bar' !== $which ) {
return;
}
?>
<div class="actions">
<?php
if ( ! $this->is_trash ) {
$this->months_dropdown( 'attachment' );
}
/** This action is documented in wp-admin/includes/class-wp-posts-list-table.php */
do_action( 'restrict_manage_posts', $this->screen->post_type, $which );
submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
if ( $this->is_trash && $this->has_items()
&& current_user_can( 'edit_others_posts' )
) {
submit_button( __( 'Empty Trash' ), 'apply', 'delete_all', false );
}
?>
</div>
<?php
}
```
[do\_action( 'restrict\_manage\_posts', string $post\_type, string $which )](../../hooks/restrict_manage_posts)
Fires before the Filter button on the Posts and Pages list tables.
| Uses | Description |
| --- | --- |
| [submit\_button()](../../functions/submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [WP\_Media\_List\_Table::has\_items()](has_items) wp-admin/includes/class-wp-media-list-table.php | |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Media\_List\_Table::views()](views) wp-admin/includes/class-wp-media-list-table.php | Override parent views so we can use the filter bar display. |
wordpress WP_Media_List_Table::current_action(): string WP\_Media\_List\_Table::current\_action(): string
=================================================
string
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function current_action() {
if ( isset( $_REQUEST['found_post_id'] ) && isset( $_REQUEST['media'] ) ) {
return 'attach';
}
if ( isset( $_REQUEST['parent_post_id'] ) && isset( $_REQUEST['media'] ) ) {
return 'detach';
}
if ( isset( $_REQUEST['delete_all'] ) || isset( $_REQUEST['delete_all2'] ) ) {
return 'delete_all';
}
return parent::current_action();
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::current\_action()](../wp_list_table/current_action) wp-admin/includes/class-wp-list-table.php | Gets the current action selected from the bulk actions dropdown. |
wordpress WP_Media_List_Table::prepare_items() WP\_Media\_List\_Table::prepare\_items()
========================================
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function prepare_items() {
global $mode, $wp_query, $post_mime_types, $avail_post_mime_types;
$mode = empty( $_REQUEST['mode'] ) ? 'list' : $_REQUEST['mode'];
/*
* Exclude attachments scheduled for deletion in the next two hours
* if they are for zip packages for interrupted or failed updates.
* See File_Upload_Upgrader class.
*/
$not_in = array();
$crons = _get_cron_array();
if ( is_array( $crons ) ) {
foreach ( $crons as $cron ) {
if ( isset( $cron['upgrader_scheduled_cleanup'] ) ) {
$details = reset( $cron['upgrader_scheduled_cleanup'] );
if ( ! empty( $details['args'][0] ) ) {
$not_in[] = (int) $details['args'][0];
}
}
}
}
if ( ! empty( $_REQUEST['post__not_in'] ) && is_array( $_REQUEST['post__not_in'] ) ) {
$not_in = array_merge( array_values( $_REQUEST['post__not_in'] ), $not_in );
}
if ( ! empty( $not_in ) ) {
$_REQUEST['post__not_in'] = $not_in;
}
list( $post_mime_types, $avail_post_mime_types ) = wp_edit_attachments_query( $_REQUEST );
$this->is_trash = isset( $_REQUEST['attachment-filter'] ) && 'trash' === $_REQUEST['attachment-filter'];
$this->set_pagination_args(
array(
'total_items' => $wp_query->found_posts,
'total_pages' => $wp_query->max_num_pages,
'per_page' => $wp_query->query_vars['posts_per_page'],
)
);
update_post_parent_caches( $wp_query->posts );
}
```
| Uses | Description |
| --- | --- |
| [update\_post\_parent\_caches()](../../functions/update_post_parent_caches) wp-includes/post.php | Updates parent post caches for a list of post objects. |
| [wp\_edit\_attachments\_query()](../../functions/wp_edit_attachments_query) wp-admin/includes/post.php | Executes a query for attachments. An array of [WP\_Query](../wp_query) arguments can be passed in, which will override the arguments set by this function. |
| [\_get\_cron\_array()](../../functions/_get_cron_array) wp-includes/cron.php | Retrieve cron info array option. |
wordpress WP_Media_List_Table::column_title( WP_Post $post ) WP\_Media\_List\_Table::column\_title( WP\_Post $post )
=======================================================
Handles the title column output.
`$post` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function column_title( $post ) {
list( $mime ) = explode( '/', $post->post_mime_type );
$title = _draft_or_post_title();
$thumb = wp_get_attachment_image( $post->ID, array( 60, 60 ), true, array( 'alt' => '' ) );
$link_start = '';
$link_end = '';
if ( current_user_can( 'edit_post', $post->ID ) && ! $this->is_trash ) {
$link_start = sprintf(
'<a href="%s" aria-label="%s">',
get_edit_post_link( $post->ID ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( '“%s” (Edit)' ), $title ) )
);
$link_end = '</a>';
}
$class = $thumb ? ' class="has-media-icon"' : '';
?>
<strong<?php echo $class; ?>>
<?php
echo $link_start;
if ( $thumb ) :
?>
<span class="media-icon <?php echo sanitize_html_class( $mime . '-icon' ); ?>"><?php echo $thumb; ?></span>
<?php
endif;
echo $title . $link_end;
_media_states( $post );
?>
</strong>
<p class="filename">
<span class="screen-reader-text"><?php _e( 'File name:' ); ?> </span>
<?php
$file = get_attached_file( $post->ID );
echo esc_html( wp_basename( $file ) );
?>
</p>
<?php
}
```
| Uses | Description |
| --- | --- |
| [\_draft\_or\_post\_title()](../../functions/_draft_or_post_title) wp-admin/includes/template.php | Gets the post title. |
| [\_media\_states()](../../functions/_media_states) wp-admin/includes/template.php | Outputs the attachment media states as HTML. |
| [sanitize\_html\_class()](../../functions/sanitize_html_class) wp-includes/formatting.php | Sanitizes an HTML classname to ensure it only contains valid characters. |
| [get\_edit\_post\_link()](../../functions/get_edit_post_link) wp-includes/link-template.php | Retrieves the edit post link for post. |
| [wp\_get\_attachment\_image()](../../functions/wp_get_attachment_image) wp-includes/media.php | Gets an HTML img element representing an image attachment. |
| [get\_attached\_file()](../../functions/get_attached_file) wp-includes/post.php | Retrieves attached file path based on attachment ID. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Media_List_Table::ajax_user_can(): bool WP\_Media\_List\_Table::ajax\_user\_can(): bool
===============================================
bool
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function ajax_user_can() {
return current_user_can( 'upload_files' );
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
wordpress WP_Media_List_Table::display_rows() WP\_Media\_List\_Table::display\_rows()
=======================================
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function display_rows() {
global $post, $wp_query;
$post_ids = wp_list_pluck( $wp_query->posts, 'ID' );
reset( $wp_query->posts );
$this->comment_pending_count = get_pending_comments_num( $post_ids );
add_filter( 'the_title', 'esc_html' );
while ( have_posts() ) :
the_post();
if ( $this->is_trash && 'trash' !== $post->post_status
|| ! $this->is_trash && 'trash' === $post->post_status
) {
continue;
}
$post_owner = ( get_current_user_id() === (int) $post->post_author ) ? 'self' : 'other';
?>
<tr id="post-<?php echo $post->ID; ?>" class="<?php echo trim( ' author-' . $post_owner . ' status-' . $post->post_status ); ?>">
<?php $this->single_row_columns( $post ); ?>
</tr>
<?php
endwhile;
}
```
| Uses | Description |
| --- | --- |
| [get\_pending\_comments\_num()](../../functions/get_pending_comments_num) wp-admin/includes/comment.php | Gets the number of pending comments on a post or posts. |
| [have\_posts()](../../functions/have_posts) wp-includes/query.php | Determines whether current WordPress query has posts to loop over. |
| [the\_post()](../../functions/the_post) wp-includes/query.php | Iterate the post index in the loop. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
wordpress WP_Media_List_Table::column_author( WP_Post $post ) WP\_Media\_List\_Table::column\_author( WP\_Post $post )
========================================================
Handles the author column output.
`$post` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function column_author( $post ) {
printf(
'<a href="%s">%s</a>',
esc_url( add_query_arg( array( 'author' => get_the_author_meta( 'ID' ) ), 'upload.php' ) ),
get_the_author()
);
}
```
| Uses | Description |
| --- | --- |
| [get\_the\_author\_meta()](../../functions/get_the_author_meta) wp-includes/author-template.php | Retrieves the requested data of the author of the current post. |
| [get\_the\_author()](../../functions/get_the_author) wp-includes/author-template.php | Retrieves the author of the current post. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Media_List_Table::no_items() WP\_Media\_List\_Table::no\_items()
===================================
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function no_items() {
if ( $this->is_trash ) {
_e( 'No media files found in Trash.' );
} else {
_e( 'No media files found.' );
}
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
wordpress WP_Media_List_Table::get_default_primary_column_name(): string WP\_Media\_List\_Table::get\_default\_primary\_column\_name(): string
=====================================================================
Gets the name of the default primary column.
string Name of the default primary column, in this case, `'title'`.
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
protected function get_default_primary_column_name() {
return 'title';
}
```
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Media_List_Table::handle_row_actions( WP_Post $item, string $column_name, string $primary ): string WP\_Media\_List\_Table::handle\_row\_actions( WP\_Post $item, string $column\_name, string $primary ): string
=============================================================================================================
Generates and displays row action links.
`$item` [WP\_Post](../wp_post) Required Attachment being acted upon. `$column_name` string Required Current column name. `$primary` string Required Primary column name. string Row actions output for media attachments, or an empty string if the current column is not the primary column.
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
protected function handle_row_actions( $item, $column_name, $primary ) {
if ( $primary !== $column_name ) {
return '';
}
$att_title = _draft_or_post_title();
$actions = $this->_get_row_actions(
$item, // WP_Post object for an attachment.
$att_title
);
return $this->row_actions( $actions );
}
```
| Uses | Description |
| --- | --- |
| [\_draft\_or\_post\_title()](../../functions/_draft_or_post_title) wp-admin/includes/template.php | Gets the post title. |
| [WP\_Media\_List\_Table::\_get\_row\_actions()](_get_row_actions) wp-admin/includes/class-wp-media-list-table.php | |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Media_List_Table::_get_row_actions( WP_Post $post, string $att_title ): array WP\_Media\_List\_Table::\_get\_row\_actions( WP\_Post $post, string $att\_title ): array
========================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
`$post` [WP\_Post](../wp_post) Required `$att_title` string Required array
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
private function _get_row_actions( $post, $att_title ) {
$actions = array();
if ( $this->detached ) {
if ( current_user_can( 'edit_post', $post->ID ) ) {
$actions['edit'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
get_edit_post_link( $post->ID ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Edit “%s”' ), $att_title ) ),
__( 'Edit' )
);
}
if ( current_user_can( 'delete_post', $post->ID ) ) {
if ( EMPTY_TRASH_DAYS && MEDIA_TRASH ) {
$actions['trash'] = sprintf(
'<a href="%s" class="submitdelete aria-button-if-js" aria-label="%s">%s</a>',
wp_nonce_url( "post.php?action=trash&post=$post->ID", 'trash-post_' . $post->ID ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Move “%s” to the Trash' ), $att_title ) ),
_x( 'Trash', 'verb' )
);
} else {
$delete_ays = ! MEDIA_TRASH ? " onclick='return showNotice.warn();'" : '';
$actions['delete'] = sprintf(
'<a href="%s" class="submitdelete aria-button-if-js"%s aria-label="%s">%s</a>',
wp_nonce_url( "post.php?action=delete&post=$post->ID", 'delete-post_' . $post->ID ),
$delete_ays,
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Delete “%s” permanently' ), $att_title ) ),
__( 'Delete Permanently' )
);
}
}
$actions['view'] = sprintf(
'<a href="%s" aria-label="%s" rel="bookmark">%s</a>',
get_permalink( $post->ID ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'View “%s”' ), $att_title ) ),
__( 'View' )
);
if ( current_user_can( 'edit_post', $post->ID ) ) {
$actions['attach'] = sprintf(
'<a href="#the-list" onclick="findPosts.open( \'media[]\', \'%s\' ); return false;" class="hide-if-no-js aria-button-if-js" aria-label="%s">%s</a>',
$post->ID,
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Attach “%s” to existing content' ), $att_title ) ),
__( 'Attach' )
);
}
} else {
if ( current_user_can( 'edit_post', $post->ID ) && ! $this->is_trash ) {
$actions['edit'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
get_edit_post_link( $post->ID ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Edit “%s”' ), $att_title ) ),
__( 'Edit' )
);
}
if ( current_user_can( 'delete_post', $post->ID ) ) {
if ( $this->is_trash ) {
$actions['untrash'] = sprintf(
'<a href="%s" class="submitdelete aria-button-if-js" aria-label="%s">%s</a>',
wp_nonce_url( "post.php?action=untrash&post=$post->ID", 'untrash-post_' . $post->ID ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Restore “%s” from the Trash' ), $att_title ) ),
__( 'Restore' )
);
} elseif ( EMPTY_TRASH_DAYS && MEDIA_TRASH ) {
$actions['trash'] = sprintf(
'<a href="%s" class="submitdelete aria-button-if-js" aria-label="%s">%s</a>',
wp_nonce_url( "post.php?action=trash&post=$post->ID", 'trash-post_' . $post->ID ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Move “%s” to the Trash' ), $att_title ) ),
_x( 'Trash', 'verb' )
);
}
if ( $this->is_trash || ! EMPTY_TRASH_DAYS || ! MEDIA_TRASH ) {
$delete_ays = ( ! $this->is_trash && ! MEDIA_TRASH ) ? " onclick='return showNotice.warn();'" : '';
$actions['delete'] = sprintf(
'<a href="%s" class="submitdelete aria-button-if-js"%s aria-label="%s">%s</a>',
wp_nonce_url( "post.php?action=delete&post=$post->ID", 'delete-post_' . $post->ID ),
$delete_ays,
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Delete “%s” permanently' ), $att_title ) ),
__( 'Delete Permanently' )
);
}
}
if ( ! $this->is_trash ) {
$actions['view'] = sprintf(
'<a href="%s" aria-label="%s" rel="bookmark">%s</a>',
get_permalink( $post->ID ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'View “%s”' ), $att_title ) ),
__( 'View' )
);
$actions['copy'] = sprintf(
'<span class="copy-to-clipboard-container"><button type="button" class="button-link copy-attachment-url media-library" data-clipboard-text="%s" aria-label="%s">%s</button><span class="success hidden" aria-hidden="true">%s</span></span>',
esc_url( wp_get_attachment_url( $post->ID ) ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Copy “%s” URL to clipboard' ), $att_title ) ),
__( 'Copy URL to clipboard' ),
__( 'Copied!' )
);
}
}
/**
* Filters the action links for each attachment in the Media list table.
*
* @since 2.8.0
*
* @param string[] $actions An array of action links for each attachment.
* Default 'Edit', 'Delete Permanently', 'View'.
* @param WP_Post $post WP_Post object for the current attachment.
* @param bool $detached Whether the list table contains media not attached
* to any posts. Default true.
*/
return apply_filters( 'media_row_actions', $actions, $post, $this->detached );
}
```
[apply\_filters( 'media\_row\_actions', string[] $actions, WP\_Post $post, bool $detached )](../../hooks/media_row_actions)
Filters the action links for each attachment in the Media list table.
| Uses | Description |
| --- | --- |
| [get\_edit\_post\_link()](../../functions/get_edit_post_link) wp-includes/link-template.php | Retrieves the edit post link for post. |
| [wp\_get\_attachment\_url()](../../functions/wp_get_attachment_url) wp-includes/post.php | Retrieves the URL for an attachment. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [wp\_nonce\_url()](../../functions/wp_nonce_url) wp-includes/functions.php | Retrieves URL with nonce added to URL query. |
| [get\_permalink()](../../functions/get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Media\_List\_Table::handle\_row\_actions()](handle_row_actions) wp-admin/includes/class-wp-media-list-table.php | Generates and displays row action links. |
| programming_docs |
wordpress WP_Media_List_Table::get_views(): array WP\_Media\_List\_Table::get\_views(): array
===========================================
array
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
protected function get_views() {
global $post_mime_types, $avail_post_mime_types;
$type_links = array();
$filter = empty( $_GET['attachment-filter'] ) ? '' : $_GET['attachment-filter'];
$type_links['all'] = sprintf(
'<option value=""%s>%s</option>',
selected( $filter, true, false ),
__( 'All media items' )
);
foreach ( $post_mime_types as $mime_type => $label ) {
if ( ! wp_match_mime_types( $mime_type, $avail_post_mime_types ) ) {
continue;
}
$selected = selected(
$filter && 0 === strpos( $filter, 'post_mime_type:' ) &&
wp_match_mime_types( $mime_type, str_replace( 'post_mime_type:', '', $filter ) ),
true,
false
);
$type_links[ $mime_type ] = sprintf(
'<option value="post_mime_type:%s"%s>%s</option>',
esc_attr( $mime_type ),
$selected,
$label[0]
);
}
$type_links['detached'] = '<option value="detached"' . ( $this->detached ? ' selected="selected"' : '' ) . '>' . _x( 'Unattached', 'media items' ) . '</option>';
$type_links['mine'] = sprintf(
'<option value="mine"%s>%s</option>',
selected( 'mine' === $filter, true, false ),
_x( 'Mine', 'media items' )
);
if ( $this->is_trash || ( defined( 'MEDIA_TRASH' ) && MEDIA_TRASH ) ) {
$type_links['trash'] = sprintf(
'<option value="trash"%s>%s</option>',
selected( 'trash' === $filter, true, false ),
_x( 'Trash', 'attachment filter' )
);
}
return $type_links;
}
```
| Uses | Description |
| --- | --- |
| [selected()](../../functions/selected) wp-includes/general-template.php | Outputs the HTML selected attribute. |
| [wp\_match\_mime\_types()](../../functions/wp_match_mime_types) wp-includes/post.php | Checks a MIME-Type against a list. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Used By | Description |
| --- | --- |
| [WP\_Media\_List\_Table::views()](views) wp-admin/includes/class-wp-media-list-table.php | Override parent views so we can use the filter bar display. |
wordpress WP_Media_List_Table::get_sortable_columns(): array WP\_Media\_List\_Table::get\_sortable\_columns(): array
=======================================================
array
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
protected function get_sortable_columns() {
return array(
'title' => 'title',
'author' => 'author',
'parent' => 'parent',
'comments' => 'comment_count',
'date' => array( 'date', true ),
);
}
```
wordpress WP_Media_List_Table::has_items(): bool WP\_Media\_List\_Table::has\_items(): bool
==========================================
bool
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function has_items() {
return have_posts();
}
```
| Uses | Description |
| --- | --- |
| [have\_posts()](../../functions/have_posts) wp-includes/query.php | Determines whether current WordPress query has posts to loop over. |
| Used By | Description |
| --- | --- |
| [WP\_Media\_List\_Table::extra\_tablenav()](extra_tablenav) wp-admin/includes/class-wp-media-list-table.php | |
wordpress WP_Media_List_Table::column_parent( WP_Post $post ) WP\_Media\_List\_Table::column\_parent( WP\_Post $post )
========================================================
Handles the parent column output.
`$post` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function column_parent( $post ) {
$user_can_edit = current_user_can( 'edit_post', $post->ID );
if ( $post->post_parent > 0 ) {
$parent = get_post( $post->post_parent );
} else {
$parent = false;
}
if ( $parent ) {
$title = _draft_or_post_title( $post->post_parent );
$parent_type = get_post_type_object( $parent->post_type );
if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $post->post_parent ) ) {
printf( '<strong><a href="%s">%s</a></strong>', get_edit_post_link( $post->post_parent ), $title );
} elseif ( $parent_type && current_user_can( 'read_post', $post->post_parent ) ) {
printf( '<strong>%s</strong>', $title );
} else {
_e( '(Private post)' );
}
if ( $user_can_edit ) :
$detach_url = add_query_arg(
array(
'parent_post_id' => $post->post_parent,
'media[]' => $post->ID,
'_wpnonce' => wp_create_nonce( 'bulk-' . $this->_args['plural'] ),
),
'upload.php'
);
printf(
'<br /><a href="%s" class="hide-if-no-js detach-from-parent" aria-label="%s">%s</a>',
$detach_url,
/* translators: %s: Title of the post the attachment is attached to. */
esc_attr( sprintf( __( 'Detach from “%s”' ), $title ) ),
__( 'Detach' )
);
endif;
} else {
_e( '(Unattached)' );
?>
<?php
if ( $user_can_edit ) {
$title = _draft_or_post_title( $post->post_parent );
printf(
'<br /><a href="#the-list" onclick="findPosts.open( \'media[]\', \'%s\' ); return false;" class="hide-if-no-js aria-button-if-js" aria-label="%s">%s</a>',
$post->ID,
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Attach “%s” to existing content' ), $title ) ),
__( 'Attach' )
);
}
}
}
```
| Uses | Description |
| --- | --- |
| [\_draft\_or\_post\_title()](../../functions/_draft_or_post_title) wp-admin/includes/template.php | Gets the post title. |
| [wp\_create\_nonce()](../../functions/wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| [get\_edit\_post\_link()](../../functions/get_edit_post_link) wp-includes/link-template.php | Retrieves the edit post link for post. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Media_List_Table::column_cb( WP_Post $item ) WP\_Media\_List\_Table::column\_cb( WP\_Post $item )
====================================================
Handles the checkbox column output.
`$item` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$post = $item;
if ( current_user_can( 'edit_post', $post->ID ) ) {
?>
<label class="screen-reader-text" for="cb-select-<?php echo $post->ID; ?>">
<?php
/* translators: %s: Attachment title. */
printf( __( 'Select %s' ), _draft_or_post_title() );
?>
</label>
<input type="checkbox" name="media[]" id="cb-select-<?php echo $post->ID; ?>" value="<?php echo $post->ID; ?>" />
<?php
}
}
```
| Uses | Description |
| --- | --- |
| [\_draft\_or\_post\_title()](../../functions/_draft_or_post_title) wp-admin/includes/template.php | Gets the post title. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Media_List_Table::get_columns(): array WP\_Media\_List\_Table::get\_columns(): array
=============================================
array
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function get_columns() {
$posts_columns = array();
$posts_columns['cb'] = '<input type="checkbox" />';
/* translators: Column name. */
$posts_columns['title'] = _x( 'File', 'column name' );
$posts_columns['author'] = __( 'Author' );
$taxonomies = get_taxonomies_for_attachments( 'objects' );
$taxonomies = wp_filter_object_list( $taxonomies, array( 'show_admin_column' => true ), 'and', 'name' );
/**
* Filters the taxonomy columns for attachments in the Media list table.
*
* @since 3.5.0
*
* @param string[] $taxonomies An array of registered taxonomy names to show for attachments.
* @param string $post_type The post type. Default 'attachment'.
*/
$taxonomies = apply_filters( 'manage_taxonomies_for_attachment_columns', $taxonomies, 'attachment' );
$taxonomies = array_filter( $taxonomies, 'taxonomy_exists' );
foreach ( $taxonomies as $taxonomy ) {
if ( 'category' === $taxonomy ) {
$column_key = 'categories';
} elseif ( 'post_tag' === $taxonomy ) {
$column_key = 'tags';
} else {
$column_key = 'taxonomy-' . $taxonomy;
}
$posts_columns[ $column_key ] = get_taxonomy( $taxonomy )->labels->name;
}
/* translators: Column name. */
if ( ! $this->detached ) {
$posts_columns['parent'] = _x( 'Uploaded to', 'column name' );
if ( post_type_supports( 'attachment', 'comments' ) ) {
$posts_columns['comments'] = sprintf(
'<span class="vers comment-grey-bubble" title="%1$s" aria-hidden="true"></span><span class="screen-reader-text">%2$s</span>',
esc_attr__( 'Comments' ),
__( 'Comments' )
);
}
}
/* translators: Column name. */
$posts_columns['date'] = _x( 'Date', 'column name' );
/**
* Filters the Media list table columns.
*
* @since 2.5.0
*
* @param string[] $posts_columns An array of columns displayed in the Media list table.
* @param bool $detached Whether the list table contains media not attached
* to any posts. Default true.
*/
return apply_filters( 'manage_media_columns', $posts_columns, $this->detached );
}
```
[apply\_filters( 'manage\_media\_columns', string[] $posts\_columns, bool $detached )](../../hooks/manage_media_columns)
Filters the Media list table columns.
[apply\_filters( 'manage\_taxonomies\_for\_attachment\_columns', string[] $taxonomies, string $post\_type )](../../hooks/manage_taxonomies_for_attachment_columns)
Filters the taxonomy columns for attachments in the Media list table.
| Uses | Description |
| --- | --- |
| [esc\_attr\_\_()](../../functions/esc_attr__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in an attribute. |
| [wp\_filter\_object\_list()](../../functions/wp_filter_object_list) wp-includes/functions.php | Filters a list of objects, based on a set of key => value arguments. |
| [get\_taxonomies\_for\_attachments()](../../functions/get_taxonomies_for_attachments) wp-includes/media.php | Retrieves all of the taxonomies that are registered for attachments. |
| [post\_type\_supports()](../../functions/post_type_supports) wp-includes/post.php | Checks a post type’s support for a given feature. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_taxonomy()](../../functions/get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
wordpress WP_Media_List_Table::get_bulk_actions(): array WP\_Media\_List\_Table::get\_bulk\_actions(): array
===================================================
array
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
protected function get_bulk_actions() {
$actions = array();
if ( MEDIA_TRASH ) {
if ( $this->is_trash ) {
$actions['untrash'] = __( 'Restore' );
$actions['delete'] = __( 'Delete permanently' );
} else {
$actions['trash'] = __( 'Move to Trash' );
}
} else {
$actions['delete'] = __( 'Delete permanently' );
}
if ( $this->detached ) {
$actions['attach'] = __( 'Attach' );
}
return $actions;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
wordpress WP_Media_List_Table::column_date( WP_Post $post ) WP\_Media\_List\_Table::column\_date( WP\_Post $post )
======================================================
Handles the date column output.
`$post` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function column_date( $post ) {
if ( '0000-00-00 00:00:00' === $post->post_date ) {
$h_time = __( 'Unpublished' );
} else {
$time = get_post_timestamp( $post );
$time_diff = time() - $time;
if ( $time && $time_diff > 0 && $time_diff < DAY_IN_SECONDS ) {
/* translators: %s: Human-readable time difference. */
$h_time = sprintf( __( '%s ago' ), human_time_diff( $time ) );
} else {
$h_time = get_the_time( __( 'Y/m/d' ), $post );
}
}
/**
* Filters the published time of an attachment displayed in the Media list table.
*
* @since 6.0.0
*
* @param string $h_time The published time.
* @param WP_Post $post Attachment object.
* @param string $column_name The column name.
*/
echo apply_filters( 'media_date_column_time', $h_time, $post, 'date' );
}
```
[apply\_filters( 'media\_date\_column\_time', string $h\_time, WP\_Post $post, string $column\_name )](../../hooks/media_date_column_time)
Filters the published time of an attachment displayed in the Media list table.
| Uses | Description |
| --- | --- |
| [get\_post\_timestamp()](../../functions/get_post_timestamp) wp-includes/general-template.php | Retrieves post published or modified time as a Unix timestamp. |
| [human\_time\_diff()](../../functions/human_time_diff) wp-includes/formatting.php | Determines the difference between two timestamps. |
| [get\_the\_time()](../../functions/get_the_time) wp-includes/general-template.php | Retrieves the time at which the post was written. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Media_List_Table::__construct( array $args = array() ) WP\_Media\_List\_Table::\_\_construct( array $args = array() )
==============================================================
Constructor.
* [WP\_List\_Table::\_\_construct()](../wp_list_table/__construct): for more information on default arguments.
`$args` array Optional An associative array of arguments. Default: `array()`
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function __construct( $args = array() ) {
$this->detached = ( isset( $_REQUEST['attachment-filter'] ) && 'detached' === $_REQUEST['attachment-filter'] );
$this->modes = array(
'list' => __( 'List view' ),
'grid' => __( 'Grid view' ),
);
parent::__construct(
array(
'plural' => 'media',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::\_\_construct()](../wp_list_table/__construct) wp-admin/includes/class-wp-list-table.php | Constructor. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Media_List_Table::column_comments( WP_Post $post ) WP\_Media\_List\_Table::column\_comments( WP\_Post $post )
==========================================================
Handles the comments column output.
`$post` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function column_comments( $post ) {
echo '<div class="post-com-count-wrapper">';
if ( isset( $this->comment_pending_count[ $post->ID ] ) ) {
$pending_comments = $this->comment_pending_count[ $post->ID ];
} else {
$pending_comments = get_pending_comments_num( $post->ID );
}
$this->comments_bubble( $post->ID, $pending_comments );
echo '</div>';
}
```
| Uses | Description |
| --- | --- |
| [get\_pending\_comments\_num()](../../functions/get_pending_comments_num) wp-admin/includes/comment.php | Gets the number of pending comments on a post or posts. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Media_List_Table::column_default( WP_Post $item, string $column_name ) WP\_Media\_List\_Table::column\_default( WP\_Post $item, string $column\_name )
===============================================================================
Handles output for the default column.
`$item` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. `$column_name` string Required Current column name. File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function column_default( $item, $column_name ) {
// Restores the more descriptive, specific name for use within this method.
$post = $item;
if ( 'categories' === $column_name ) {
$taxonomy = 'category';
} elseif ( 'tags' === $column_name ) {
$taxonomy = 'post_tag';
} elseif ( 0 === strpos( $column_name, 'taxonomy-' ) ) {
$taxonomy = substr( $column_name, 9 );
} else {
$taxonomy = false;
}
if ( $taxonomy ) {
$terms = get_the_terms( $post->ID, $taxonomy );
if ( is_array( $terms ) ) {
$output = array();
foreach ( $terms as $t ) {
$posts_in_term_qv = array();
$posts_in_term_qv['taxonomy'] = $taxonomy;
$posts_in_term_qv['term'] = $t->slug;
$output[] = sprintf(
'<a href="%s">%s</a>',
esc_url( add_query_arg( $posts_in_term_qv, 'upload.php' ) ),
esc_html( sanitize_term_field( 'name', $t->name, $t->term_id, $taxonomy, 'display' ) )
);
}
echo implode( wp_get_list_item_separator(), $output );
} else {
echo '<span aria-hidden="true">—</span><span class="screen-reader-text">' . get_taxonomy( $taxonomy )->labels->no_terms . '</span>';
}
return;
}
/**
* Fires for each custom column in the Media list table.
*
* Custom columns are registered using the {@see 'manage_media_columns'} filter.
*
* @since 2.5.0
*
* @param string $column_name Name of the custom column.
* @param int $post_id Attachment ID.
*/
do_action( 'manage_media_custom_column', $column_name, $post->ID );
}
```
[do\_action( 'manage\_media\_custom\_column', string $column\_name, int $post\_id )](../../hooks/manage_media_custom_column)
Fires for each custom column in the Media list table.
| Uses | Description |
| --- | --- |
| [wp\_get\_list\_item\_separator()](../../functions/wp_get_list_item_separator) wp-includes/l10n.php | Retrieves the list item separator based on the locale. |
| [get\_the\_terms()](../../functions/get_the_terms) wp-includes/category-template.php | Retrieves the terms of the taxonomy that are attached to the post. |
| [sanitize\_term\_field()](../../functions/sanitize_term_field) wp-includes/taxonomy.php | Sanitizes the field value in the term based on the context. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [get\_taxonomy()](../../functions/get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
| programming_docs |
wordpress WP_Media_List_Table::column_desc( WP_Post $post ) WP\_Media\_List\_Table::column\_desc( WP\_Post $post )
======================================================
Handles the description column output.
`$post` [WP\_Post](../wp_post) Required The current [WP\_Post](../wp_post) object. File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function column_desc( $post ) {
echo has_excerpt() ? $post->post_excerpt : '';
}
```
| Uses | Description |
| --- | --- |
| [has\_excerpt()](../../functions/has_excerpt) wp-includes/post-template.php | Determines whether the post has a custom excerpt. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Media_List_Table::views() WP\_Media\_List\_Table::views()
===============================
Override parent views so we can use the filter bar display.
File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/)
```
public function views() {
global $mode;
$views = $this->get_views();
$this->screen->render_screen_reader_content( 'heading_views' );
?>
<div class="wp-filter">
<div class="filter-items">
<?php $this->view_switcher( $mode ); ?>
<label for="attachment-filter" class="screen-reader-text"><?php _e( 'Filter by type' ); ?></label>
<select class="attachment-filters" name="attachment-filter" id="attachment-filter">
<?php
if ( ! empty( $views ) ) {
foreach ( $views as $class => $view ) {
echo "\t$view\n";
}
}
?>
</select>
<?php
$this->extra_tablenav( 'bar' );
/** This filter is documented in wp-admin/inclues/class-wp-list-table.php */
$views = apply_filters( "views_{$this->screen->id}", array() );
// Back compat for pre-4.0 view links.
if ( ! empty( $views ) ) {
echo '<ul class="filter-links">';
foreach ( $views as $class => $view ) {
echo "<li class='$class'>$view</li>";
}
echo '</ul>';
}
?>
</div>
<div class="search-form">
<label for="media-search-input" class="media-search-input-label"><?php esc_html_e( 'Search' ); ?></label>
<input type="search" id="media-search-input" class="search" name="s" value="<?php _admin_search_query(); ?>">
</div>
</div>
<?php
}
```
[apply\_filters( "views\_{$this->screen->id}", string[] $views )](../../hooks/views_this-screen-id)
Filters the list of available list table views.
| Uses | Description |
| --- | --- |
| [\_admin\_search\_query()](../../functions/_admin_search_query) wp-admin/includes/template.php | Displays the search query. |
| [WP\_Media\_List\_Table::get\_views()](get_views) wp-admin/includes/class-wp-media-list-table.php | |
| [WP\_Media\_List\_Table::extra\_tablenav()](extra_tablenav) wp-admin/includes/class-wp-media-list-table.php | |
| [esc\_html\_e()](../../functions/esc_html_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in HTML output. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
wordpress WP_Theme_JSON_Schema::rename_settings( array $settings, array $paths_to_rename ) WP\_Theme\_JSON\_Schema::rename\_settings( array $settings, array $paths\_to\_rename )
======================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Processes a settings array, renaming or moving properties.
`$settings` array Required Reference to settings either defaults or an individual block's. `$paths_to_rename` array Required Paths to rename. File: `wp-includes/class-wp-theme-json-schema.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme-json-schema.php/)
```
private static function rename_settings( &$settings, $paths_to_rename ) {
foreach ( $paths_to_rename as $original => $renamed ) {
$original_path = explode( '.', $original );
$renamed_path = explode( '.', $renamed );
$current_value = _wp_array_get( $settings, $original_path, null );
if ( null !== $current_value ) {
_wp_array_set( $settings, $renamed_path, $current_value );
self::unset_setting_by_path( $settings, $original_path );
}
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Schema::unset\_setting\_by\_path()](unset_setting_by_path) wp-includes/class-wp-theme-json-schema.php | Removes a property from within the provided settings by its path. |
| [\_wp\_array\_set()](../../functions/_wp_array_set) wp-includes/functions.php | Sets an array in depth based on a path of keys. |
| [\_wp\_array\_get()](../../functions/_wp_array_get) wp-includes/functions.php | Accesses an array in depth based on a path of keys. |
| Used By | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Schema::rename\_paths()](rename_paths) wp-includes/class-wp-theme-json-schema.php | Processes the settings subtree. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Theme_JSON_Schema::unset_setting_by_path( array $settings, array $path ): void WP\_Theme\_JSON\_Schema::unset\_setting\_by\_path( array $settings, array $path ): void
=======================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Removes a property from within the provided settings by its path.
`$settings` array Required Reference to the current settings array. `$path` array Required Path to the property to be removed. void
File: `wp-includes/class-wp-theme-json-schema.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme-json-schema.php/)
```
private static function unset_setting_by_path( &$settings, $path ) {
$tmp_settings = &$settings; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
$last_key = array_pop( $path );
foreach ( $path as $key ) {
$tmp_settings = &$tmp_settings[ $key ];
}
unset( $tmp_settings[ $last_key ] );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Schema::rename\_settings()](rename_settings) wp-includes/class-wp-theme-json-schema.php | Processes a settings array, renaming or moving properties. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Theme_JSON_Schema::migrate( array $theme_json ): array WP\_Theme\_JSON\_Schema::migrate( array $theme\_json ): array
=============================================================
Function that migrates a given theme.json structure to the last version.
`$theme_json` array Required The structure to migrate. array The structure in the last version.
File: `wp-includes/class-wp-theme-json-schema.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme-json-schema.php/)
```
public static function migrate( $theme_json ) {
if ( ! isset( $theme_json['version'] ) ) {
$theme_json = array(
'version' => WP_Theme_JSON::LATEST_SCHEMA,
);
}
if ( 1 === $theme_json['version'] ) {
$theme_json = self::migrate_v1_to_v2( $theme_json );
}
return $theme_json;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Schema::migrate\_v1\_to\_v2()](migrate_v1_to_v2) wp-includes/class-wp-theme-json-schema.php | Removes the custom prefixes for a few properties that were part of v1: |
| Used By | Description |
| --- | --- |
| [WP\_Theme\_JSON::remove\_insecure\_properties()](../wp_theme_json/remove_insecure_properties) wp-includes/class-wp-theme-json.php | Removes insecure data from theme.json. |
| [WP\_Theme\_JSON::\_\_construct()](../wp_theme_json/__construct) wp-includes/class-wp-theme-json.php | Constructor. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Theme_JSON_Schema::rename_paths( array $settings, array $paths_to_rename ): array WP\_Theme\_JSON\_Schema::rename\_paths( array $settings, array $paths\_to\_rename ): array
==========================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Processes the settings subtree.
`$settings` array Required Array to process. `$paths_to_rename` array Required Paths to rename. array The settings in the new format.
File: `wp-includes/class-wp-theme-json-schema.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme-json-schema.php/)
```
private static function rename_paths( $settings, $paths_to_rename ) {
$new_settings = $settings;
// Process any renamed/moved paths within default settings.
self::rename_settings( $new_settings, $paths_to_rename );
// Process individual block settings.
if ( isset( $new_settings['blocks'] ) && is_array( $new_settings['blocks'] ) ) {
foreach ( $new_settings['blocks'] as &$block_settings ) {
self::rename_settings( $block_settings, $paths_to_rename );
}
}
return $new_settings;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Schema::rename\_settings()](rename_settings) wp-includes/class-wp-theme-json-schema.php | Processes a settings array, renaming or moving properties. |
| Used By | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Schema::migrate\_v1\_to\_v2()](migrate_v1_to_v2) wp-includes/class-wp-theme-json-schema.php | Removes the custom prefixes for a few properties that were part of v1: |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Theme_JSON_Schema::migrate_v1_to_v2( array $old ): array WP\_Theme\_JSON\_Schema::migrate\_v1\_to\_v2( array $old ): array
=================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Removes the custom prefixes for a few properties that were part of v1:
‘border.customRadius’ => ‘border.radius’, ‘spacing.customMargin’ => ‘spacing.margin’, ‘spacing.customPadding’ => ‘spacing.padding’, ‘typography.customLineHeight’ => ‘typography.lineHeight’,
`$old` array Required Data to migrate. array Data without the custom prefixes.
File: `wp-includes/class-wp-theme-json-schema.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme-json-schema.php/)
```
private static function migrate_v1_to_v2( $old ) {
// Copy everything.
$new = $old;
// Overwrite the things that changed.
if ( isset( $old['settings'] ) ) {
$new['settings'] = self::rename_paths( $old['settings'], self::V1_TO_V2_RENAMED_PATHS );
}
// Set the new version.
$new['version'] = 2;
return $new;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Schema::rename\_paths()](rename_paths) wp-includes/class-wp-theme-json-schema.php | Processes the settings subtree. |
| Used By | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Schema::migrate()](migrate) wp-includes/class-wp-theme-json-schema.php | Function that migrates a given theme.json structure to the last version. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Image_Editor_GD::__destruct() WP\_Image\_Editor\_GD::\_\_destruct()
=====================================
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
public function __destruct() {
if ( $this->image ) {
// We don't need the original in memory anymore.
imagedestroy( $this->image );
}
}
```
wordpress WP_Image_Editor_GD::load(): true|WP_Error WP\_Image\_Editor\_GD::load(): true|WP\_Error
=============================================
Loads image from $this->file into new GD Resource.
true|[WP\_Error](../wp_error) True if loaded successfully; [WP\_Error](../wp_error) on failure.
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
public function load() {
if ( $this->image ) {
return true;
}
if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) ) {
return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file );
}
// Set artificially high because GD uses uncompressed images in memory.
wp_raise_memory_limit( 'image' );
$file_contents = @file_get_contents( $this->file );
if ( ! $file_contents ) {
return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file );
}
// WebP may not work with imagecreatefromstring().
if (
function_exists( 'imagecreatefromwebp' ) &&
( 'image/webp' === wp_get_image_mime( $this->file ) )
) {
$this->image = @imagecreatefromwebp( $this->file );
} else {
$this->image = @imagecreatefromstring( $file_contents );
}
if ( ! is_gd_image( $this->image ) ) {
return new WP_Error( 'invalid_image', __( 'File is not an image.' ), $this->file );
}
$size = wp_getimagesize( $this->file );
if ( ! $size ) {
return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file );
}
if ( function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' ) ) {
imagealphablending( $this->image, false );
imagesavealpha( $this->image, true );
}
$this->update_size( $size[0], $size[1] );
$this->mime_type = $size['mime'];
return $this->set_quality();
}
```
| Uses | Description |
| --- | --- |
| [wp\_getimagesize()](../../functions/wp_getimagesize) wp-includes/media.php | Allows PHP’s getimagesize() to be debuggable when necessary. |
| [is\_gd\_image()](../../functions/is_gd_image) wp-includes/media.php | Determines whether the value is an acceptable type for GD image functions. |
| [wp\_get\_image\_mime()](../../functions/wp_get_image_mime) wp-includes/functions.php | Returns the real mime type of an image file. |
| [wp\_raise\_memory\_limit()](../../functions/wp_raise_memory_limit) wp-includes/functions.php | Attempts to raise the PHP memory limit for memory intensive processes. |
| [WP\_Image\_Editor\_GD::update\_size()](update_size) wp-includes/class-wp-image-editor-gd.php | Sets or updates current image size. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_GD::supports_mime_type( string $mime_type ): bool WP\_Image\_Editor\_GD::supports\_mime\_type( string $mime\_type ): bool
=======================================================================
Checks to see if editor supports the mime-type specified.
`$mime_type` string Required bool
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
public static function supports_mime_type( $mime_type ) {
$image_types = imagetypes();
switch ( $mime_type ) {
case 'image/jpeg':
return ( $image_types & IMG_JPG ) != 0;
case 'image/png':
return ( $image_types & IMG_PNG ) != 0;
case 'image/gif':
return ( $image_types & IMG_GIF ) != 0;
case 'image/webp':
return ( $image_types & IMG_WEBP ) != 0;
}
return false;
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_GD::flip( bool $horz, bool $vert ): true|WP_Error WP\_Image\_Editor\_GD::flip( bool $horz, bool $vert ): true|WP\_Error
=====================================================================
Flips current image.
`$horz` bool Required Flip along Horizontal Axis. `$vert` bool Required Flip along Vertical Axis. true|[WP\_Error](../wp_error)
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
public function flip( $horz, $vert ) {
$w = $this->size['width'];
$h = $this->size['height'];
$dst = wp_imagecreatetruecolor( $w, $h );
if ( is_gd_image( $dst ) ) {
$sx = $vert ? ( $w - 1 ) : 0;
$sy = $horz ? ( $h - 1 ) : 0;
$sw = $vert ? -$w : $w;
$sh = $horz ? -$h : $h;
if ( imagecopyresampled( $dst, $this->image, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) {
imagedestroy( $this->image );
$this->image = $dst;
return true;
}
}
return new WP_Error( 'image_flip_error', __( 'Image flip failed.' ), $this->file );
}
```
| Uses | Description |
| --- | --- |
| [is\_gd\_image()](../../functions/is_gd_image) wp-includes/media.php | Determines whether the value is an acceptable type for GD image functions. |
| [wp\_imagecreatetruecolor()](../../functions/wp_imagecreatetruecolor) wp-includes/media.php | Creates new GD image resource with transparency support. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_GD::_save( resource|GdImage $image, string|null $filename = null, string|null $mime_type = null ): array|WP_Error WP\_Image\_Editor\_GD::\_save( resource|GdImage $image, string|null $filename = null, string|null $mime\_type = null ): array|WP\_Error
=======================================================================================================================================
`$image` resource|GdImage Required `$filename` string|null Optional Default: `null`
`$mime_type` string|null Optional Default: `null`
array|[WP\_Error](../wp_error) Array on success or [WP\_Error](../wp_error) if the file failed to save.
* `path`stringPath to the image file.
* `file`stringName of the image file.
* `width`intImage width.
* `height`intImage height.
* `mime-type`stringThe mime type of the image.
* `filesize`intFile size of the image.
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
protected function _save( $image, $filename = null, $mime_type = null ) {
list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
if ( ! $filename ) {
$filename = $this->generate_filename( null, null, $extension );
}
if ( 'image/gif' === $mime_type ) {
if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) ) {
return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
}
} elseif ( 'image/png' === $mime_type ) {
// Convert from full colors to index colors, like original PNG.
if ( function_exists( 'imageistruecolor' ) && ! imageistruecolor( $image ) ) {
imagetruecolortopalette( $image, false, imagecolorstotal( $image ) );
}
if ( ! $this->make_image( $filename, 'imagepng', array( $image, $filename ) ) ) {
return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
}
} elseif ( 'image/jpeg' === $mime_type ) {
if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, $this->get_quality() ) ) ) {
return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
}
} elseif ( 'image/webp' == $mime_type ) {
if ( ! function_exists( 'imagewebp' ) || ! $this->make_image( $filename, 'imagewebp', array( $image, $filename, $this->get_quality() ) ) ) {
return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
}
} else {
return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
}
// Set correct file permissions.
$stat = stat( dirname( $filename ) );
$perms = $stat['mode'] & 0000666; // Same permissions as parent folder, strip off the executable bits.
chmod( $filename, $perms );
return array(
'path' => $filename,
/**
* Filters the name of the saved image file.
*
* @since 2.6.0
*
* @param string $filename Name of the file.
*/
'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
'width' => $this->size['width'],
'height' => $this->size['height'],
'mime-type' => $mime_type,
'filesize' => wp_filesize( $filename ),
);
}
```
[apply\_filters( 'image\_make\_intermediate\_size', string $filename )](../../hooks/image_make_intermediate_size)
Filters the name of the saved image file.
| Uses | Description |
| --- | --- |
| [wp\_filesize()](../../functions/wp_filesize) wp-includes/functions.php | Wrapper for PHP filesize with filters and casting the result as an integer. |
| [WP\_Image\_Editor\_GD::make\_image()](make_image) wp-includes/class-wp-image-editor-gd.php | Either calls editor’s save function or handles file as a stream. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Image\_Editor\_GD::make\_subsize()](make_subsize) wp-includes/class-wp-image-editor-gd.php | Create an image sub-size and return the image meta data value for it. |
| [WP\_Image\_Editor\_GD::save()](save) wp-includes/class-wp-image-editor-gd.php | Saves current in-memory image to file. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | The `$filesize` value was added to the returned array. |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
| programming_docs |
wordpress WP_Image_Editor_GD::resize( int|null $max_w, int|null $max_h, bool $crop = false ): true|WP_Error WP\_Image\_Editor\_GD::resize( int|null $max\_w, int|null $max\_h, bool $crop = false ): true|WP\_Error
=======================================================================================================
Resizes current image.
Wraps `::_resize()` which returns a GD resource or GdImage instance.
At minimum, either a height or width must be provided. If one of the two is set to null, the resize will maintain aspect ratio according to the provided dimension.
`$max_w` int|null Required Image width. `$max_h` int|null Required Image height. `$crop` bool Optional Default: `false`
true|[WP\_Error](../wp_error)
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
public function resize( $max_w, $max_h, $crop = false ) {
if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) ) {
return true;
}
$resized = $this->_resize( $max_w, $max_h, $crop );
if ( is_gd_image( $resized ) ) {
imagedestroy( $this->image );
$this->image = $resized;
return true;
} elseif ( is_wp_error( $resized ) ) {
return $resized;
}
return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ), $this->file );
}
```
| Uses | Description |
| --- | --- |
| [is\_gd\_image()](../../functions/is_gd_image) wp-includes/media.php | Determines whether the value is an acceptable type for GD image functions. |
| [WP\_Image\_Editor\_GD::\_resize()](_resize) wp-includes/class-wp-image-editor-gd.php | |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_GD::stream( string $mime_type = null ): bool WP\_Image\_Editor\_GD::stream( string $mime\_type = null ): bool
================================================================
Returns stream of current image.
`$mime_type` string Optional The mime type of the image. Default: `null`
bool True on success, false on failure.
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
public function stream( $mime_type = null ) {
list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
switch ( $mime_type ) {
case 'image/png':
header( 'Content-Type: image/png' );
return imagepng( $this->image );
case 'image/gif':
header( 'Content-Type: image/gif' );
return imagegif( $this->image );
case 'image/webp':
if ( function_exists( 'imagewebp' ) ) {
header( 'Content-Type: image/webp' );
return imagewebp( $this->image, null, $this->get_quality() );
}
// Fall back to the default if webp isn't supported.
default:
header( 'Content-Type: image/jpeg' );
return imagejpeg( $this->image, null, $this->get_quality() );
}
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_GD::rotate( float $angle ): true|WP_Error WP\_Image\_Editor\_GD::rotate( float $angle ): true|WP\_Error
=============================================================
Rotates current image counter-clockwise by $angle.
Ported from image-edit.php
`$angle` float Required true|[WP\_Error](../wp_error)
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
public function rotate( $angle ) {
if ( function_exists( 'imagerotate' ) ) {
$transparency = imagecolorallocatealpha( $this->image, 255, 255, 255, 127 );
$rotated = imagerotate( $this->image, $angle, $transparency );
if ( is_gd_image( $rotated ) ) {
imagealphablending( $rotated, true );
imagesavealpha( $rotated, true );
imagedestroy( $this->image );
$this->image = $rotated;
$this->update_size();
return true;
}
}
return new WP_Error( 'image_rotate_error', __( 'Image rotate failed.' ), $this->file );
}
```
| Uses | Description |
| --- | --- |
| [is\_gd\_image()](../../functions/is_gd_image) wp-includes/media.php | Determines whether the value is an acceptable type for GD image functions. |
| [WP\_Image\_Editor\_GD::update\_size()](update_size) wp-includes/class-wp-image-editor-gd.php | Sets or updates current image size. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_GD::test( array $args = array() ): bool WP\_Image\_Editor\_GD::test( array $args = array() ): bool
==========================================================
Checks to see if current environment supports GD.
`$args` array Optional Default: `array()`
bool
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
public static function test( $args = array() ) {
if ( ! extension_loaded( 'gd' ) || ! function_exists( 'gd_info' ) ) {
return false;
}
// On some setups GD library does not provide imagerotate() - Ticket #11536.
if ( isset( $args['methods'] ) &&
in_array( 'rotate', $args['methods'], true ) &&
! function_exists( 'imagerotate' ) ) {
return false;
}
return true;
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_GD::save( string|null $destfilename = null, string|null $mime_type = null ): array|WP_Error WP\_Image\_Editor\_GD::save( string|null $destfilename = null, string|null $mime\_type = null ): array|WP\_Error
================================================================================================================
Saves current in-memory image to file.
`$destfilename` string|null Optional Destination filename. Default: `null`
`$mime_type` string|null Optional The mime-type. Default: `null`
array|[WP\_Error](../wp_error) Array on success or [WP\_Error](../wp_error) if the file failed to save.
* `path`stringPath to the image file.
* `file`stringName of the image file.
* `width`intImage width.
* `height`intImage height.
* `mime-type`stringThe mime type of the image.
* `filesize`intFile size of the image.
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
public function save( $destfilename = null, $mime_type = null ) {
$saved = $this->_save( $this->image, $destfilename, $mime_type );
if ( ! is_wp_error( $saved ) ) {
$this->file = $saved['path'];
$this->mime_type = $saved['mime-type'];
}
return $saved;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Image\_Editor\_GD::\_save()](_save) wp-includes/class-wp-image-editor-gd.php | |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | The `$filesize` value was added to the returned array. |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$filename` to `$destfilename` to match parent class for PHP 8 named parameter support. |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_GD::_resize( int $max_w, int $max_h, bool|array $crop = false ): resource|GdImage|WP_Error WP\_Image\_Editor\_GD::\_resize( int $max\_w, int $max\_h, bool|array $crop = false ): resource|GdImage|WP\_Error
=================================================================================================================
`$max_w` int Required `$max_h` int Required `$crop` bool|array Optional Default: `false`
resource|GdImage|[WP\_Error](../wp_error)
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
protected function _resize( $max_w, $max_h, $crop = false ) {
$dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
if ( ! $dims ) {
return new WP_Error( 'error_getting_dimensions', __( 'Could not calculate resized image dimensions' ), $this->file );
}
list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
$resized = wp_imagecreatetruecolor( $dst_w, $dst_h );
imagecopyresampled( $resized, $this->image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
if ( is_gd_image( $resized ) ) {
$this->update_size( $dst_w, $dst_h );
return $resized;
}
return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ), $this->file );
}
```
| Uses | Description |
| --- | --- |
| [is\_gd\_image()](../../functions/is_gd_image) wp-includes/media.php | Determines whether the value is an acceptable type for GD image functions. |
| [WP\_Image\_Editor\_GD::update\_size()](update_size) wp-includes/class-wp-image-editor-gd.php | Sets or updates current image size. |
| [wp\_imagecreatetruecolor()](../../functions/wp_imagecreatetruecolor) wp-includes/media.php | Creates new GD image resource with transparency support. |
| [image\_resize\_dimensions()](../../functions/image_resize_dimensions) wp-includes/media.php | Retrieves calculated resize dimensions for use in [WP\_Image\_Editor](../wp_image_editor). |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Image\_Editor\_GD::make\_subsize()](make_subsize) wp-includes/class-wp-image-editor-gd.php | Create an image sub-size and return the image meta data value for it. |
| [WP\_Image\_Editor\_GD::resize()](resize) wp-includes/class-wp-image-editor-gd.php | Resizes current image. |
wordpress WP_Image_Editor_GD::crop( int $src_x, int $src_y, int $src_w, int $src_h, int $dst_w = null, int $dst_h = null, bool $src_abs = false ): true|WP_Error WP\_Image\_Editor\_GD::crop( int $src\_x, int $src\_y, int $src\_w, int $src\_h, int $dst\_w = null, int $dst\_h = null, bool $src\_abs = false ): true|WP\_Error
=================================================================================================================================================================
Crops Image.
`$src_x` int Required The start x position to crop from. `$src_y` int Required The start y position to crop from. `$src_w` int Required The width to crop. `$src_h` int Required The height to crop. `$dst_w` int Optional The destination width. Default: `null`
`$dst_h` int Optional The destination height. Default: `null`
`$src_abs` bool Optional If the source crop points are absolute. Default: `false`
true|[WP\_Error](../wp_error)
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
// If destination width/height isn't specified,
// use same as width/height from source.
if ( ! $dst_w ) {
$dst_w = $src_w;
}
if ( ! $dst_h ) {
$dst_h = $src_h;
}
foreach ( array( $src_w, $src_h, $dst_w, $dst_h ) as $value ) {
if ( ! is_numeric( $value ) || (int) $value <= 0 ) {
return new WP_Error( 'image_crop_error', __( 'Image crop failed.' ), $this->file );
}
}
$dst = wp_imagecreatetruecolor( (int) $dst_w, (int) $dst_h );
if ( $src_abs ) {
$src_w -= $src_x;
$src_h -= $src_y;
}
if ( function_exists( 'imageantialias' ) ) {
imageantialias( $dst, true );
}
imagecopyresampled( $dst, $this->image, 0, 0, (int) $src_x, (int) $src_y, (int) $dst_w, (int) $dst_h, (int) $src_w, (int) $src_h );
if ( is_gd_image( $dst ) ) {
imagedestroy( $this->image );
$this->image = $dst;
$this->update_size();
return true;
}
return new WP_Error( 'image_crop_error', __( 'Image crop failed.' ), $this->file );
}
```
| Uses | Description |
| --- | --- |
| [is\_gd\_image()](../../functions/is_gd_image) wp-includes/media.php | Determines whether the value is an acceptable type for GD image functions. |
| [WP\_Image\_Editor\_GD::update\_size()](update_size) wp-includes/class-wp-image-editor-gd.php | Sets or updates current image size. |
| [wp\_imagecreatetruecolor()](../../functions/wp_imagecreatetruecolor) wp-includes/media.php | Creates new GD image resource with transparency support. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_GD::update_size( int $width = false, int $height = false ): true WP\_Image\_Editor\_GD::update\_size( int $width = false, int $height = false ): true
====================================================================================
Sets or updates current image size.
`$width` int Optional Default: `false`
`$height` int Optional Default: `false`
true
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
protected function update_size( $width = false, $height = false ) {
if ( ! $width ) {
$width = imagesx( $this->image );
}
if ( ! $height ) {
$height = imagesy( $this->image );
}
return parent::update_size( $width, $height );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Image\_Editor::update\_size()](../wp_image_editor/update_size) wp-includes/class-wp-image-editor.php | Sets current image size. |
| Used By | Description |
| --- | --- |
| [WP\_Image\_Editor\_GD::load()](load) wp-includes/class-wp-image-editor-gd.php | Loads image from $this->file into new GD Resource. |
| [WP\_Image\_Editor\_GD::\_resize()](_resize) wp-includes/class-wp-image-editor-gd.php | |
| [WP\_Image\_Editor\_GD::crop()](crop) wp-includes/class-wp-image-editor-gd.php | Crops Image. |
| [WP\_Image\_Editor\_GD::rotate()](rotate) wp-includes/class-wp-image-editor-gd.php | Rotates current image counter-clockwise by $angle. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_GD::multi_resize( array $sizes ): array WP\_Image\_Editor\_GD::multi\_resize( array $sizes ): array
===========================================================
Create multiple smaller images from a single source.
Attempts to create all sub-sizes and returns the meta data at the end. This may result in the server running out of resources. When it fails there may be few "orphaned" images left over as the meta data is never returned and saved.
As of 5.3.0 the preferred way to do this is with `make_subsize()`. It creates the new images one at a time and allows for the meta data to be saved after each new image is created.
`$sizes` array Required An array of image size data arrays.
Either a height or width must be provided.
If one of the two is set to null, the resize will maintain aspect ratio according to the source image.
* `...$0`array Array of height, width values, and whether to crop.
+ `width`intImage width. Optional if `$height` is specified.
+ `height`intImage height. Optional if `$width` is specified.
+ `crop`boolOptional. Whether to crop the image. Default false. array An array of resized images' metadata by size.
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
public function multi_resize( $sizes ) {
$metadata = array();
foreach ( $sizes as $size => $size_data ) {
$meta = $this->make_subsize( $size_data );
if ( ! is_wp_error( $meta ) ) {
$metadata[ $size ] = $meta;
}
}
return $metadata;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Image\_Editor\_GD::make\_subsize()](make_subsize) wp-includes/class-wp-image-editor-gd.php | Create an image sub-size and return the image meta data value for it. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_GD::make_image( string $filename, callable $callback, array $arguments ): bool WP\_Image\_Editor\_GD::make\_image( string $filename, callable $callback, array $arguments ): bool
==================================================================================================
Either calls editor’s save function or handles file as a stream.
`$filename` string Required `$callback` callable Required `$arguments` array Required bool
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
protected function make_image( $filename, $callback, $arguments ) {
if ( wp_is_stream( $filename ) ) {
$arguments[1] = null;
}
return parent::make_image( $filename, $callback, $arguments );
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_stream()](../../functions/wp_is_stream) wp-includes/functions.php | Tests if a given path is a stream URL |
| [WP\_Image\_Editor::make\_image()](../wp_image_editor/make_image) wp-includes/class-wp-image-editor.php | Either calls editor’s save function or handles file as a stream. |
| Used By | Description |
| --- | --- |
| [WP\_Image\_Editor\_GD::\_save()](_save) wp-includes/class-wp-image-editor-gd.php | |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_GD::make_subsize( array $size_data ): array|WP_Error WP\_Image\_Editor\_GD::make\_subsize( array $size\_data ): array|WP\_Error
==========================================================================
Create an image sub-size and return the image meta data value for it.
`$size_data` array Required Array of size data.
* `width`intThe maximum width in pixels.
* `height`intThe maximum height in pixels.
* `crop`boolWhether to crop the image to exact dimensions.
array|[WP\_Error](../wp_error) The image data array for inclusion in the `sizes` array in the image meta, [WP\_Error](../wp_error) object on error.
File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/)
```
public function make_subsize( $size_data ) {
if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
return new WP_Error( 'image_subsize_create_error', __( 'Cannot resize the image. Both width and height are not set.' ) );
}
$orig_size = $this->size;
if ( ! isset( $size_data['width'] ) ) {
$size_data['width'] = null;
}
if ( ! isset( $size_data['height'] ) ) {
$size_data['height'] = null;
}
if ( ! isset( $size_data['crop'] ) ) {
$size_data['crop'] = false;
}
$resized = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
if ( is_wp_error( $resized ) ) {
$saved = $resized;
} else {
$saved = $this->_save( $resized );
imagedestroy( $resized );
}
$this->size = $orig_size;
if ( ! is_wp_error( $saved ) ) {
unset( $saved['path'] );
}
return $saved;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Image\_Editor\_GD::\_save()](_save) wp-includes/class-wp-image-editor-gd.php | |
| [WP\_Image\_Editor\_GD::\_resize()](_resize) wp-includes/class-wp-image-editor-gd.php | |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Image\_Editor\_GD::multi\_resize()](multi_resize) wp-includes/class-wp-image-editor-gd.php | Create multiple smaller images from a single source. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
| programming_docs |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.