code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
wordpress WP_REST_Controller::get_fields_for_response( WP_REST_Request $request ): string[] WP\_REST\_Controller::get\_fields\_for\_response( WP\_REST\_Request $request ): string[]
========================================================================================
Gets an array of fields to be included on the response.
Included fields are based on item schema and `_fields=` request argument.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. string[] Fields to be included in the response.
File: `wp-includes/rest-api/endpoints/class-wp-rest-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
public function get_fields_for_response( $request ) {
$schema = $this->get_item_schema();
$properties = isset( $schema['properties'] ) ? $schema['properties'] : array();
$additional_fields = $this->get_additional_fields();
foreach ( $additional_fields as $field_name => $field_options ) {
// For back-compat, include any field with an empty schema
// because it won't be present in $this->get_item_schema().
if ( is_null( $field_options['schema'] ) ) {
$properties[ $field_name ] = $field_options;
}
}
// Exclude fields that specify a different context than the request context.
$context = $request['context'];
if ( $context ) {
foreach ( $properties as $name => $options ) {
if ( ! empty( $options['context'] ) && ! in_array( $context, $options['context'], true ) ) {
unset( $properties[ $name ] );
}
}
}
$fields = array_keys( $properties );
/*
* '_links' and '_embedded' are not typically part of the item schema,
* but they can be specified in '_fields', so they are added here as a
* convenience for checking with rest_is_field_included().
*/
$fields[] = '_links';
if ( $request->has_param( '_embed' ) ) {
$fields[] = '_embedded';
}
$fields = array_unique( $fields );
if ( ! isset( $request['_fields'] ) ) {
return $fields;
}
$requested_fields = wp_parse_list( $request['_fields'] );
if ( 0 === count( $requested_fields ) ) {
return $fields;
}
// Trim off outside whitespace from the comma delimited list.
$requested_fields = array_map( 'trim', $requested_fields );
// Always persist 'id', because it can be needed for add_additional_fields_to_object().
if ( in_array( 'id', $fields, true ) ) {
$requested_fields[] = 'id';
}
// Return the list of all requested fields which appear in the schema.
return array_reduce(
$requested_fields,
static function( $response_fields, $field ) use ( $fields ) {
if ( in_array( $field, $fields, true ) ) {
$response_fields[] = $field;
return $response_fields;
}
// Check for nested fields if $field is not a direct match.
$nested_fields = explode( '.', $field );
// A nested field is included so long as its top-level property
// is present in the schema.
if ( in_array( $nested_fields[0], $fields, true ) ) {
$response_fields[] = $field;
}
return $response_fields;
},
array()
);
}
```
| Uses | Description |
| --- | --- |
| [wp\_parse\_list()](../../functions/wp_parse_list) wp-includes/functions.php | Converts a comma- or space-separated list of scalar values to an array. |
| [WP\_REST\_Controller::get\_additional\_fields()](get_additional_fields) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves all of the registered additional fields for a given object-type. |
| [WP\_REST\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves the item’s schema, conforming to JSON Schema. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Controller::add\_additional\_fields\_to\_object()](add_additional_fields_to_object) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Adds the values from additional fields to a data object. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_REST_Controller::prepare_item_for_database( WP_REST_Request $request ): object|WP_Error WP\_REST\_Controller::prepare\_item\_for\_database( WP\_REST\_Request $request ): object|WP\_Error
==================================================================================================
Prepares one item for create or update operation.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. object|[WP\_Error](../wp_error) The prepared item, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
protected function prepare_item_for_database( $request ) {
return new WP_Error(
'invalid-method',
/* translators: %s: Method name. */
sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ),
array( 'status' => 405 )
);
}
```
| 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. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
==================================================================================================
Checks if a given request has access to get items.
`$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-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
public function get_items_permissions_check( $request ) {
return new WP_Error(
'invalid-method',
/* translators: %s: Method name. */
sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ),
array( 'status' => 405 )
);
}
```
| 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. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Controller::update_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Controller::update\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
====================================================================================================
Checks if a given request has access to update a specific item.
`$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-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
public function update_item_permissions_check( $request ) {
return new WP_Error(
'invalid-method',
/* translators: %s: Method name. */
sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ),
array( 'status' => 405 )
);
}
```
| 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. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Controller::get_object_type(): string WP\_REST\_Controller::get\_object\_type(): string
=================================================
Retrieves the object type this controller is responsible for managing.
string Object type for the controller.
File: `wp-includes/rest-api/endpoints/class-wp-rest-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
protected function get_object_type() {
$schema = $this->get_item_schema();
if ( ! $schema || ! isset( $schema['title'] ) ) {
return null;
}
return $schema['title'];
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves the item’s schema, conforming to JSON Schema. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Controller::add\_additional\_fields\_to\_object()](add_additional_fields_to_object) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Adds the values from additional fields to a data object. |
| [WP\_REST\_Controller::update\_additional\_fields\_for\_object()](update_additional_fields_for_object) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Updates the values of additional fields added to a data object. |
| [WP\_REST\_Controller::get\_additional\_fields()](get_additional_fields) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves all of the registered additional fields for a given object-type. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Controller::register_routes() WP\_REST\_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-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
public function register_routes() {
_doing_it_wrong(
'WP_REST_Controller::register_routes',
/* translators: %s: register_routes() */
sprintf( __( "Method '%s' must be overridden." ), __METHOD__ ),
'4.7.0'
);
}
```
| 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 |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Controller::get_context_param( array $args = array() ): array WP\_REST\_Controller::get\_context\_param( array $args = array() ): array
=========================================================================
Retrieves the magical context param.
Ensures consistent descriptions between endpoints, and populates enum from schema.
`$args` array Optional Additional arguments for context parameter. Default: `array()`
array Context parameter details.
File: `wp-includes/rest-api/endpoints/class-wp-rest-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
public function get_context_param( $args = array() ) {
$param_details = array(
'description' => __( 'Scope under which the request is made; determines fields present in response.' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_key',
'validate_callback' => 'rest_validate_request_arg',
);
$schema = $this->get_item_schema();
if ( empty( $schema['properties'] ) ) {
return array_merge( $param_details, $args );
}
$contexts = array();
foreach ( $schema['properties'] as $attributes ) {
if ( ! empty( $attributes['context'] ) ) {
$contexts = array_merge( $contexts, $attributes['context'] );
}
}
if ( ! empty( $contexts ) ) {
$param_details['enum'] = array_unique( $contexts );
rsort( $param_details['enum'] );
}
return array_merge( $param_details, $args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves the item’s schema, conforming to JSON Schema. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves the query params for the collections. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Controller::get_collection_params(): array WP\_REST\_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-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
public function get_collection_params() {
return array(
'context' => $this->get_context_param(),
'page' => array(
'description' => __( 'Current page of the collection.' ),
'type' => 'integer',
'default' => 1,
'sanitize_callback' => 'absint',
'validate_callback' => 'rest_validate_request_arg',
'minimum' => 1,
),
'per_page' => array(
'description' => __( 'Maximum number of items to be returned in result set.' ),
'type' => 'integer',
'default' => 10,
'minimum' => 1,
'maximum' => 100,
'sanitize_callback' => 'absint',
'validate_callback' => 'rest_validate_request_arg',
),
'search' => array(
'description' => __( 'Limit results to those matching a string.' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
),
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Controller::get\_context\_param()](get_context_param) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves the magical context param. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Pattern\_Directory\_Controller::get\_collection\_params()](../wp_rest_pattern_directory_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php | Retrieves the search parameters for the block pattern’s collection. |
| [WP\_REST\_Block\_Directory\_Controller::get\_collection\_params()](../wp_rest_block_directory_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-block-directory-controller.php | Retrieves the search params for the blocks collection. |
| [WP\_REST\_Plugins\_Controller::get\_collection\_params()](../wp_rest_plugins_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Retrieves the query params for the collections. |
| [WP\_REST\_Search\_Controller::get\_collection\_params()](../wp_rest_search_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-search-controller.php | Retrieves the query params for the search results collection. |
| [WP\_REST\_Users\_Controller::get\_collection\_params()](../wp_rest_users_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Retrieves the query params for collections. |
| [WP\_REST\_Revisions\_Controller::get\_collection\_params()](../wp_rest_revisions_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Retrieves the query params for collections. |
| [WP\_REST\_Terms\_Controller::get\_collection\_params()](../wp_rest_terms_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Retrieves the query params for collections. |
| [WP\_REST\_Posts\_Controller::get\_collection\_params()](../wp_rest_posts_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves the query params for the posts collection. |
| [WP\_REST\_Comments\_Controller::get\_collection\_params()](../wp_rest_comments_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Retrieves the query params for collections. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Controller::sanitize_slug( string $slug ): string WP\_REST\_Controller::sanitize\_slug( string $slug ): string
============================================================
Sanitizes the slug value.
* <https://github.com/WP-API/WP-API/issues/1585>
`$slug` string Required Slug value passed in request. string Sanitized value for the slug.
File: `wp-includes/rest-api/endpoints/class-wp-rest-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
public function sanitize_slug( $slug ) {
return sanitize_title( $slug );
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_title()](../../functions/sanitize_title) wp-includes/formatting.php | Sanitizes a string into a slug, which can be used in URLs or HTML attributes. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Controller::prepare_response_for_collection( WP_REST_Response $response ): array|mixed WP\_REST\_Controller::prepare\_response\_for\_collection( WP\_REST\_Response $response ): array|mixed
=====================================================================================================
Prepares a response for insertion into a collection.
`$response` [WP\_REST\_Response](../wp_rest_response) Required Response object. array|mixed Response data, ready for insertion into collection data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
public function prepare_response_for_collection( $response ) {
if ( ! ( $response instanceof WP_REST_Response ) ) {
return $response;
}
$data = (array) $response->get_data();
$server = rest_get_server();
$links = $server::get_compact_response_links( $response );
if ( ! empty( $links ) ) {
$data['_links'] = $links;
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [rest\_get\_server()](../../functions/rest_get_server) wp-includes/rest-api.php | Retrieves the current REST server instance. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Controller::get_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Controller::get\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=================================================================================================
Checks if a given request has access to get a specific item.
`$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-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
public function get_item_permissions_check( $request ) {
return new WP_Error(
'invalid-method',
/* translators: %s: Method name. */
sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ),
array( 'status' => 405 )
);
}
```
| 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. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Controller::create_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Controller::create\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
====================================================================================================
Checks if a given request has access to create items.
`$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-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
public function create_item_permissions_check( $request ) {
return new WP_Error(
'invalid-method',
/* translators: %s: Method name. */
sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ),
array( 'status' => 405 )
);
}
```
| 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. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Controller::delete_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Controller::delete\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
==============================================================================================
Deletes one item from the collection.
`$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-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
public function delete_item( $request ) {
return new WP_Error(
'invalid-method',
/* translators: %s: Method name. */
sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ),
array( 'status' => 405 )
);
}
```
| 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. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Controller::get_item_schema(): array WP\_REST\_Controller::get\_item\_schema(): array
================================================
Retrieves the item’s schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
public function get_item_schema() {
return $this->add_additional_fields_schema( array() );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Controller::add\_additional\_fields\_schema()](../wp_rest_controller/add_additional_fields_schema) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Adds the schema from additional fields to a schema array. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Controller::get\_fields\_for\_response()](../wp_rest_controller/get_fields_for_response) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Gets an array of fields to be included on the response. |
| [WP\_REST\_Controller::get\_object\_type()](../wp_rest_controller/get_object_type) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves the object type this controller is responsible for managing. |
| [WP\_REST\_Controller::get\_endpoint\_args\_for\_item\_schema()](../wp_rest_controller/get_endpoint_args_for_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves an array of endpoint arguments from the item schema for the controller. |
| [WP\_REST\_Controller::get\_public\_item\_schema()](../wp_rest_controller/get_public_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves the item’s schema for display / public consumption purposes. |
| [WP\_REST\_Controller::get\_context\_param()](../wp_rest_controller/get_context_param) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves the magical context param. |
| [WP\_REST\_Controller::filter\_response\_by\_context()](../wp_rest_controller/filter_response_by_context) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Filters a response based on the context defined in the schema. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Controller::get_public_item_schema(): array WP\_REST\_Controller::get\_public\_item\_schema(): array
========================================================
Retrieves the item’s schema for display / public consumption purposes.
array Public item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-controller.php/)
```
public function get_public_item_schema() {
$schema = $this->get_item_schema();
if ( ! empty( $schema['properties'] ) ) {
foreach ( $schema['properties'] as &$property ) {
unset( $property['arg_options'] );
}
}
return $schema;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves the item’s schema, conforming to JSON Schema. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Control::content_template() WP\_Customize\_Control::content\_template()
===========================================
An Underscore (JS) template for this control’s content (but not its container).
Class variables for this control class are available in the `data` JS object; export custom variables by overriding [WP\_Customize\_Control::to\_json()](to_json).
* [WP\_Customize\_Control::print\_template()](../wp_customize_control/print_template)
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
protected function content_template() {}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Control::print\_template()](print_template) wp-includes/class-wp-customize-control.php | Render the control’s JS template. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Control::get_content(): string WP\_Customize\_Control::get\_content(): string
==============================================
Get the control’s content for insertion into the Customizer pane.
string Contents of the control.
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
final public function get_content() {
ob_start();
$this->maybe_render();
return trim( ob_get_clean() );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::maybe\_render()](maybe_render) wp-includes/class-wp-customize-control.php | Check capabilities and render the control. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Control::to\_json()](to_json) wp-includes/class-wp-customize-control.php | Refresh the parameters passed to the JavaScript via JSON. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Control::link( string $setting_key = 'default' ) WP\_Customize\_Control::link( string $setting\_key = 'default' )
================================================================
Render the data link attribute for the control’s input element.
`$setting_key` string Optional Default: `'default'`
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
public function link( $setting_key = 'default' ) {
echo $this->get_link( $setting_key );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::get\_link()](get_link) wp-includes/class-wp-customize-control.php | Get the data link attribute for a setting. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Control::render\_content()](render_content) wp-includes/class-wp-customize-control.php | Render the control’s content. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Control::input_attrs() WP\_Customize\_Control::input\_attrs()
======================================
Render the custom attributes for the control’s input element.
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
public function input_attrs() {
foreach ( $this->input_attrs as $attr => $value ) {
echo $attr . '="' . esc_attr( $value ) . '" ';
}
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Control::render\_content()](render_content) wp-includes/class-wp-customize-control.php | Render the control’s content. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Control::to_json() WP\_Customize\_Control::to\_json()
==================================
Refresh the parameters passed to the JavaScript via JSON.
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
public function to_json() {
$this->json['settings'] = array();
foreach ( $this->settings as $key => $setting ) {
$this->json['settings'][ $key ] = $setting->id;
}
$this->json['type'] = $this->type;
$this->json['priority'] = $this->priority;
$this->json['active'] = $this->active();
$this->json['section'] = $this->section;
$this->json['content'] = $this->get_content();
$this->json['label'] = $this->label;
$this->json['description'] = $this->description;
$this->json['instanceNumber'] = $this->instance_number;
if ( 'dropdown-pages' === $this->type ) {
$this->json['allow_addition'] = $this->allow_addition;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::get\_content()](../wp_customize_control/get_content) wp-includes/class-wp-customize-control.php | Get the control’s content for insertion into the Customizer pane. |
| [WP\_Customize\_Control::active()](../wp_customize_control/active) wp-includes/class-wp-customize-control.php | Check whether control is active to current Customizer preview. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Location\_Control::to\_json()](../wp_customize_nav_menu_location_control/to_json) wp-includes/customize/class-wp-customize-nav-menu-location-control.php | Refresh the parameters passed to JavaScript via JSON. |
| [WP\_Customize\_Theme\_Control::to\_json()](../wp_customize_theme_control/to_json) wp-includes/customize/class-wp-customize-theme-control.php | Refresh the parameters passed to the JavaScript via JSON. |
| [WP\_Customize\_Media\_Control::to\_json()](../wp_customize_media_control/to_json) wp-includes/customize/class-wp-customize-media-control.php | Refresh the parameters passed to the JavaScript via JSON. |
| [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. |
| [WP\_Widget\_Form\_Customize\_Control::to\_json()](../wp_widget_form_customize_control/to_json) wp-includes/customize/class-wp-widget-form-customize-control.php | Gather control params for exporting to JavaScript. |
| [WP\_Widget\_Area\_Customize\_Control::to\_json()](../wp_widget_area_customize_control/to_json) wp-includes/customize/class-wp-widget-area-customize-control.php | Refreshes the parameters passed to the JavaScript via JSON. |
| [WP\_Customize\_Color\_Control::to\_json()](../wp_customize_color_control/to_json) wp-includes/customize/class-wp-customize-color-control.php | Refresh the parameters passed to the JavaScript via JSON. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Control::json(): array WP\_Customize\_Control::json(): array
=====================================
Get the data to export to the client via JSON.
array Array of parameters passed to the JavaScript.
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
public function json() {
$this->to_json();
return $this->json;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::to\_json()](to_json) wp-includes/class-wp-customize-control.php | Refresh the parameters passed to the JavaScript via JSON. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Code\_Editor\_Control::json()](../wp_customize_code_editor_control/json) wp-includes/customize/class-wp-customize-code-editor-control.php | Refresh the parameters passed to the JavaScript via JSON. |
| [WP\_Customize\_Date\_Time\_Control::json()](../wp_customize_date_time_control/json) wp-includes/customize/class-wp-customize-date-time-control.php | Export data to JS. |
| [WP\_Customize\_Nav\_Menu\_Item\_Control::json()](../wp_customize_nav_menu_item_control/json) wp-includes/customize/class-wp-customize-nav-menu-item-control.php | Return parameters for this control. |
| [WP\_Customize\_Nav\_Menu\_Control::json()](../wp_customize_nav_menu_control/json) wp-includes/customize/class-wp-customize-nav-menu-control.php | Return parameters for this control. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Control::active_callback(): true WP\_Customize\_Control::active\_callback(): true
================================================
Default callback used when invoking [WP\_Customize\_Control::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-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
public function active_callback() {
return true;
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Control::active(): bool WP\_Customize\_Control::active(): bool
======================================
Check whether control is active to current Customizer preview.
bool Whether the control is active to the current preview.
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
final public function active() {
$control = $this;
$active = call_user_func( $this->active_callback, $this );
/**
* Filters response of WP_Customize_Control::active().
*
* @since 4.0.0
*
* @param bool $active Whether the Customizer control is active.
* @param WP_Customize_Control $control WP_Customize_Control instance.
*/
$active = apply_filters( 'customize_control_active', $active, $control );
return $active;
}
```
[apply\_filters( 'customize\_control\_active', bool $active, WP\_Customize\_Control $control )](../../hooks/customize_control_active)
Filters response of [WP\_Customize\_Control::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\_Control::to\_json()](to_json) wp-includes/class-wp-customize-control.php | Refresh the parameters passed to the JavaScript via JSON. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Control::print_template() WP\_Customize\_Control::print\_template()
=========================================
Render the control’s JS template.
This function is only run for control types that have been registered with [WP\_Customize\_Manager::register\_control\_type()](../wp_customize_manager/register_control_type).
In the future, this will also print the template for the control’s container element and be override-able.
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
final public function print_template() {
?>
<script type="text/html" id="tmpl-customize-control-<?php echo esc_attr( $this->type ); ?>-content">
<?php $this->content_template(); ?>
</script>
<?php
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::content\_template()](content_template) wp-includes/class-wp-customize-control.php | An Underscore (JS) template for this control’s content (but not its container). |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Control::value( string $setting_key = 'default' ): mixed WP\_Customize\_Control::value( string $setting\_key = 'default' ): mixed
========================================================================
Fetch a setting’s value.
Grabs the main setting by default.
`$setting_key` string Optional Default: `'default'`
mixed The requested setting's value, if the setting exists.
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
final public function value( $setting_key = 'default' ) {
if ( isset( $this->settings[ $setting_key ] ) ) {
return $this->settings[ $setting_key ]->value();
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Control::render\_content()](render_content) wp-includes/class-wp-customize-control.php | Render the control’s content. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Control::__construct( WP_Customize_Manager $manager, string $id, array $args = array() ) WP\_Customize\_Control::\_\_construct( WP\_Customize\_Manager $manager, 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.
`$manager` [WP\_Customize\_Manager](../wp_customize_manager) Required Customizer bootstrap instance. `$id` string Required Control ID. `$args` array Optional Array of properties for the new Control object.
* `instance_number`intOrder in which this instance was created in relation to other instances.
* `manager`[WP\_Customize\_Manager](../wp_customize_manager)Customizer bootstrap instance.
* `id`stringControl ID.
* `settings`arrayAll settings tied to the control. If undefined, `$id` will be used.
* `setting`stringThe primary setting for the control (if there is one).
Default `'default'`.
* `capability`stringCapability required to use this control. Normally this is empty and the capability is derived from `$settings`.
* `priority`intOrder priority to load the control. Default 10.
* `section`stringSection the control belongs to.
* `label`stringLabel for the control.
* `description`stringDescription for the control.
* `choices`arrayList of choices for `'radio'` or `'select'` type controls, where values are the keys, and labels are the values.
* `input_attrs`arrayList of custom input attributes for control output, where attribute names are the keys and values are the values. Not used for `'checkbox'`, `'radio'`, `'select'`, `'textarea'`, or `'dropdown-pages'` control types.
* `allow_addition`boolShow UI for adding new content, currently only used for the dropdown-pages control. Default false.
* `json`arrayDeprecated. Use [WP\_Customize\_Control::json()](../wp_customize_control/json) instead.
* `type`stringControl type. Core controls include `'text'`, `'checkbox'`, `'textarea'`, `'radio'`, `'select'`, and `'dropdown-pages'`. Additional input types such as `'email'`, `'url'`, `'number'`, `'hidden'`, and `'date'` are supported implicitly. Default `'text'`.
* `active_callback`callableActive callback.
Default: `array()`
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.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;
// Process settings.
if ( ! isset( $this->settings ) ) {
$this->settings = $id;
}
$settings = array();
if ( is_array( $this->settings ) ) {
foreach ( $this->settings as $key => $setting ) {
$settings[ $key ] = $this->manager->get_setting( $setting );
}
} elseif ( is_string( $this->settings ) ) {
$this->setting = $this->manager->get_setting( $this->settings );
$settings['default'] = $this->setting;
}
$this->settings = $settings;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_New\_Menu\_Control::\_\_construct()](../wp_customize_new_menu_control/__construct) wp-includes/customize/class-wp-customize-new-menu-control.php | Constructor. |
| [WP\_Customize\_Nav\_Menu\_Item\_Control::\_\_construct()](../wp_customize_nav_menu_item_control/__construct) wp-includes/customize/class-wp-customize-nav-menu-item-control.php | Constructor. |
| [WP\_Customize\_Media\_Control::\_\_construct()](../wp_customize_media_control/__construct) wp-includes/customize/class-wp-customize-media-control.php | Constructor. |
| [WP\_Customize\_Manager::add\_control()](../wp_customize_manager/add_control) wp-includes/class-wp-customize-manager.php | Adds a customize control. |
| [WP\_Customize\_Color\_Control::\_\_construct()](../wp_customize_color_control/__construct) wp-includes/customize/class-wp-customize-color-control.php | Constructor. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Control::render() WP\_Customize\_Control::render()
================================
Renders the control wrapper and calls $this->render\_content() for the internals.
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
protected function render() {
$id = 'customize-control-' . str_replace( array( '[', ']' ), array( '-', '' ), $this->id );
$class = 'customize-control customize-control-' . $this->type;
printf( '<li id="%s" class="%s">', esc_attr( $id ), esc_attr( $class ) );
$this->render_content();
echo '</li>';
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::render\_content()](render_content) wp-includes/class-wp-customize-control.php | Render the control’s content. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Control::maybe\_render()](maybe_render) wp-includes/class-wp-customize-control.php | Check capabilities and render the control. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Control::check_capabilities(): bool WP\_Customize\_Control::check\_capabilities(): bool
===================================================
Checks if the user can use this control.
Returns false if the user cannot manipulate one of the associated settings, or if one of the associated settings does not exist. Also returns false if the associated section does not exist or if its capability check returns false.
bool False if theme doesn't support the control or user doesn't have the required permissions, otherwise true.
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
final public function check_capabilities() {
if ( ! empty( $this->capability ) && ! current_user_can( $this->capability ) ) {
return false;
}
foreach ( $this->settings as $setting ) {
if ( ! $setting || ! $setting->check_capabilities() ) {
return false;
}
}
$section = $this->manager->get_section( $this->section );
if ( isset( $section ) && ! $section->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. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Control::maybe\_render()](maybe_render) wp-includes/class-wp-customize-control.php | Check capabilities and render the control. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Control::render_content() WP\_Customize\_Control::render\_content()
=========================================
Render the control’s content.
Allows the content to be overridden without having to rewrite the wrapper in `$this::render()`.
Supports basic input types `text`, `checkbox`, `textarea`, `radio`, `select` and `dropdown-pages`.
Additional input types such as `email`, `url`, `number`, `hidden` and `date` are supported implicitly.
Control content can alternately be rendered in JS. See [WP\_Customize\_Control::print\_template()](print_template).
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
protected function render_content() {
$input_id = '_customize-input-' . $this->id;
$description_id = '_customize-description-' . $this->id;
$describedby_attr = ( ! empty( $this->description ) ) ? ' aria-describedby="' . esc_attr( $description_id ) . '" ' : '';
switch ( $this->type ) {
case 'checkbox':
?>
<span class="customize-inside-control-row">
<input
id="<?php echo esc_attr( $input_id ); ?>"
<?php echo $describedby_attr; ?>
type="checkbox"
value="<?php echo esc_attr( $this->value() ); ?>"
<?php $this->link(); ?>
<?php checked( $this->value() ); ?>
/>
<label for="<?php echo esc_attr( $input_id ); ?>"><?php echo esc_html( $this->label ); ?></label>
<?php if ( ! empty( $this->description ) ) : ?>
<span id="<?php echo esc_attr( $description_id ); ?>" class="description customize-control-description"><?php echo $this->description; ?></span>
<?php endif; ?>
</span>
<?php
break;
case 'radio':
if ( empty( $this->choices ) ) {
return;
}
$name = '_customize-radio-' . $this->id;
?>
<?php if ( ! empty( $this->label ) ) : ?>
<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
<?php endif; ?>
<?php if ( ! empty( $this->description ) ) : ?>
<span id="<?php echo esc_attr( $description_id ); ?>" class="description customize-control-description"><?php echo $this->description; ?></span>
<?php endif; ?>
<?php foreach ( $this->choices as $value => $label ) : ?>
<span class="customize-inside-control-row">
<input
id="<?php echo esc_attr( $input_id . '-radio-' . $value ); ?>"
type="radio"
<?php echo $describedby_attr; ?>
value="<?php echo esc_attr( $value ); ?>"
name="<?php echo esc_attr( $name ); ?>"
<?php $this->link(); ?>
<?php checked( $this->value(), $value ); ?>
/>
<label for="<?php echo esc_attr( $input_id . '-radio-' . $value ); ?>"><?php echo esc_html( $label ); ?></label>
</span>
<?php endforeach; ?>
<?php
break;
case 'select':
if ( empty( $this->choices ) ) {
return;
}
?>
<?php if ( ! empty( $this->label ) ) : ?>
<label for="<?php echo esc_attr( $input_id ); ?>" class="customize-control-title"><?php echo esc_html( $this->label ); ?></label>
<?php endif; ?>
<?php if ( ! empty( $this->description ) ) : ?>
<span id="<?php echo esc_attr( $description_id ); ?>" class="description customize-control-description"><?php echo $this->description; ?></span>
<?php endif; ?>
<select id="<?php echo esc_attr( $input_id ); ?>" <?php echo $describedby_attr; ?> <?php $this->link(); ?>>
<?php
foreach ( $this->choices as $value => $label ) {
echo '<option value="' . esc_attr( $value ) . '"' . selected( $this->value(), $value, false ) . '>' . $label . '</option>';
}
?>
</select>
<?php
break;
case 'textarea':
?>
<?php if ( ! empty( $this->label ) ) : ?>
<label for="<?php echo esc_attr( $input_id ); ?>" class="customize-control-title"><?php echo esc_html( $this->label ); ?></label>
<?php endif; ?>
<?php if ( ! empty( $this->description ) ) : ?>
<span id="<?php echo esc_attr( $description_id ); ?>" class="description customize-control-description"><?php echo $this->description; ?></span>
<?php endif; ?>
<textarea
id="<?php echo esc_attr( $input_id ); ?>"
rows="5"
<?php echo $describedby_attr; ?>
<?php $this->input_attrs(); ?>
<?php $this->link(); ?>
><?php echo esc_textarea( $this->value() ); ?></textarea>
<?php
break;
case 'dropdown-pages':
?>
<?php if ( ! empty( $this->label ) ) : ?>
<label for="<?php echo esc_attr( $input_id ); ?>" class="customize-control-title"><?php echo esc_html( $this->label ); ?></label>
<?php endif; ?>
<?php if ( ! empty( $this->description ) ) : ?>
<span id="<?php echo esc_attr( $description_id ); ?>" class="description customize-control-description"><?php echo $this->description; ?></span>
<?php endif; ?>
<?php
$dropdown_name = '_customize-dropdown-pages-' . $this->id;
$show_option_none = __( '— Select —' );
$option_none_value = '0';
$dropdown = wp_dropdown_pages(
array(
'name' => $dropdown_name,
'echo' => 0,
'show_option_none' => $show_option_none,
'option_none_value' => $option_none_value,
'selected' => $this->value(),
)
);
if ( empty( $dropdown ) ) {
$dropdown = sprintf( '<select id="%1$s" name="%1$s">', esc_attr( $dropdown_name ) );
$dropdown .= sprintf( '<option value="%1$s">%2$s</option>', esc_attr( $option_none_value ), esc_html( $show_option_none ) );
$dropdown .= '</select>';
}
// Hackily add in the data link parameter.
$dropdown = str_replace( '<select', '<select ' . $this->get_link() . ' id="' . esc_attr( $input_id ) . '" ' . $describedby_attr, $dropdown );
// Even more hacikly add auto-draft page stubs.
// @todo Eventually this should be removed in favor of the pages being injected into the underlying get_pages() call. See <https://github.com/xwp/wp-customize-posts/pull/250>.
$nav_menus_created_posts_setting = $this->manager->get_setting( 'nav_menus_created_posts' );
if ( $nav_menus_created_posts_setting && current_user_can( 'publish_pages' ) ) {
$auto_draft_page_options = '';
foreach ( $nav_menus_created_posts_setting->value() as $auto_draft_page_id ) {
$post = get_post( $auto_draft_page_id );
if ( $post && 'page' === $post->post_type ) {
$auto_draft_page_options .= sprintf( '<option value="%1$s">%2$s</option>', esc_attr( $post->ID ), esc_html( $post->post_title ) );
}
}
if ( $auto_draft_page_options ) {
$dropdown = str_replace( '</select>', $auto_draft_page_options . '</select>', $dropdown );
}
}
echo $dropdown;
?>
<?php if ( $this->allow_addition && current_user_can( 'publish_pages' ) && current_user_can( 'edit_theme_options' ) ) : // Currently tied to menus functionality. ?>
<button type="button" class="button-link add-new-toggle">
<?php
/* translators: %s: Add New Page label. */
printf( __( '+ %s' ), get_post_type_object( 'page' )->labels->add_new_item );
?>
</button>
<div class="new-content-item">
<label for="create-input-<?php echo esc_attr( $this->id ); ?>"><span class="screen-reader-text"><?php _e( 'New page title' ); ?></span></label>
<input type="text" id="create-input-<?php echo esc_attr( $this->id ); ?>" class="create-item-input" placeholder="<?php esc_attr_e( 'New page title…' ); ?>">
<button type="button" class="button add-content"><?php _e( 'Add' ); ?></button>
</div>
<?php endif; ?>
<?php
break;
default:
?>
<?php if ( ! empty( $this->label ) ) : ?>
<label for="<?php echo esc_attr( $input_id ); ?>" class="customize-control-title"><?php echo esc_html( $this->label ); ?></label>
<?php endif; ?>
<?php if ( ! empty( $this->description ) ) : ?>
<span id="<?php echo esc_attr( $description_id ); ?>" class="description customize-control-description"><?php echo $this->description; ?></span>
<?php endif; ?>
<input
id="<?php echo esc_attr( $input_id ); ?>"
type="<?php echo esc_attr( $this->type ); ?>"
<?php echo $describedby_attr; ?>
<?php $this->input_attrs(); ?>
<?php if ( ! isset( $this->input_attrs['value'] ) ) : ?>
value="<?php echo esc_attr( $this->value() ); ?>"
<?php endif; ?>
<?php $this->link(); ?>
/>
<?php
break;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::input\_attrs()](input_attrs) wp-includes/class-wp-customize-control.php | Render the custom attributes for the control’s input element. |
| [esc\_attr\_e()](../../functions/esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [esc\_textarea()](../../functions/esc_textarea) wp-includes/formatting.php | Escaping for textarea values. |
| [checked()](../../functions/checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [selected()](../../functions/selected) wp-includes/general-template.php | Outputs the HTML selected attribute. |
| [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\_Customize\_Control::link()](link) wp-includes/class-wp-customize-control.php | Render the data link attribute for the control’s input element. |
| [WP\_Customize\_Control::get\_link()](get_link) wp-includes/class-wp-customize-control.php | Get the data link attribute for a setting. |
| [WP\_Customize\_Control::value()](value) wp-includes/class-wp-customize-control.php | Fetch a setting’s value. |
| [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. |
| [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. |
| [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\_Customize\_Control::render()](render) wp-includes/class-wp-customize-control.php | Renders the control wrapper and calls $this->render\_content() for the internals. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Control::get_link( string $setting_key = 'default' ): string WP\_Customize\_Control::get\_link( string $setting\_key = 'default' ): string
=============================================================================
Get the data link attribute for a setting.
`$setting_key` string Optional Default: `'default'`
string Data link parameter, a `data-customize-setting-link` attribute if the `$setting_key` refers to a pre-registered setting, and a `data-customize-setting-key-link` attribute if the setting is not yet registered.
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
public function get_link( $setting_key = 'default' ) {
if ( isset( $this->settings[ $setting_key ] ) && $this->settings[ $setting_key ] instanceof WP_Customize_Setting ) {
return 'data-customize-setting-link="' . esc_attr( $this->settings[ $setting_key ]->id ) . '"';
} else {
return 'data-customize-setting-key-link="' . esc_attr( $setting_key ) . '"';
}
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Control::link()](link) wp-includes/class-wp-customize-control.php | Render the data link attribute for the control’s input element. |
| [WP\_Customize\_Control::render\_content()](render_content) wp-includes/class-wp-customize-control.php | Render the control’s content. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Return a `data-customize-setting-key-link` attribute if a setting is not registered for the supplied setting key. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Control::maybe_render() WP\_Customize\_Control::maybe\_render()
=======================================
Check capabilities and render the control.
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
final public function maybe_render() {
if ( ! $this->check_capabilities() ) {
return;
}
/**
* Fires just before the current Customizer control is rendered.
*
* @since 3.4.0
*
* @param WP_Customize_Control $control WP_Customize_Control instance.
*/
do_action( 'customize_render_control', $this );
/**
* Fires just before a specific Customizer control is rendered.
*
* The dynamic portion of the hook name, `$this->id`, refers to
* the control ID.
*
* @since 3.4.0
*
* @param WP_Customize_Control $control WP_Customize_Control instance.
*/
do_action( "customize_render_control_{$this->id}", $this );
$this->render();
}
```
[do\_action( 'customize\_render\_control', WP\_Customize\_Control $control )](../../hooks/customize_render_control)
Fires just before the current Customizer control is rendered.
[do\_action( "customize\_render\_control\_{$this->id}", WP\_Customize\_Control $control )](../../hooks/customize_render_control_this-id)
Fires just before a specific Customizer control is rendered.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::render()](render) wp-includes/class-wp-customize-control.php | Renders the control wrapper and calls $this->render\_content() for the internals. |
| [WP\_Customize\_Control::check\_capabilities()](check_capabilities) wp-includes/class-wp-customize-control.php | Checks if the user can use this control. |
| [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\_Control::get\_content()](get_content) wp-includes/class-wp-customize-control.php | Get the control’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_Customize_Control::enqueue() WP\_Customize\_Control::enqueue()
=================================
Enqueue control related scripts/styles.
File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/)
```
public function enqueue() {}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Privacy_Data_Removal_Requests_List_Table::column_email( WP_User_Request $item ): string WP\_Privacy\_Data\_Removal\_Requests\_List\_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/class-wp-privacy-data-removal-requests-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-data-removal-requests-list-table.php/)
```
public function column_email( $item ) {
$row_actions = array();
// Allow the administrator to "force remove" the personal data even if confirmation has not yet been received.
$status = $item->status;
$request_id = $item->ID;
$row_actions = array();
if ( 'request-confirmed' !== $status ) {
/** This filter is documented in wp-admin/includes/ajax-actions.php */
$erasers = apply_filters( 'wp_privacy_personal_data_erasers', array() );
$erasers_count = count( $erasers );
$nonce = wp_create_nonce( 'wp-privacy-erase-personal-data-' . $request_id );
$remove_data_markup = '<span class="remove-personal-data force-remove-personal-data" ' .
'data-erasers-count="' . esc_attr( $erasers_count ) . '" ' .
'data-request-id="' . esc_attr( $request_id ) . '" ' .
'data-nonce="' . esc_attr( $nonce ) .
'">';
$remove_data_markup .= '<span class="remove-personal-data-idle"><button type="button" class="button-link remove-personal-data-handle">' . __( 'Force erase personal data' ) . '</button></span>' .
'<span class="remove-personal-data-processing hidden">' . __( 'Erasing data...' ) . ' <span class="erasure-progress"></span></span>' .
'<span class="remove-personal-data-success hidden">' . __( 'Erasure completed.' ) . '</span>' .
'<span class="remove-personal-data-failed hidden">' . __( 'Force erasure has failed.' ) . ' <button type="button" class="button-link remove-personal-data-handle">' . __( 'Retry' ) . '</button></span>';
$remove_data_markup .= '</span>';
$row_actions['remove-data'] = $remove_data_markup;
}
if ( 'request-completed' !== $status ) {
$complete_request_markup = '<span>';
$complete_request_markup .= sprintf(
'<a href="%s" class="complete-request" aria-label="%s">%s</a>',
esc_url(
wp_nonce_url(
add_query_arg(
array(
'action' => 'complete',
'request_id' => array( $request_id ),
),
admin_url( 'erase-personal-data.php' )
),
'bulk-privacy_requests'
)
),
esc_attr(
sprintf(
/* translators: %s: Request email. */
__( 'Mark export request for “%s” as completed.' ),
$item->email
)
),
__( 'Complete request' )
);
$complete_request_markup .= '</span>';
}
if ( ! empty( $complete_request_markup ) ) {
$row_actions['complete-request'] = $complete_request_markup;
}
return sprintf( '<a href="%1$s">%2$s</a> %3$s', esc_url( 'mailto:' . $item->email ), $item->email, $this->row_actions( $row_actions ) );
}
```
[apply\_filters( 'wp\_privacy\_personal\_data\_erasers', array $args )](../../hooks/wp_privacy_personal_data_erasers)
Filters the array of personal data eraser callbacks.
| 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. |
| [\_\_()](../../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. |
| [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. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_Privacy_Data_Removal_Requests_List_Table::column_next_steps( WP_User_Request $item ) WP\_Privacy\_Data\_Removal\_Requests\_List\_Table::column\_next\_steps( WP\_User\_Request $item )
=================================================================================================
Next steps column.
`$item` [WP\_User\_Request](../wp_user_request) Required Item being shown. File: `wp-admin/includes/class-wp-privacy-data-removal-requests-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-data-removal-requests-list-table.php/)
```
public function column_next_steps( $item ) {
$status = $item->status;
switch ( $status ) {
case 'request-pending':
esc_html_e( 'Waiting for confirmation' );
break;
case 'request-confirmed':
/** This filter is documented in wp-admin/includes/ajax-actions.php */
$erasers = apply_filters( 'wp_privacy_personal_data_erasers', array() );
$erasers_count = count( $erasers );
$request_id = $item->ID;
$nonce = wp_create_nonce( 'wp-privacy-erase-personal-data-' . $request_id );
echo '<div class="remove-personal-data" ' .
'data-force-erase="1" ' .
'data-erasers-count="' . esc_attr( $erasers_count ) . '" ' .
'data-request-id="' . esc_attr( $request_id ) . '" ' .
'data-nonce="' . esc_attr( $nonce ) .
'">';
?>
<span class="remove-personal-data-idle"><button type="button" class="button-link remove-personal-data-handle"><?php _e( 'Erase personal data' ); ?></button></span>
<span class="remove-personal-data-processing hidden"><?php _e( 'Erasing data...' ); ?> <span class="erasure-progress"></span></span>
<span class="remove-personal-data-success success-message hidden" ><?php _e( 'Erasure completed.' ); ?></span>
<span class="remove-personal-data-failed hidden"><?php _e( 'Data erasure has failed.' ); ?> <button type="button" class="button-link remove-personal-data-handle"><?php _e( 'Retry' ); ?></button></span>
<?php
echo '</div>';
break;
case 'request-failed':
echo '<button type="submit" class="button-link" name="privacy_action_email_retry[' . $item->ID . ']" id="privacy_action_email_retry[' . $item->ID . ']">' . __( 'Retry' ) . '</button>';
break;
case 'request-completed':
echo '<a href="' . esc_url(
wp_nonce_url(
add_query_arg(
array(
'action' => 'delete',
'request_id' => array( $item->ID ),
),
admin_url( 'erase-personal-data.php' )
),
'bulk-privacy_requests'
)
) . '">' . esc_html__( 'Remove request' ) . '</a>';
break;
}
}
```
[apply\_filters( 'wp\_privacy\_personal\_data\_erasers', array $args )](../../hooks/wp_privacy_personal_data_erasers)
Filters the array of personal data eraser callbacks.
| Uses | Description |
| --- | --- |
| [esc\_html\_e()](../../functions/esc_html_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in HTML output. |
| [esc\_html\_\_()](../../functions/esc_html__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in HTML output. |
| [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. |
| [\_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. |
| [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. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress WP_oEmbed_Controller::get_item( WP_REST_Request $request ): array|WP_Error WP\_oEmbed\_Controller::get\_item( WP\_REST\_Request $request ): array|WP\_Error
================================================================================
Callback for the embed API endpoint.
Returns the JSON object for the post.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full data about the request. array|[WP\_Error](../wp_error) oEmbed response data or [WP\_Error](../wp_error) on failure.
File: `wp-includes/class-wp-oembed-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-oembed-controller.php/)
```
public function get_item( $request ) {
$post_id = url_to_postid( $request['url'] );
/**
* Filters the determined post ID.
*
* @since 4.4.0
*
* @param int $post_id The post ID.
* @param string $url The requested URL.
*/
$post_id = apply_filters( 'oembed_request_post_id', $post_id, $request['url'] );
$data = get_oembed_response_data( $post_id, $request['maxwidth'] );
if ( ! $data ) {
return new WP_Error( 'oembed_invalid_url', get_status_header_desc( 404 ), array( 'status' => 404 ) );
}
return $data;
}
```
[apply\_filters( 'oembed\_request\_post\_id', int $post\_id, string $url )](../../hooks/oembed_request_post_id)
Filters the determined post ID.
| Uses | Description |
| --- | --- |
| [get\_oembed\_response\_data()](../../functions/get_oembed_response_data) wp-includes/embed.php | Retrieves the oEmbed response data for a given post. |
| [get\_status\_header\_desc()](../../functions/get_status_header_desc) wp-includes/functions.php | Retrieves the description for the HTTP status. |
| [url\_to\_postid()](../../functions/url_to_postid) wp-includes/rewrite.php | Examines a URL and try to determine the post ID it represents. |
| [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_oEmbed_Controller::get_proxy_item( WP_REST_Request $request ): object|WP_Error WP\_oEmbed\_Controller::get\_proxy\_item( WP\_REST\_Request $request ): object|WP\_Error
========================================================================================
Callback for the proxy API endpoint.
Returns the JSON object for the proxied item.
* [WP\_oEmbed::get\_html()](../wp_oembed/get_html)
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full data about the request. object|[WP\_Error](../wp_error) oEmbed response data or [WP\_Error](../wp_error) on failure.
File: `wp-includes/class-wp-oembed-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-oembed-controller.php/)
```
public function get_proxy_item( $request ) {
global $wp_embed;
$args = $request->get_params();
// Serve oEmbed data from cache if set.
unset( $args['_wpnonce'] );
$cache_key = 'oembed_' . md5( serialize( $args ) );
$data = get_transient( $cache_key );
if ( ! empty( $data ) ) {
return $data;
}
$url = $request['url'];
unset( $args['url'] );
// Copy maxwidth/maxheight to width/height since WP_oEmbed::fetch() uses these arg names.
if ( isset( $args['maxwidth'] ) ) {
$args['width'] = $args['maxwidth'];
}
if ( isset( $args['maxheight'] ) ) {
$args['height'] = $args['maxheight'];
}
// Short-circuit process for URLs belonging to the current site.
$data = get_oembed_response_data_for_url( $url, $args );
if ( $data ) {
return $data;
}
$data = _wp_oembed_get_object()->get_data( $url, $args );
if ( false === $data ) {
// Try using a classic embed, instead.
/* @var WP_Embed $wp_embed */
$html = $wp_embed->get_embed_handler_html( $args, $url );
if ( $html ) {
global $wp_scripts;
// Check if any scripts were enqueued by the shortcode, and include them in the response.
$enqueued_scripts = array();
foreach ( $wp_scripts->queue as $script ) {
$enqueued_scripts[] = $wp_scripts->registered[ $script ]->src;
}
return (object) array(
'provider_name' => __( 'Embed Handler' ),
'html' => $html,
'scripts' => $enqueued_scripts,
);
}
return new WP_Error( 'oembed_invalid_url', get_status_header_desc( 404 ), array( 'status' => 404 ) );
}
/** This filter is documented in wp-includes/class-wp-oembed.php */
$data->html = apply_filters( 'oembed_result', _wp_oembed_get_object()->data2html( (object) $data, $url ), $url, $args );
/**
* Filters the oEmbed TTL value (time to live).
*
* Similar to the {@see 'oembed_ttl'} filter, but for the REST API
* oEmbed proxy endpoint.
*
* @since 4.8.0
*
* @param int $time Time to live (in seconds).
* @param string $url The attempted embed URL.
* @param array $args An array of embed request arguments.
*/
$ttl = apply_filters( 'rest_oembed_ttl', DAY_IN_SECONDS, $url, $args );
set_transient( $cache_key, $data, $ttl );
return $data;
}
```
[apply\_filters( 'oembed\_result', string|false $data, string $url, string|array $args )](../../hooks/oembed_result)
Filters the HTML returned by the oEmbed provider.
[apply\_filters( 'rest\_oembed\_ttl', int $time, string $url, array $args )](../../hooks/rest_oembed_ttl)
Filters the oEmbed TTL value (time to live).
| Uses | Description |
| --- | --- |
| [WP\_Embed::get\_embed\_handler\_html()](../wp_embed/get_embed_handler_html) wp-includes/class-wp-embed.php | Returns embed HTML for a given URL from embed handlers. |
| [get\_oembed\_response\_data\_for\_url()](../../functions/get_oembed_response_data_for_url) wp-includes/embed.php | Retrieves the oEmbed response data for a given URL. |
| [get\_status\_header\_desc()](../../functions/get_status_header_desc) wp-includes/functions.php | Retrieves the description for the HTTP status. |
| [\_wp\_oembed\_get\_object()](../../functions/_wp_oembed_get_object) wp-includes/embed.php | Returns the initialized [WP\_oEmbed](../wp_oembed) object. |
| [get\_transient()](../../functions/get_transient) wp-includes/option.php | Retrieves the value of a transient. |
| [set\_transient()](../../functions/set_transient) wp-includes/option.php | Sets/updates the value of a transient. |
| [\_\_()](../../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.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_oEmbed_Controller::register_routes() WP\_oEmbed\_Controller::register\_routes()
==========================================
Register the oEmbed REST API route.
File: `wp-includes/class-wp-oembed-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-oembed-controller.php/)
```
public function register_routes() {
/**
* Filters the maxwidth oEmbed parameter.
*
* @since 4.4.0
*
* @param int $maxwidth Maximum allowed width. Default 600.
*/
$maxwidth = apply_filters( 'oembed_default_width', 600 );
register_rest_route(
'oembed/1.0',
'/embed',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => '__return_true',
'args' => array(
'url' => array(
'description' => __( 'The URL of the resource for which to fetch oEmbed data.' ),
'required' => true,
'type' => 'string',
'format' => 'uri',
),
'format' => array(
'default' => 'json',
'sanitize_callback' => 'wp_oembed_ensure_format',
),
'maxwidth' => array(
'default' => $maxwidth,
'sanitize_callback' => 'absint',
),
),
),
)
);
register_rest_route(
'oembed/1.0',
'/proxy',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_proxy_item' ),
'permission_callback' => array( $this, 'get_proxy_item_permissions_check' ),
'args' => array(
'url' => array(
'description' => __( 'The URL of the resource for which to fetch oEmbed data.' ),
'required' => true,
'type' => 'string',
'format' => 'uri',
),
'format' => array(
'description' => __( 'The oEmbed format to use.' ),
'type' => 'string',
'default' => 'json',
'enum' => array(
'json',
'xml',
),
),
'maxwidth' => array(
'description' => __( 'The maximum width of the embed frame in pixels.' ),
'type' => 'integer',
'default' => $maxwidth,
'sanitize_callback' => 'absint',
),
'maxheight' => array(
'description' => __( 'The maximum height of the embed frame in pixels.' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
),
'discover' => array(
'description' => __( 'Whether to perform an oEmbed discovery request for unsanctioned providers.' ),
'type' => 'boolean',
'default' => true,
),
),
),
)
);
}
```
[apply\_filters( 'oembed\_default\_width', int $maxwidth )](../../hooks/oembed_default_width)
Filters the maxwidth oEmbed parameter.
| 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. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress WP_oEmbed_Controller::get_proxy_item_permissions_check(): true|WP_Error WP\_oEmbed\_Controller::get\_proxy\_item\_permissions\_check(): true|WP\_Error
==============================================================================
Checks if current user can make a proxy oEmbed request.
true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/class-wp-oembed-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-oembed-controller.php/)
```
public function get_proxy_item_permissions_check() {
if ( ! current_user_can( 'edit_posts' ) ) {
return new WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to make proxied oEmbed requests.' ), 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 |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Image_Editor_Imagick::thumbnail_image( int $dst_w, int $dst_h, string $filter_name = 'FILTER_TRIANGLE', bool $strip_meta = true ): void|WP_Error WP\_Image\_Editor\_Imagick::thumbnail\_image( int $dst\_w, int $dst\_h, string $filter\_name = 'FILTER\_TRIANGLE', bool $strip\_meta = true ): void|WP\_Error
=============================================================================================================================================================
Efficiently resize the current image
This is a WordPress specific implementation of Imagick::thumbnailImage(), which resizes an image to given dimensions and removes any associated profiles.
`$dst_w` int Required The destination width. `$dst_h` int Required The destination height. `$filter_name` string Optional The Imagick filter to use when resizing. Default `'FILTER_TRIANGLE'`. Default: `'FILTER_TRIANGLE'`
`$strip_meta` bool Optional Strip all profiles, excluding color profiles, from the image. Default: `true`
void|[WP\_Error](../wp_error)
File: `wp-includes/class-wp-image-editor-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
protected function thumbnail_image( $dst_w, $dst_h, $filter_name = 'FILTER_TRIANGLE', $strip_meta = true ) {
$allowed_filters = array(
'FILTER_POINT',
'FILTER_BOX',
'FILTER_TRIANGLE',
'FILTER_HERMITE',
'FILTER_HANNING',
'FILTER_HAMMING',
'FILTER_BLACKMAN',
'FILTER_GAUSSIAN',
'FILTER_QUADRATIC',
'FILTER_CUBIC',
'FILTER_CATROM',
'FILTER_MITCHELL',
'FILTER_LANCZOS',
'FILTER_BESSEL',
'FILTER_SINC',
);
/**
* Set the filter value if '$filter_name' name is in the allowed list and the related
* Imagick constant is defined or fall back to the default filter.
*/
if ( in_array( $filter_name, $allowed_filters, true ) && defined( 'Imagick::' . $filter_name ) ) {
$filter = constant( 'Imagick::' . $filter_name );
} else {
$filter = defined( 'Imagick::FILTER_TRIANGLE' ) ? Imagick::FILTER_TRIANGLE : false;
}
/**
* Filters whether to strip metadata from images when they're resized.
*
* This filter only applies when resizing using the Imagick editor since GD
* always strips profiles by default.
*
* @since 4.5.0
*
* @param bool $strip_meta Whether to strip image metadata during resizing. Default true.
*/
if ( apply_filters( 'image_strip_meta', $strip_meta ) ) {
$this->strip_meta(); // Fail silently if not supported.
}
try {
/*
* To be more efficient, resample large images to 5x the destination size before resizing
* whenever the output size is less that 1/3 of the original image size (1/3^2 ~= .111),
* unless we would be resampling to a scale smaller than 128x128.
*/
if ( is_callable( array( $this->image, 'sampleImage' ) ) ) {
$resize_ratio = ( $dst_w / $this->size['width'] ) * ( $dst_h / $this->size['height'] );
$sample_factor = 5;
if ( $resize_ratio < .111 && ( $dst_w * $sample_factor > 128 && $dst_h * $sample_factor > 128 ) ) {
$this->image->sampleImage( $dst_w * $sample_factor, $dst_h * $sample_factor );
}
}
/*
* Use resizeImage() when it's available and a valid filter value is set.
* Otherwise, fall back to the scaleImage() method for resizing, which
* results in better image quality over resizeImage() with default filter
* settings and retains backward compatibility with pre 4.5 functionality.
*/
if ( is_callable( array( $this->image, 'resizeImage' ) ) && $filter ) {
$this->image->setOption( 'filter:support', '2.0' );
$this->image->resizeImage( $dst_w, $dst_h, $filter, 1 );
} else {
$this->image->scaleImage( $dst_w, $dst_h );
}
// Set appropriate quality settings after resizing.
if ( 'image/jpeg' === $this->mime_type ) {
if ( is_callable( array( $this->image, 'unsharpMaskImage' ) ) ) {
$this->image->unsharpMaskImage( 0.25, 0.25, 8, 0.065 );
}
$this->image->setOption( 'jpeg:fancy-upsampling', 'off' );
}
if ( 'image/png' === $this->mime_type ) {
$this->image->setOption( 'png:compression-filter', '5' );
$this->image->setOption( 'png:compression-level', '9' );
$this->image->setOption( 'png:compression-strategy', '1' );
$this->image->setOption( 'png:exclude-chunk', 'all' );
}
/*
* If alpha channel is not defined, set it opaque.
*
* Note that Imagick::getImageAlphaChannel() is only available if Imagick
* has been compiled against ImageMagick version 6.4.0 or newer.
*/
if ( is_callable( array( $this->image, 'getImageAlphaChannel' ) )
&& is_callable( array( $this->image, 'setImageAlphaChannel' ) )
&& defined( 'Imagick::ALPHACHANNEL_UNDEFINED' )
&& defined( 'Imagick::ALPHACHANNEL_OPAQUE' )
) {
if ( $this->image->getImageAlphaChannel() === Imagick::ALPHACHANNEL_UNDEFINED ) {
$this->image->setImageAlphaChannel( Imagick::ALPHACHANNEL_OPAQUE );
}
}
// Limit the bit depth of resized images to 8 bits per channel.
if ( is_callable( array( $this->image, 'getImageDepth' ) ) && is_callable( array( $this->image, 'setImageDepth' ) ) ) {
if ( 8 < $this->image->getImageDepth() ) {
$this->image->setImageDepth( 8 );
}
}
if ( is_callable( array( $this->image, 'setInterlaceScheme' ) ) && defined( 'Imagick::INTERLACE_NO' ) ) {
$this->image->setInterlaceScheme( Imagick::INTERLACE_NO );
}
} catch ( Exception $e ) {
return new WP_Error( 'image_resize_error', $e->getMessage() );
}
}
```
[apply\_filters( 'image\_strip\_meta', bool $strip\_meta )](../../hooks/image_strip_meta)
Filters whether to strip metadata from images when they’re resized.
| Uses | Description |
| --- | --- |
| [WP\_Image\_Editor\_Imagick::strip\_meta()](strip_meta) wp-includes/class-wp-image-editor-imagick.php | Strips all image meta except color profiles from an image. |
| [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\_Imagick::resize()](resize) wp-includes/class-wp-image-editor-imagick.php | Resizes current image. |
| [WP\_Image\_Editor\_Imagick::crop()](crop) wp-includes/class-wp-image-editor-imagick.php | Crops Image. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Image_Editor_Imagick::pdf_load_source(): true|WP_Error WP\_Image\_Editor\_Imagick::pdf\_load\_source(): true|WP\_Error
===============================================================
Load the image produced by Ghostscript.
Includes a workaround for a bug in Ghostscript 8.70 that prevents processing of some PDF files when `use-cropbox` is set.
true|[WP\_Error](../wp_error)
File: `wp-includes/class-wp-image-editor-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
protected function pdf_load_source() {
$filename = $this->pdf_setup();
if ( is_wp_error( $filename ) ) {
return $filename;
}
try {
// When generating thumbnails from cropped PDF pages, Imagemagick uses the uncropped
// area (resulting in unnecessary whitespace) unless the following option is set.
$this->image->setOption( 'pdf:use-cropbox', true );
// Reading image after Imagick instantiation because `setResolution`
// only applies correctly before the image is read.
$this->image->readImage( $filename );
} catch ( Exception $e ) {
// Attempt to run `gs` without the `use-cropbox` option. See #48853.
$this->image->setOption( 'pdf:use-cropbox', false );
$this->image->readImage( $filename );
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Image\_Editor\_Imagick::pdf\_setup()](pdf_setup) wp-includes/class-wp-image-editor-imagick.php | Sets up Imagick for PDF processing. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Image\_Editor\_Imagick::load()](load) wp-includes/class-wp-image-editor-imagick.php | Loads image from $this->file into new Imagick Object. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Image_Editor_Imagick::__destruct() WP\_Image\_Editor\_Imagick::\_\_destruct()
==========================================
File: `wp-includes/class-wp-image-editor-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
public function __destruct() {
if ( $this->image instanceof Imagick ) {
// We don't need the original in memory anymore.
$this->image->clear();
$this->image->destroy();
}
}
```
wordpress WP_Image_Editor_Imagick::load(): true|WP_Error WP\_Image\_Editor\_Imagick::load(): true|WP\_Error
==================================================
Loads image from $this->file into new Imagick Object.
true|[WP\_Error](../wp_error) True if loaded; [WP\_Error](../wp_error) on failure.
File: `wp-includes/class-wp-image-editor-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
public function load() {
if ( $this->image instanceof Imagick ) {
return true;
}
if ( ! is_file( $this->file ) && ! wp_is_stream( $this->file ) ) {
return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file );
}
/*
* Even though Imagick uses less PHP memory than GD, set higher limit
* for users that have low PHP.ini limits.
*/
wp_raise_memory_limit( 'image' );
try {
$this->image = new Imagick();
$file_extension = strtolower( pathinfo( $this->file, PATHINFO_EXTENSION ) );
if ( 'pdf' === $file_extension ) {
$pdf_loaded = $this->pdf_load_source();
if ( is_wp_error( $pdf_loaded ) ) {
return $pdf_loaded;
}
} else {
if ( wp_is_stream( $this->file ) ) {
// Due to reports of issues with streams with `Imagick::readImageFile()`, uses `Imagick::readImageBlob()` instead.
$this->image->readImageBlob( file_get_contents( $this->file ), $this->file );
} else {
$this->image->readImage( $this->file );
}
}
if ( ! $this->image->valid() ) {
return new WP_Error( 'invalid_image', __( 'File is not an image.' ), $this->file );
}
// Select the first frame to handle animated images properly.
if ( is_callable( array( $this->image, 'setIteratorIndex' ) ) ) {
$this->image->setIteratorIndex( 0 );
}
$this->mime_type = $this->get_mime_type( $this->image->getImageFormat() );
} catch ( Exception $e ) {
return new WP_Error( 'invalid_image', $e->getMessage(), $this->file );
}
$updated_size = $this->update_size();
if ( is_wp_error( $updated_size ) ) {
return $updated_size;
}
return $this->set_quality();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Image\_Editor\_Imagick::pdf\_load\_source()](pdf_load_source) wp-includes/class-wp-image-editor-imagick.php | Load the image produced by Ghostscript. |
| [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\_Imagick::update\_size()](update_size) wp-includes/class-wp-image-editor-imagick.php | Sets or updates current image size. |
| [WP\_Image\_Editor\_Imagick::set\_quality()](set_quality) wp-includes/class-wp-image-editor-imagick.php | Sets Image Compression quality on a 1-100% scale. |
| [wp\_is\_stream()](../../functions/wp_is_stream) wp-includes/functions.php | Tests if a given path is a stream URL |
| [\_\_()](../../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_Imagick::supports_mime_type( string $mime_type ): bool WP\_Image\_Editor\_Imagick::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-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
public static function supports_mime_type( $mime_type ) {
$imagick_extension = strtoupper( self::get_extension( $mime_type ) );
if ( ! $imagick_extension ) {
return false;
}
// setIteratorIndex is optional unless mime is an animated format.
// Here, we just say no if you are missing it and aren't loading a jpeg.
if ( ! method_exists( 'Imagick', 'setIteratorIndex' ) && 'image/jpeg' !== $mime_type ) {
return false;
}
try {
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
return ( (bool) @Imagick::queryFormats( $imagick_extension ) );
} catch ( Exception $e ) {
return false;
}
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_Imagick::flip( bool $horz, bool $vert ): true|WP_Error WP\_Image\_Editor\_Imagick::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-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
public function flip( $horz, $vert ) {
try {
if ( $horz ) {
$this->image->flipImage();
}
if ( $vert ) {
$this->image->flopImage();
}
// Normalize EXIF orientation data so that display is consistent across devices.
if ( is_callable( array( $this->image, 'setImageOrientation' ) ) && defined( 'Imagick::ORIENTATION_TOPLEFT' ) ) {
$this->image->setImageOrientation( Imagick::ORIENTATION_TOPLEFT );
}
} catch ( Exception $e ) {
return new WP_Error( 'image_flip_error', $e->getMessage() );
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [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_Imagick::strip_meta(): true|WP_Error WP\_Image\_Editor\_Imagick::strip\_meta(): true|WP\_Error
=========================================================
Strips all image meta except color profiles from an image.
true|[WP\_Error](../wp_error) True if stripping metadata was successful. [WP\_Error](../wp_error) object on error.
File: `wp-includes/class-wp-image-editor-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
protected function strip_meta() {
if ( ! is_callable( array( $this->image, 'getImageProfiles' ) ) ) {
return new WP_Error(
'image_strip_meta_error',
sprintf(
/* translators: %s: ImageMagick method name. */
__( '%s is required to strip image meta.' ),
'<code>Imagick::getImageProfiles()</code>'
)
);
}
if ( ! is_callable( array( $this->image, 'removeImageProfile' ) ) ) {
return new WP_Error(
'image_strip_meta_error',
sprintf(
/* translators: %s: ImageMagick method name. */
__( '%s is required to strip image meta.' ),
'<code>Imagick::removeImageProfile()</code>'
)
);
}
/*
* Protect a few profiles from being stripped for the following reasons:
*
* - icc: Color profile information
* - icm: Color profile information
* - iptc: Copyright data
* - exif: Orientation data
* - xmp: Rights usage data
*/
$protected_profiles = array(
'icc',
'icm',
'iptc',
'exif',
'xmp',
);
try {
// Strip profiles.
foreach ( $this->image->getImageProfiles( '*', true ) as $key => $value ) {
if ( ! in_array( $key, $protected_profiles, true ) ) {
$this->image->removeImageProfile( $key );
}
}
} catch ( Exception $e ) {
return new WP_Error( 'image_strip_meta_error', $e->getMessage() );
}
return true;
}
```
| 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\_Image\_Editor\_Imagick::thumbnail\_image()](thumbnail_image) wp-includes/class-wp-image-editor-imagick.php | Efficiently resize the current image |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Image_Editor_Imagick::_save( Imagick $image, string $filename = null, string $mime_type = null ): array|WP_Error WP\_Image\_Editor\_Imagick::\_save( Imagick $image, string $filename = null, string $mime\_type = null ): array|WP\_Error
=========================================================================================================================
`$image` Imagick Required `$filename` string Optional Default: `null`
`$mime_type` string 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-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.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 );
}
try {
// Store initial format.
$orig_format = $this->image->getImageFormat();
$this->image->setImageFormat( strtoupper( $this->get_extension( $mime_type ) ) );
} catch ( Exception $e ) {
return new WP_Error( 'image_save_error', $e->getMessage(), $filename );
}
$write_image_result = $this->write_image( $this->image, $filename );
if ( is_wp_error( $write_image_result ) ) {
return $write_image_result;
}
try {
// Reset original format.
$this->image->setImageFormat( $orig_format );
} catch ( Exception $e ) {
return new WP_Error( 'image_save_error', $e->getMessage(), $filename );
}
// 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,
/** This filter is documented in wp-includes/class-wp-image-editor-gd.php */
'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\_Imagick::write\_image()](write_image) wp-includes/class-wp-image-editor-imagick.php | Writes an image to a file or stream. |
| [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. |
| [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\_Imagick::make\_subsize()](make_subsize) wp-includes/class-wp-image-editor-imagick.php | Create an image sub-size and return the image meta data value for it. |
| [WP\_Image\_Editor\_Imagick::save()](save) wp-includes/class-wp-image-editor-imagick.php | Saves current 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_Imagick::resize( int|null $max_w, int|null $max_h, bool $crop = false ): true|WP_Error WP\_Image\_Editor\_Imagick::resize( int|null $max\_w, int|null $max\_h, bool $crop = false ): true|WP\_Error
============================================================================================================
Resizes current image.
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-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
public function resize( $max_w, $max_h, $crop = false ) {
if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) ) {
return true;
}
$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' ) );
}
list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
if ( $crop ) {
return $this->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h );
}
// Execute the resize.
$thumb_result = $this->thumbnail_image( $dst_w, $dst_h );
if ( is_wp_error( $thumb_result ) ) {
return $thumb_result;
}
return $this->update_size( $dst_w, $dst_h );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Image\_Editor\_Imagick::thumbnail\_image()](thumbnail_image) wp-includes/class-wp-image-editor-imagick.php | Efficiently resize the current image |
| [WP\_Image\_Editor\_Imagick::crop()](crop) wp-includes/class-wp-image-editor-imagick.php | Crops Image. |
| [WP\_Image\_Editor\_Imagick::update\_size()](update_size) wp-includes/class-wp-image-editor-imagick.php | Sets or updates current image size. |
| [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. |
| [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\_Imagick::make\_subsize()](make_subsize) wp-includes/class-wp-image-editor-imagick.php | Create an image sub-size and return the image meta data value for it. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_Imagick::stream( string $mime_type = null ): true|WP_Error WP\_Image\_Editor\_Imagick::stream( string $mime\_type = null ): true|WP\_Error
===============================================================================
Streams current image to browser.
`$mime_type` string Optional The mime type of the image. Default: `null`
true|[WP\_Error](../wp_error) True on success, [WP\_Error](../wp_error) object on failure.
File: `wp-includes/class-wp-image-editor-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
public function stream( $mime_type = null ) {
list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
try {
// Temporarily change format for stream.
$this->image->setImageFormat( strtoupper( $extension ) );
// Output stream of image content.
header( "Content-Type: $mime_type" );
print $this->image->getImageBlob();
// Reset image to original format.
$this->image->setImageFormat( $this->get_extension( $this->mime_type ) );
} catch ( Exception $e ) {
return new WP_Error( 'image_stream_error', $e->getMessage() );
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [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_Imagick::rotate( float $angle ): true|WP_Error WP\_Image\_Editor\_Imagick::rotate( float $angle ): true|WP\_Error
==================================================================
Rotates current image counter-clockwise by $angle.
`$angle` float Required true|[WP\_Error](../wp_error)
File: `wp-includes/class-wp-image-editor-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
public function rotate( $angle ) {
/**
* $angle is 360-$angle because Imagick rotates clockwise
* (GD rotates counter-clockwise)
*/
try {
$this->image->rotateImage( new ImagickPixel( 'none' ), 360 - $angle );
// Normalize EXIF orientation data so that display is consistent across devices.
if ( is_callable( array( $this->image, 'setImageOrientation' ) ) && defined( 'Imagick::ORIENTATION_TOPLEFT' ) ) {
$this->image->setImageOrientation( Imagick::ORIENTATION_TOPLEFT );
}
// Since this changes the dimensions of the image, update the size.
$result = $this->update_size();
if ( is_wp_error( $result ) ) {
return $result;
}
$this->image->setImagePage( $this->size['width'], $this->size['height'], 0, 0 );
} catch ( Exception $e ) {
return new WP_Error( 'image_rotate_error', $e->getMessage() );
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Image\_Editor\_Imagick::update\_size()](update_size) wp-includes/class-wp-image-editor-imagick.php | Sets or updates current image size. |
| [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_Imagick::test( array $args = array() ): bool WP\_Image\_Editor\_Imagick::test( array $args = array() ): bool
===============================================================
Checks to see if current environment supports Imagick.
We require Imagick 2.2.0 or greater, based on whether the queryFormats() method can be called statically.
`$args` array Optional Default: `array()`
bool
File: `wp-includes/class-wp-image-editor-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
public static function test( $args = array() ) {
// First, test Imagick's extension and classes.
if ( ! extension_loaded( 'imagick' ) || ! class_exists( 'Imagick', false ) || ! class_exists( 'ImagickPixel', false ) ) {
return false;
}
if ( version_compare( phpversion( 'imagick' ), '2.2.0', '<' ) ) {
return false;
}
$required_methods = array(
'clear',
'destroy',
'valid',
'getimage',
'writeimage',
'getimageblob',
'getimagegeometry',
'getimageformat',
'setimageformat',
'setimagecompression',
'setimagecompressionquality',
'setimagepage',
'setoption',
'scaleimage',
'cropimage',
'rotateimage',
'flipimage',
'flopimage',
'readimage',
'readimageblob',
);
// Now, test for deep requirements within Imagick.
if ( ! defined( 'imagick::COMPRESSION_JPEG' ) ) {
return false;
}
$class_methods = array_map( 'strtolower', get_class_methods( 'Imagick' ) );
if ( array_diff( $required_methods, $class_methods ) ) {
return false;
}
return true;
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_Imagick::save( string $destfilename = null, string $mime_type = null ): array|WP_Error WP\_Image\_Editor\_Imagick::save( string $destfilename = null, string $mime\_type = null ): array|WP\_Error
===========================================================================================================
Saves current image to file.
`$destfilename` string Optional Destination filename. Default: `null`
`$mime_type` string 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-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.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'];
try {
$this->image->setImageFormat( strtoupper( $this->get_extension( $this->mime_type ) ) );
} catch ( Exception $e ) {
return new WP_Error( 'image_save_error', $e->getMessage(), $this->file );
}
}
return $saved;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Image\_Editor\_Imagick::\_save()](_save) wp-includes/class-wp-image-editor-imagick.php | |
| [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 |
| --- | --- |
| [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. |
wordpress WP_Image_Editor_Imagick::set_quality( int $quality = null ): true|WP_Error WP\_Image\_Editor\_Imagick::set\_quality( int $quality = null ): true|WP\_Error
===============================================================================
Sets Image Compression quality on a 1-100% scale.
`$quality` int Optional Compression Quality. Range: [1,100] Default: `null`
true|[WP\_Error](../wp_error) True if set successfully; [WP\_Error](../wp_error) on failure.
File: `wp-includes/class-wp-image-editor-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
public function set_quality( $quality = null ) {
$quality_result = parent::set_quality( $quality );
if ( is_wp_error( $quality_result ) ) {
return $quality_result;
} else {
$quality = $this->get_quality();
}
try {
switch ( $this->mime_type ) {
case 'image/jpeg':
$this->image->setImageCompressionQuality( $quality );
$this->image->setImageCompression( imagick::COMPRESSION_JPEG );
break;
case 'image/webp':
$webp_info = wp_get_webp_info( $this->file );
if ( 'lossless' === $webp_info['type'] ) {
// Use WebP lossless settings.
$this->image->setImageCompressionQuality( 100 );
$this->image->setOption( 'webp:lossless', 'true' );
} else {
$this->image->setImageCompressionQuality( $quality );
}
break;
default:
$this->image->setImageCompressionQuality( $quality );
}
} catch ( Exception $e ) {
return new WP_Error( 'image_quality_error', $e->getMessage() );
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_webp\_info()](../../functions/wp_get_webp_info) wp-includes/media.php | Extracts meta information about a WebP file: width, height, and type. |
| [WP\_Image\_Editor::set\_quality()](../wp_image_editor/set_quality) wp-includes/class-wp-image-editor.php | Sets Image Compression quality on a 1-100% scale. |
| [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\_Imagick::load()](load) wp-includes/class-wp-image-editor-imagick.php | Loads image from $this->file into new Imagick Object. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_Imagick::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\_Imagick::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-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
if ( $src_abs ) {
$src_w -= $src_x;
$src_h -= $src_y;
}
try {
$this->image->cropImage( $src_w, $src_h, $src_x, $src_y );
$this->image->setImagePage( $src_w, $src_h, 0, 0 );
if ( $dst_w || $dst_h ) {
// 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;
}
$thumb_result = $this->thumbnail_image( $dst_w, $dst_h );
if ( is_wp_error( $thumb_result ) ) {
return $thumb_result;
}
return $this->update_size();
}
} catch ( Exception $e ) {
return new WP_Error( 'image_crop_error', $e->getMessage() );
}
return $this->update_size();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Image\_Editor\_Imagick::thumbnail\_image()](thumbnail_image) wp-includes/class-wp-image-editor-imagick.php | Efficiently resize the current image |
| [WP\_Image\_Editor\_Imagick::update\_size()](update_size) wp-includes/class-wp-image-editor-imagick.php | Sets or updates current image size. |
| [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\_Imagick::resize()](resize) wp-includes/class-wp-image-editor-imagick.php | Resizes current image. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_Imagick::update_size( int $width = null, int $height = null ): true|WP_Error WP\_Image\_Editor\_Imagick::update\_size( int $width = null, int $height = null ): true|WP\_Error
=================================================================================================
Sets or updates current image size.
`$width` int Optional Default: `null`
`$height` int Optional Default: `null`
true|[WP\_Error](../wp_error)
File: `wp-includes/class-wp-image-editor-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
protected function update_size( $width = null, $height = null ) {
$size = null;
if ( ! $width || ! $height ) {
try {
$size = $this->image->getImageGeometry();
} catch ( Exception $e ) {
return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file );
}
}
if ( ! $width ) {
$width = $size['width'];
}
if ( ! $height ) {
$height = $size['height'];
}
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. |
| [\_\_()](../../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\_Imagick::resize()](resize) wp-includes/class-wp-image-editor-imagick.php | Resizes current image. |
| [WP\_Image\_Editor\_Imagick::crop()](crop) wp-includes/class-wp-image-editor-imagick.php | Crops Image. |
| [WP\_Image\_Editor\_Imagick::rotate()](rotate) wp-includes/class-wp-image-editor-imagick.php | Rotates current image counter-clockwise by $angle. |
| [WP\_Image\_Editor\_Imagick::load()](load) wp-includes/class-wp-image-editor-imagick.php | Loads image from $this->file into new Imagick Object. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Image_Editor_Imagick::maybe_exif_rotate(): bool|WP_Error WP\_Image\_Editor\_Imagick::maybe\_exif\_rotate(): bool|WP\_Error
=================================================================
Check if a JPEG image has EXIF Orientation tag and rotate it if needed.
As ImageMagick copies the EXIF data to the flipped/rotated image, proceed only if EXIF Orientation can be reset afterwards.
bool|[WP\_Error](../wp_error) True if the image was rotated. False if no EXIF data or if the image doesn't need rotation.
[WP\_Error](../wp_error) if error while rotating.
File: `wp-includes/class-wp-image-editor-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
public function maybe_exif_rotate() {
if ( is_callable( array( $this->image, 'setImageOrientation' ) ) && defined( 'Imagick::ORIENTATION_TOPLEFT' ) ) {
return parent::maybe_exif_rotate();
} else {
return new WP_Error( 'write_exif_error', __( 'The image cannot be rotated because the embedded meta data cannot be updated.' ) );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Image\_Editor::maybe\_exif\_rotate()](../wp_image_editor/maybe_exif_rotate) wp-includes/class-wp-image-editor.php | Check if a JPEG image has EXIF Orientation tag and rotate it if needed. |
| [\_\_()](../../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.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_Image_Editor_Imagick::multi_resize( array $sizes ): array WP\_Image\_Editor\_Imagick::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 provided dimension.
* `...$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-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.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\_Imagick::make\_subsize()](make_subsize) wp-includes/class-wp-image-editor-imagick.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. |
| programming_docs |
wordpress WP_Image_Editor_Imagick::pdf_setup(): string|WP_Error WP\_Image\_Editor\_Imagick::pdf\_setup(): string|WP\_Error
==========================================================
Sets up Imagick for PDF processing.
Increases rendering DPI and only loads first page.
string|[WP\_Error](../wp_error) File to load or [WP\_Error](../wp_error) on failure.
File: `wp-includes/class-wp-image-editor-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
protected function pdf_setup() {
try {
// By default, PDFs are rendered in a very low resolution.
// We want the thumbnail to be readable, so increase the rendering DPI.
$this->image->setResolution( 128, 128 );
// Only load the first page.
return $this->file . '[0]';
} catch ( Exception $e ) {
return new WP_Error( 'pdf_setup_failed', $e->getMessage(), $this->file );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Image\_Editor\_Imagick::pdf\_load\_source()](pdf_load_source) wp-includes/class-wp-image-editor-imagick.php | Load the image produced by Ghostscript. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Image_Editor_Imagick::make_subsize( array $size_data ): array|WP_Error WP\_Image\_Editor\_Imagick::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-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.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;
$orig_image = $this->image->getImage();
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( $this->image );
$this->image->clear();
$this->image->destroy();
$this->image = null;
}
$this->size = $orig_size;
$this->image = $orig_image;
if ( ! is_wp_error( $saved ) ) {
unset( $saved['path'] );
}
return $saved;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Image\_Editor\_Imagick::\_save()](_save) wp-includes/class-wp-image-editor-imagick.php | |
| [WP\_Image\_Editor\_Imagick::resize()](resize) wp-includes/class-wp-image-editor-imagick.php | Resizes current image. |
| [\_\_()](../../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\_Imagick::multi\_resize()](multi_resize) wp-includes/class-wp-image-editor-imagick.php | Create multiple smaller images from a single source. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_Image_Editor_Imagick::write_image( Imagick $image, string $filename ): true|WP_Error WP\_Image\_Editor\_Imagick::write\_image( Imagick $image, string $filename ): true|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.
Writes an image to a file or stream.
`$image` Imagick Required `$filename` string Required The destination filename or stream URL. true|[WP\_Error](../wp_error)
File: `wp-includes/class-wp-image-editor-imagick.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-imagick.php/)
```
private function write_image( $image, $filename ) {
if ( wp_is_stream( $filename ) ) {
/*
* Due to reports of issues with streams with `Imagick::writeImageFile()` and `Imagick::writeImage()`, copies the blob instead.
* Checks for exact type due to: https://www.php.net/manual/en/function.file-put-contents.php
*/
if ( file_put_contents( $filename, $image->getImageBlob() ) === false ) {
return new WP_Error(
'image_save_error',
sprintf(
/* translators: %s: PHP function name. */
__( '%s failed while writing image to stream.' ),
'<code>file_put_contents()</code>'
),
$filename
);
} else {
return true;
}
} else {
$dirname = dirname( $filename );
if ( ! wp_mkdir_p( $dirname ) ) {
return new WP_Error(
'image_save_error',
sprintf(
/* translators: %s: Directory path. */
__( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
esc_html( $dirname )
)
);
}
try {
return $image->writeImage( $filename );
} catch ( Exception $e ) {
return new WP_Error( 'image_save_error', $e->getMessage(), $filename );
}
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_stream()](../../functions/wp_is_stream) wp-includes/functions.php | Tests if a given path is a stream URL |
| [wp\_mkdir\_p()](../../functions/wp_mkdir_p) wp-includes/functions.php | Recursive directory creation based on full path. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Image\_Editor\_Imagick::\_save()](_save) wp-includes/class-wp-image-editor-imagick.php | |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Widget_Custom_HTML::add_help_text() WP\_Widget\_Custom\_HTML::add\_help\_text()
===========================================
Add help text to widgets admin screen.
File: `wp-includes/widgets/class-wp-widget-custom-html.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-custom-html.php/)
```
public static function add_help_text() {
$screen = get_current_screen();
$content = '<p>';
$content .= __( 'Use the Custom HTML widget to add arbitrary HTML code to your widget areas.' );
$content .= '</p>';
if ( 'false' !== wp_get_current_user()->syntax_highlighting ) {
$content .= '<p>';
$content .= sprintf(
/* translators: 1: Link to user profile, 2: Additional link attributes, 3: Accessibility text. */
__( 'The edit field automatically highlights code syntax. You can disable this in your <a href="%1$s" %2$s>user profile%3$s</a> to work in plain text mode.' ),
esc_url( get_edit_profile_url() ),
'class="external-link" target="_blank"',
sprintf(
'<span class="screen-reader-text"> %s</span>',
/* translators: Accessibility text. */
__( '(opens in a new tab)' )
)
);
$content .= '</p>';
$content .= '<p id="editor-keyboard-trap-help-1">' . __( 'When using a keyboard to navigate:' ) . '</p>';
$content .= '<ul>';
$content .= '<li id="editor-keyboard-trap-help-2">' . __( 'In the editing area, the Tab key enters a tab character.' ) . '</li>';
$content .= '<li id="editor-keyboard-trap-help-3">' . __( 'To move away from this area, press the Esc key followed by the Tab key.' ) . '</li>';
$content .= '<li id="editor-keyboard-trap-help-4">' . __( 'Screen reader users: when in forms mode, you may need to press the Esc key twice.' ) . '</li>';
$content .= '</ul>';
}
$screen->add_help_tab(
array(
'id' => 'custom_html_widget',
'title' => __( 'Custom HTML Widget' ),
'content' => $content,
)
);
}
```
| Uses | Description |
| --- | --- |
| [get\_current\_screen()](../../functions/get_current_screen) wp-admin/includes/screen.php | Get the current screen object |
| [wp\_get\_current\_user()](../../functions/wp_get_current_user) wp-includes/pluggable.php | Retrieves the current user object. |
| [get\_edit\_profile\_url()](../../functions/get_edit_profile_url) wp-includes/link-template.php | Retrieves the URL to the user’s profile editor. |
| [\_\_()](../../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 |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Widget_Custom_HTML::form( array $instance ) WP\_Widget\_Custom\_HTML::form( array $instance )
=================================================
Outputs the Custom HTML widget settings form.
* [WP\_Widget\_Custom\_HTML::render\_control\_template\_scripts()](../wp_widget_custom_html/render_control_template_scripts)
`$instance` array Required Current instance. File: `wp-includes/widgets/class-wp-widget-custom-html.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-custom-html.php/)
```
public function form( $instance ) {
$instance = wp_parse_args( (array) $instance, $this->default_instance );
?>
<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" class="title sync-input" type="hidden" value="<?php echo esc_attr( $instance['title'] ); ?>" />
<textarea id="<?php echo $this->get_field_id( 'content' ); ?>" name="<?php echo $this->get_field_name( 'content' ); ?>" class="content sync-input" hidden><?php echo esc_textarea( $instance['content'] ); ?></textarea>
<?php
}
```
| Uses | Description |
| --- | --- |
| [esc\_textarea()](../../functions/esc_textarea) wp-includes/formatting.php | Escaping for textarea values. |
| [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 |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | The form contains only hidden sync inputs. For the control UI, see `WP_Widget_Custom_HTML::render_control_template_scripts()`. |
| [4.8.1](https://developer.wordpress.org/reference/since/4.8.1/) | Introduced. |
wordpress WP_Widget_Custom_HTML::update( array $new_instance, array $old_instance ): array WP\_Widget\_Custom\_HTML::update( array $new\_instance, array $old\_instance ): array
=====================================================================================
Handles updating settings for the current Custom HTML 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 Settings to save or bool false to cancel saving.
File: `wp-includes/widgets/class-wp-widget-custom-html.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-custom-html.php/)
```
public function update( $new_instance, $old_instance ) {
$instance = array_merge( $this->default_instance, $old_instance );
$instance['title'] = sanitize_text_field( $new_instance['title'] );
if ( current_user_can( 'unfiltered_html' ) ) {
$instance['content'] = $new_instance['content'];
} else {
$instance['content'] = wp_kses_post( $new_instance['content'] );
}
return $instance;
}
```
| Uses | Description |
| --- | --- |
| [wp\_kses\_post()](../../functions/wp_kses_post) wp-includes/kses.php | Sanitizes content for allowed HTML tags for post content. |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Version | Description |
| --- | --- |
| [4.8.1](https://developer.wordpress.org/reference/since/4.8.1/) | Introduced. |
wordpress WP_Widget_Custom_HTML::enqueue_admin_scripts() WP\_Widget\_Custom\_HTML::enqueue\_admin\_scripts()
===================================================
Loads the required scripts and styles for the widget control.
File: `wp-includes/widgets/class-wp-widget-custom-html.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-custom-html.php/)
```
public function enqueue_admin_scripts() {
$settings = wp_enqueue_code_editor(
array(
'type' => 'text/html',
'codemirror' => array(
'indentUnit' => 2,
'tabSize' => 2,
),
)
);
wp_enqueue_script( 'custom-html-widgets' );
if ( empty( $settings ) ) {
$settings = array(
'disabled' => true,
);
}
wp_add_inline_script( 'custom-html-widgets', sprintf( 'wp.customHtmlWidgets.init( %s );', wp_json_encode( $settings ) ), 'after' );
$l10n = array(
'errorNotice' => array(
/* translators: %d: Error count. */
'singular' => _n( 'There is %d error which must be fixed before you can save.', 'There are %d errors which must be fixed before you can save.', 1 ),
/* translators: %d: Error count. */
'plural' => _n( 'There is %d error which must be fixed before you can save.', 'There are %d errors which must be fixed before you can save.', 2 ),
// @todo This is lacking, as some languages have a dedicated dual form. For proper handling of plurals in JS, see #20491.
),
);
wp_add_inline_script( 'custom-html-widgets', sprintf( 'jQuery.extend( wp.customHtmlWidgets.l10n, %s );', wp_json_encode( $l10n ) ), 'after' );
}
```
| Uses | Description |
| --- | --- |
| [wp\_enqueue\_code\_editor()](../../functions/wp_enqueue_code_editor) wp-includes/general-template.php | Enqueues assets needed by the code editor for the given settings. |
| [wp\_add\_inline\_script()](../../functions/wp_add_inline_script) wp-includes/functions.wp-scripts.php | Adds extra code to a registered script. |
| [\_n()](../../functions/_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Widget_Custom_HTML::render_control_template_scripts() WP\_Widget\_Custom\_HTML::render\_control\_template\_scripts()
==============================================================
Render form template scripts.
File: `wp-includes/widgets/class-wp-widget-custom-html.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-custom-html.php/)
```
public static function render_control_template_scripts() {
?>
<script type="text/html" id="tmpl-widget-custom-html-control-fields">
<# var elementIdPrefix = 'el' + String( Math.random() ).replace( /\D/g, '' ) + '_' #>
<p>
<label for="{{ elementIdPrefix }}title"><?php esc_html_e( 'Title:' ); ?></label>
<input id="{{ elementIdPrefix }}title" type="text" class="widefat title">
</p>
<p>
<label for="{{ elementIdPrefix }}content" id="{{ elementIdPrefix }}content-label"><?php esc_html_e( 'Content:' ); ?></label>
<textarea id="{{ elementIdPrefix }}content" class="widefat code content" rows="16" cols="20"></textarea>
</p>
<?php if ( ! current_user_can( 'unfiltered_html' ) ) : ?>
<?php
$probably_unsafe_html = array( 'script', 'iframe', 'form', 'input', 'style' );
$allowed_html = wp_kses_allowed_html( 'post' );
$disallowed_html = array_diff( $probably_unsafe_html, array_keys( $allowed_html ) );
?>
<?php if ( ! empty( $disallowed_html ) ) : ?>
<# if ( data.codeEditorDisabled ) { #>
<p>
<?php _e( 'Some HTML tags are not permitted, including:' ); ?>
<code><?php echo implode( '</code>, <code>', $disallowed_html ); ?></code>
</p>
<# } #>
<?php endif; ?>
<?php endif; ?>
<div class="code-editor-error-container"></div>
</script>
<?php
}
```
| Uses | Description |
| --- | --- |
| [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\_kses\_allowed\_html()](../../functions/wp_kses_allowed_html) wp-includes/kses.php | Returns an array of allowed HTML tags and attributes for a given context. |
| [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. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Widget_Custom_HTML::_register_one( int $number = -1 ) WP\_Widget\_Custom\_HTML::\_register\_one( int $number = -1 )
=============================================================
Add hooks for enqueueing assets when registering all widget instances of this widget class.
`$number` int Optional The unique order number of this widget instance compared to other instances of the same class. Default: `-1`
File: `wp-includes/widgets/class-wp-widget-custom-html.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-custom-html.php/)
```
public function _register_one( $number = -1 ) {
parent::_register_one( $number );
if ( $this->registered ) {
return;
}
$this->registered = true;
wp_add_inline_script( 'custom-html-widgets', sprintf( 'wp.customHtmlWidgets.idBases.push( %s );', wp_json_encode( $this->id_base ) ) );
// Note that the widgets component in the customizer will also do
// the 'admin_print_scripts-widgets.php' action in WP_Customize_Widgets::print_scripts().
add_action( 'admin_print_scripts-widgets.php', array( $this, 'enqueue_admin_scripts' ) );
// Note that the widgets component in the customizer will also do
// the 'admin_footer-widgets.php' action in WP_Customize_Widgets::print_footer_scripts().
add_action( 'admin_footer-widgets.php', array( 'WP_Widget_Custom_HTML', 'render_control_template_scripts' ) );
// Note this action is used to ensure the help text is added to the end.
add_action( 'admin_head-widgets.php', array( 'WP_Widget_Custom_HTML', 'add_help_text' ) );
}
```
| Uses | Description |
| --- | --- |
| [wp\_add\_inline\_script()](../../functions/wp_add_inline_script) wp-includes/functions.wp-scripts.php | Adds extra code to a registered script. |
| [WP\_Widget::\_register\_one()](../wp_widget/_register_one) wp-includes/class-wp-widget.php | Registers an instance of the widget class. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
| programming_docs |
wordpress WP_Widget_Custom_HTML::_filter_gallery_shortcode_attrs( array $attrs ): array WP\_Widget\_Custom\_HTML::\_filter\_gallery\_shortcode\_attrs( array $attrs ): array
====================================================================================
Filters gallery shortcode attributes.
Prevents all of a site’s attachments from being shown in a gallery displayed on a non-singular template where a $post context is not available.
`$attrs` array Required Attributes. array Attributes.
File: `wp-includes/widgets/class-wp-widget-custom-html.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-custom-html.php/)
```
public function _filter_gallery_shortcode_attrs( $attrs ) {
if ( ! is_singular() && empty( $attrs['id'] ) && empty( $attrs['include'] ) ) {
$attrs['id'] = -1;
}
return $attrs;
}
```
| Uses | Description |
| --- | --- |
| [is\_singular()](../../functions/is_singular) wp-includes/query.php | Determines whether the query is for an existing single post of any post type (post, attachment, page, custom post types). |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Widget_Custom_HTML::__construct() WP\_Widget\_Custom\_HTML::\_\_construct()
=========================================
Sets up a new Custom HTML widget instance.
File: `wp-includes/widgets/class-wp-widget-custom-html.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-custom-html.php/)
```
public function __construct() {
$widget_ops = array(
'classname' => 'widget_custom_html',
'description' => __( 'Arbitrary HTML code.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
$control_ops = array(
'width' => 400,
'height' => 350,
);
parent::__construct( 'custom_html', __( 'Custom HTML' ), $widget_ops, $control_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 |
| --- | --- |
| [4.8.1](https://developer.wordpress.org/reference/since/4.8.1/) | Introduced. |
wordpress WP_Widget_Custom_HTML::widget( array $args, array $instance ) WP\_Widget\_Custom\_HTML::widget( array $args, array $instance )
================================================================
Outputs the content for the current Custom HTML widget instance.
`$args` array Required Display arguments including `'before_title'`, `'after_title'`, `'before_widget'`, and `'after_widget'`. `$instance` array Required Settings for the current Custom HTML widget instance. File: `wp-includes/widgets/class-wp-widget-custom-html.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-custom-html.php/)
```
public function widget( $args, $instance ) {
global $post;
// Override global $post so filters (and shortcodes) apply in a consistent context.
$original_post = $post;
if ( is_singular() ) {
// Make sure post is always the queried object on singular queries (not from another sub-query that failed to clean up the global $post).
$post = get_queried_object();
} else {
// Nullify the $post global during widget rendering to prevent shortcodes from running with the unexpected context on archive queries.
$post = null;
}
// Prevent dumping out all attachments from the media library.
add_filter( 'shortcode_atts_gallery', array( $this, '_filter_gallery_shortcode_attrs' ) );
$instance = array_merge( $this->default_instance, $instance );
/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
$title = apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base );
// Prepare instance data that looks like a normal Text widget.
$simulated_text_widget_instance = array_merge(
$instance,
array(
'text' => isset( $instance['content'] ) ? $instance['content'] : '',
'filter' => false, // Because wpautop is not applied.
'visual' => false, // Because it wasn't created in TinyMCE.
)
);
unset( $simulated_text_widget_instance['content'] ); // Was moved to 'text' prop.
/** This filter is documented in wp-includes/widgets/class-wp-widget-text.php */
$content = apply_filters( 'widget_text', $instance['content'], $simulated_text_widget_instance, $this );
// Adds 'noopener' relationship, without duplicating values, to all HTML A elements that have a target.
$content = wp_targeted_link_rel( $content );
/**
* Filters the content of the Custom HTML widget.
*
* @since 4.8.1
*
* @param string $content The widget content.
* @param array $instance Array of settings for the current widget.
* @param WP_Widget_Custom_HTML $widget Current Custom HTML widget instance.
*/
$content = apply_filters( 'widget_custom_html_content', $content, $instance, $this );
// Restore post global.
$post = $original_post;
remove_filter( 'shortcode_atts_gallery', array( $this, '_filter_gallery_shortcode_attrs' ) );
// Inject the Text widget's container class name alongside this widget's class name for theme styling compatibility.
$args['before_widget'] = preg_replace( '/(?<=\sclass=["\'])/', 'widget_text ', $args['before_widget'] );
echo $args['before_widget'];
if ( ! empty( $title ) ) {
echo $args['before_title'] . $title . $args['after_title'];
}
echo '<div class="textwidget custom-html-widget">'; // The textwidget class is for theme styling compatibility.
echo $content;
echo '</div>';
echo $args['after_widget'];
}
```
[apply\_filters( 'widget\_custom\_html\_content', string $content, array $instance, WP\_Widget\_Custom\_HTML $widget )](../../hooks/widget_custom_html_content)
Filters the content of the Custom HTML widget.
[apply\_filters( 'widget\_text', string $text, array $instance, WP\_Widget\_Text|WP\_Widget\_Custom\_HTML $widget )](../../hooks/widget_text)
Filters the content of the Text widget.
[apply\_filters( 'widget\_title', string $title, array $instance, mixed $id\_base )](../../hooks/widget_title)
Filters the widget title.
| 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. |
| [is\_singular()](../../functions/is_singular) wp-includes/query.php | Determines whether the query is for an existing single post of any post type (post, attachment, page, custom post types). |
| [get\_queried\_object()](../../functions/get_queried_object) wp-includes/query.php | Retrieves the currently queried object. |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter 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.8.1](https://developer.wordpress.org/reference/since/4.8.1/) | Introduced. |
wordpress WP_REST_Terms_Controller::get_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Terms\_Controller::get\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
==================================================================================================
Gets 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-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
public function get_item( $request ) {
$term = $this->get_term( $request['id'] );
if ( is_wp_error( $term ) ) {
return $term;
}
$response = $this->prepare_item_for_response( $term, $request );
return rest_ensure_response( $response );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Terms\_Controller::get\_term()](get_term) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Get the term, if the ID is valid. |
| [WP\_REST\_Terms\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares a single term output for response. |
| [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 |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Terms_Controller::prepare_item_for_response( WP_Term $item, WP_REST_Request $request ): WP_REST_Response WP\_REST\_Terms\_Controller::prepare\_item\_for\_response( WP\_Term $item, WP\_REST\_Request $request ): WP\_REST\_Response
===========================================================================================================================
Prepares a single term output for response.
`$item` [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-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
public function prepare_item_for_response( $item, $request ) {
$fields = $this->get_fields_for_response( $request );
$data = array();
if ( in_array( 'id', $fields, true ) ) {
$data['id'] = (int) $item->term_id;
}
if ( in_array( 'count', $fields, true ) ) {
$data['count'] = (int) $item->count;
}
if ( in_array( 'description', $fields, true ) ) {
$data['description'] = $item->description;
}
if ( in_array( 'link', $fields, true ) ) {
$data['link'] = get_term_link( $item );
}
if ( in_array( 'name', $fields, true ) ) {
$data['name'] = $item->name;
}
if ( in_array( 'slug', $fields, true ) ) {
$data['slug'] = $item->slug;
}
if ( in_array( 'taxonomy', $fields, true ) ) {
$data['taxonomy'] = $item->taxonomy;
}
if ( in_array( 'parent', $fields, true ) ) {
$data['parent'] = (int) $item->parent;
}
if ( in_array( 'meta', $fields, true ) ) {
$data['meta'] = $this->meta->get_value( $item->term_id, $request );
}
$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( $item ) );
}
/**
* Filters the term data for a REST API response.
*
* The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `rest_prepare_category`
* - `rest_prepare_post_tag`
*
* Allows modification of the term data right before it is returned.
*
* @since 4.7.0
*
* @param WP_REST_Response $response The response object.
* @param WP_Term $item The original term object.
* @param WP_REST_Request $request Request used to generate the response.
*/
return apply_filters( "rest_prepare_{$this->taxonomy}", $response, $item, $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 |
| --- | --- |
| [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\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares links for the request. |
| [get\_term\_link()](../../functions/get_term_link) wp-includes/taxonomy.php | Generates a permalink for a taxonomy term archive. |
| [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::prepare\_item\_for\_response()](../wp_rest_menus_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Prepares a single term output for response. |
| [WP\_REST\_Terms\_Controller::delete\_item()](delete_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Deletes a single term from a taxonomy. |
| [WP\_REST\_Terms\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Gets a single term from a taxonomy. |
| [WP\_REST\_Terms\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Creates a single term in a taxonomy. |
| [WP\_REST\_Terms\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Updates a single term from a taxonomy. |
| [WP\_REST\_Terms\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Retrieves terms associated with a taxonomy. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Terms_Controller::prepare_links( WP_Term $term ): array WP\_REST\_Terms\_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-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
protected function prepare_links( $term ) {
$links = array(
'self' => array(
'href' => rest_url( rest_get_route_for_term( $term ) ),
),
'collection' => array(
'href' => rest_url( rest_get_route_for_taxonomy_items( $this->taxonomy ) ),
),
'about' => array(
'href' => rest_url( sprintf( 'wp/v2/taxonomies/%s', $this->taxonomy ) ),
),
);
if ( $term->parent ) {
$parent_term = get_term( (int) $term->parent, $term->taxonomy );
if ( $parent_term ) {
$links['up'] = array(
'href' => rest_url( rest_get_route_for_term( $parent_term ) ),
'embeddable' => true,
);
}
}
$taxonomy_obj = get_taxonomy( $term->taxonomy );
if ( empty( $taxonomy_obj->object_type ) ) {
return $links;
}
$post_type_links = array();
foreach ( $taxonomy_obj->object_type as $type ) {
$rest_path = rest_get_route_for_post_type_items( $type );
if ( empty( $rest_path ) ) {
continue;
}
$post_type_links[] = array(
'href' => add_query_arg( $this->rest_base, $term->term_id, rest_url( $rest_path ) ),
);
}
if ( ! empty( $post_type_links ) ) {
$links['https://api.w.org/post_type'] = $post_type_links;
}
return $links;
}
```
| 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\_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\_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. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [get\_term()](../../functions/get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| [get\_taxonomy()](../../functions/get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::prepare\_links()](../wp_rest_menus_controller/prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Prepares links for the request. |
| [WP\_REST\_Terms\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares a single term output for response. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Terms_Controller::get_items( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Terms\_Controller::get\_items( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
===================================================================================================
Retrieves terms associated with 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-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
public function get_items( $request ) {
// Retrieve the list of registered collection query parameters.
$registered = $this->get_collection_params();
/*
* This array defines mappings between public API query parameters whose
* values are accepted as-passed, and their internal WP_Query parameter
* name equivalents (some are the same). Only values which are also
* present in $registered will be set.
*/
$parameter_mappings = array(
'exclude' => 'exclude',
'include' => 'include',
'order' => 'order',
'orderby' => 'orderby',
'post' => 'post',
'hide_empty' => 'hide_empty',
'per_page' => 'number',
'search' => 'search',
'slug' => 'slug',
);
$prepared_args = array( 'taxonomy' => $this->taxonomy );
/*
* For each known parameter which is both registered and present in the request,
* set the parameter's value on the query $prepared_args.
*/
foreach ( $parameter_mappings as $api_param => $wp_param ) {
if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
$prepared_args[ $wp_param ] = $request[ $api_param ];
}
}
if ( isset( $prepared_args['orderby'] ) && isset( $request['orderby'] ) ) {
$orderby_mappings = array(
'include_slugs' => 'slug__in',
);
if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) {
$prepared_args['orderby'] = $orderby_mappings[ $request['orderby'] ];
}
}
if ( isset( $registered['offset'] ) && ! empty( $request['offset'] ) ) {
$prepared_args['offset'] = $request['offset'];
} else {
$prepared_args['offset'] = ( $request['page'] - 1 ) * $prepared_args['number'];
}
$taxonomy_obj = get_taxonomy( $this->taxonomy );
if ( $taxonomy_obj->hierarchical && isset( $registered['parent'], $request['parent'] ) ) {
if ( 0 === $request['parent'] ) {
// Only query top-level terms.
$prepared_args['parent'] = 0;
} else {
if ( $request['parent'] ) {
$prepared_args['parent'] = $request['parent'];
}
}
}
/**
* Filters get_terms() arguments when querying terms via the REST API.
*
* The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `rest_category_query`
* - `rest_post_tag_query`
*
* Enables adding extra arguments or setting defaults for a terms
* collection request.
*
* @since 4.7.0
*
* @link https://developer.wordpress.org/reference/functions/get_terms/
*
* @param array $prepared_args Array of arguments for get_terms().
* @param WP_REST_Request $request The REST API request.
*/
$prepared_args = apply_filters( "rest_{$this->taxonomy}_query", $prepared_args, $request );
if ( ! empty( $prepared_args['post'] ) ) {
$query_result = wp_get_object_terms( $prepared_args['post'], $this->taxonomy, $prepared_args );
// Used when calling wp_count_terms() below.
$prepared_args['object_ids'] = $prepared_args['post'];
} else {
$query_result = get_terms( $prepared_args );
}
$count_args = $prepared_args;
unset( $count_args['number'], $count_args['offset'] );
$total_terms = wp_count_terms( $count_args );
// wp_count_terms() can return a falsey value when the term has no children.
if ( ! $total_terms ) {
$total_terms = 0;
}
$response = array();
foreach ( $query_result as $term ) {
$data = $this->prepare_item_for_response( $term, $request );
$response[] = $this->prepare_response_for_collection( $data );
}
$response = rest_ensure_response( $response );
// Store pagination values for headers.
$per_page = (int) $prepared_args['number'];
$page = ceil( ( ( (int) $prepared_args['offset'] ) / $per_page ) + 1 );
$response->header( 'X-WP-Total', (int) $total_terms );
$max_pages = ceil( $total_terms / $per_page );
$response->header( 'X-WP-TotalPages', (int) $max_pages );
$request_params = $request->get_query_params();
$collection_url = rest_url( rest_get_route_for_taxonomy_items( $this->taxonomy ) );
$base = add_query_arg( urlencode_deep( $request_params ), $collection_url );
if ( $page > 1 ) {
$prev_page = $page - 1;
if ( $prev_page > $max_pages ) {
$prev_page = $max_pages;
}
$prev_link = add_query_arg( 'page', $prev_page, $base );
$response->link_header( 'prev', $prev_link );
}
if ( $max_pages > $page ) {
$next_page = $page + 1;
$next_link = add_query_arg( 'page', $next_page, $base );
$response->link_header( 'next', $next_link );
}
return $response;
}
```
[apply\_filters( "rest\_{$this->taxonomy}\_query", array $prepared\_args, WP\_REST\_Request $request )](../../hooks/rest_this-taxonomy_query)
Filters [get\_terms()](../../functions/get_terms) arguments when querying terms via the REST API.
| 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. |
| [WP\_REST\_Terms\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Retrieves the query params for collections. |
| [WP\_REST\_Terms\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares a single term output for response. |
| [urlencode\_deep()](../../functions/urlencode_deep) wp-includes/formatting.php | Navigates through an array, object, or scalar, and encodes the values to be used in a URL. |
| [wp\_get\_object\_terms()](../../functions/wp_get_object_terms) wp-includes/taxonomy.php | Retrieves the terms associated with the given object(s), in the supplied taxonomies. |
| [wp\_count\_terms()](../../functions/wp_count_terms) wp-includes/taxonomy.php | Counts how many terms are in taxonomy. |
| [get\_terms()](../../functions/get_terms) wp-includes/taxonomy.php | Retrieves the terms in a given taxonomy or list of taxonomies. |
| [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. |
| [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. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Terms_Controller::get_term( int $id ): WP_Term|WP_Error WP\_REST\_Terms\_Controller::get\_term( int $id ): WP\_Term|WP\_Error
=====================================================================
Get 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-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
protected function get_term( $id ) {
$error = new WP_Error(
'rest_term_invalid',
__( 'Term does not exist.' ),
array( 'status' => 404 )
);
if ( ! $this->check_is_taxonomy_allowed( $this->taxonomy ) ) {
return $error;
}
if ( (int) $id <= 0 ) {
return $error;
}
$term = get_term( (int) $id, $this->taxonomy );
if ( empty( $term ) || $term->taxonomy !== $this->taxonomy ) {
return $error;
}
return $term;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Terms\_Controller::check\_is\_taxonomy\_allowed()](check_is_taxonomy_allowed) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks that the taxonomy is valid. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_term()](../../functions/get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::get\_term()](../wp_rest_menus_controller/get_term) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Gets the term, if the ID is valid. |
| [WP\_REST\_Terms\_Controller::delete\_item()](delete_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Deletes a single term from a taxonomy. |
| [WP\_REST\_Terms\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Gets a single term from a taxonomy. |
| [WP\_REST\_Terms\_Controller::update\_item\_permissions\_check()](update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if a request has access to update the specified term. |
| [WP\_REST\_Terms\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Updates a single term from a taxonomy. |
| [WP\_REST\_Terms\_Controller::delete\_item\_permissions\_check()](delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if a request has access to delete the specified term. |
| [WP\_REST\_Terms\_Controller::get\_item\_permissions\_check()](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 |
| --- | --- |
| [4.7.2](https://developer.wordpress.org/reference/since/4.7.2/) | Introduced. |
wordpress WP_REST_Terms_Controller::create_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Terms\_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-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-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 = 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 );
$term = wp_insert_term( wp_slash( $prepared_term->name ), $this->taxonomy, 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.
*/
$term_id = $term->get_error_data( 'term_exists' );
if ( $term_id ) {
$existing_term = get_term( $term_id, $this->taxonomy );
$term->add_data( $existing_term->term_id, 'term_exists' );
$term->add_data(
array(
'status' => 400,
'term_id' => $term_id,
)
);
}
return $term;
}
$term = get_term( $term['term_id'], $this->taxonomy );
/**
* Fires after a single term is created or updated via the REST API.
*
* The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `rest_insert_category`
* - `rest_insert_post_tag`
*
* @since 4.7.0
*
* @param WP_Term $term Inserted or updated term object.
* @param WP_REST_Request $request Request object.
* @param bool $creating True when creating a term, false when updating.
*/
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;
}
}
$fields_update = $this->update_additional_fields_for_object( $term, $request );
if ( is_wp_error( $fields_update ) ) {
return $fields_update;
}
$request->set_param( 'context', 'edit' );
/**
* Fires after a single term is completely created or updated via the REST API.
*
* The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `rest_after_insert_category`
* - `rest_after_insert_post_tag`
*
* @since 5.0.0
*
* @param WP_Term $term Inserted or updated term object.
* @param WP_REST_Request $request Request object.
* @param bool $creating True when creating a term, false when updating.
*/
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\_Terms\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Retrieves the term’s schema, conforming to JSON Schema. |
| [WP\_REST\_Terms\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares a single term output for response. |
| [WP\_REST\_Terms\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares a single term for create or update. |
| [wp\_insert\_term()](../../functions/wp_insert_term) wp-includes/taxonomy.php | Adds a new term to the database. |
| [is\_taxonomy\_hierarchical()](../../functions/is_taxonomy_hierarchical) wp-includes/taxonomy.php | Determines whether the taxonomy object is hierarchical. |
| [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. |
| [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 |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Terms_Controller::check_read_terms_permission_for_post( WP_Post $post, WP_REST_Request $request ): bool WP\_REST\_Terms\_Controller::check\_read\_terms\_permission\_for\_post( WP\_Post $post, WP\_REST\_Request $request ): bool
==========================================================================================================================
Checks if the terms for a post can be read.
`$post` [WP\_Post](../wp_post) Required Post object. `$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. bool Whether the terms for the post can be read.
File: `wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
public function check_read_terms_permission_for_post( $post, $request ) {
// If the requested post isn't associated with this taxonomy, deny access.
if ( ! is_object_in_taxonomy( $post->post_type, $this->taxonomy ) ) {
return false;
}
// Grant access if the post is publicly viewable.
if ( is_post_publicly_viewable( $post ) ) {
return true;
}
// Otherwise grant access if the post is readable by the logged in user.
if ( current_user_can( 'read_post', $post->ID ) ) {
return true;
}
// Otherwise, deny access.
return false;
}
```
| Uses | Description |
| --- | --- |
| [is\_post\_publicly\_viewable()](../../functions/is_post_publicly_viewable) wp-includes/post.php | Determines whether a post is publicly viewable. |
| [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. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Terms\_Controller::get\_items\_permissions\_check()](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 |
| --- | --- |
| [6.0.3](https://developer.wordpress.org/reference/since/6.0.3/) | Introduced. |
wordpress WP_REST_Terms_Controller::update_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Terms\_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-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-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 ) ) {
$update = wp_update_term( $term->term_id, $term->taxonomy, 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;
}
}
$fields_update = $this->update_additional_fields_for_object( $term, $request );
if ( is_wp_error( $fields_update ) ) {
return $fields_update;
}
$request->set_param( 'context', 'edit' );
/** 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\_Terms\_Controller::get\_term()](get_term) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Get the term, if the ID is valid. |
| [WP\_REST\_Terms\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Retrieves the term’s schema, conforming to JSON Schema. |
| [WP\_REST\_Terms\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares a single term output for response. |
| [WP\_REST\_Terms\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares a single term for create or update. |
| [wp\_update\_term()](../../functions/wp_update_term) wp-includes/taxonomy.php | Updates term based on arguments provided. |
| [is\_taxonomy\_hierarchical()](../../functions/is_taxonomy_hierarchical) wp-includes/taxonomy.php | Determines whether the taxonomy object is hierarchical. |
| [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 |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Terms_Controller::delete_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Terms\_Controller::delete\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
===========================================================================================================
Checks if a request has access to delete the specified term.
`$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, otherwise false or [WP\_Error](../wp_error) object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
public function delete_item_permissions_check( $request ) {
$term = $this->get_term( $request['id'] );
if ( is_wp_error( $term ) ) {
return $term;
}
if ( ! current_user_can( 'delete_term', $term->term_id ) ) {
return new WP_Error(
'rest_cannot_delete',
__( 'Sorry, you are not allowed to delete this term.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Terms\_Controller::get\_term()](get_term) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Get the term, if the ID is valid. |
| [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 |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Terms_Controller::prepare_item_for_database( WP_REST_Request $request ): object WP\_REST\_Terms\_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 Term object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
public function prepare_item_for_database( $request ) {
$prepared_term = new stdClass;
$schema = $this->get_item_schema();
if ( isset( $request['name'] ) && ! empty( $schema['properties']['name'] ) ) {
$prepared_term->name = $request['name'];
}
if ( isset( $request['slug'] ) && ! empty( $schema['properties']['slug'] ) ) {
$prepared_term->slug = $request['slug'];
}
if ( isset( $request['taxonomy'] ) && ! empty( $schema['properties']['taxonomy'] ) ) {
$prepared_term->taxonomy = $request['taxonomy'];
}
if ( isset( $request['description'] ) && ! empty( $schema['properties']['description'] ) ) {
$prepared_term->description = $request['description'];
}
if ( isset( $request['parent'] ) && ! empty( $schema['properties']['parent'] ) ) {
$parent_term_id = 0;
$requested_parent = (int) $request['parent'];
if ( $requested_parent ) {
$parent_term = get_term( $requested_parent, $this->taxonomy );
if ( $parent_term instanceof WP_Term ) {
$parent_term_id = $parent_term->term_id;
}
}
$prepared_term->parent = $parent_term_id;
}
/**
* Filters term data before inserting term via the REST API.
*
* The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `rest_pre_insert_category`
* - `rest_pre_insert_post_tag`
*
* @since 4.7.0
*
* @param object $prepared_term Term object.
* @param WP_REST_Request $request Request object.
*/
return apply_filters( "rest_pre_insert_{$this->taxonomy}", $prepared_term, $request );
}
```
[apply\_filters( "rest\_pre\_insert\_{$this->taxonomy}", object $prepared\_term, WP\_REST\_Request $request )](../../hooks/rest_pre_insert_this-taxonomy)
Filters term data before inserting term via the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Terms\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Retrieves the term’s schema, conforming to JSON Schema. |
| [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. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::prepare\_item\_for\_database()](../wp_rest_menus_controller/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\_Terms\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Creates a single term in a taxonomy. |
| [WP\_REST\_Terms\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Updates a single term from a taxonomy. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Terms_Controller::check_is_taxonomy_allowed( string $taxonomy ): bool WP\_REST\_Terms\_Controller::check\_is\_taxonomy\_allowed( string $taxonomy ): bool
===================================================================================
Checks that the taxonomy is valid.
`$taxonomy` string Required Taxonomy to check. bool Whether the taxonomy is allowed for REST management.
File: `wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
protected function check_is_taxonomy_allowed( $taxonomy ) {
$taxonomy_obj = get_taxonomy( $taxonomy );
if ( $taxonomy_obj && ! empty( $taxonomy_obj->show_in_rest ) ) {
return true;
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [get\_taxonomy()](../../functions/get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Terms\_Controller::get\_term()](get_term) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Get the term, if the ID is valid. |
| [WP\_REST\_Terms\_Controller::create\_item\_permissions\_check()](create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if a request has access to create a term. |
| [WP\_REST\_Terms\_Controller::get\_items\_permissions\_check()](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 |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Terms_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Terms\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=========================================================================================================
Checks if a request has access to read terms in the specified 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, otherwise false or [WP\_Error](../wp_error) object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
public function get_items_permissions_check( $request ) {
$tax_obj = get_taxonomy( $this->taxonomy );
if ( ! $tax_obj || ! $this->check_is_taxonomy_allowed( $this->taxonomy ) ) {
return false;
}
if ( 'edit' === $request['context'] && ! current_user_can( $tax_obj->cap->edit_terms ) ) {
return new WP_Error(
'rest_forbidden_context',
__( 'Sorry, you are not allowed to edit terms in this taxonomy.' ),
array( 'status' => rest_authorization_required_code() )
);
}
if ( ! empty( $request['post'] ) ) {
$post = get_post( $request['post'] );
if ( ! $post ) {
return new WP_Error(
'rest_post_invalid_id',
__( 'Invalid post ID.' ),
array(
'status' => 400,
)
);
}
if ( ! $this->check_read_terms_permission_for_post( $post, $request ) ) {
return new WP_Error(
'rest_forbidden_context',
__( 'Sorry, you are not allowed to view terms for this post.' ),
array(
'status' => rest_authorization_required_code(),
)
);
}
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Terms\_Controller::check\_read\_terms\_permission\_for\_post()](check_read_terms_permission_for_post) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if the terms for a post can be read. |
| [WP\_REST\_Terms\_Controller::check\_is\_taxonomy\_allowed()](check_is_taxonomy_allowed) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks that the taxonomy is valid. |
| [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. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [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()](../wp_rest_menus_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Checks if a request has access to read menus. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Terms_Controller::update_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Terms\_Controller::update\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
===========================================================================================================
Checks if a request has access to update the specified term.
`$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, false or [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
public function update_item_permissions_check( $request ) {
$term = $this->get_term( $request['id'] );
if ( is_wp_error( $term ) ) {
return $term;
}
if ( ! current_user_can( 'edit_term', $term->term_id ) ) {
return new WP_Error(
'rest_cannot_update',
__( 'Sorry, you are not allowed to edit this term.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Terms\_Controller::get\_term()](get_term) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Get the term, if the ID is valid. |
| [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 |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Terms_Controller::register_routes() WP\_REST\_Terms\_Controller::register\_routes()
===============================================
Registers the routes for terms.
* [register\_rest\_route()](../../functions/register_rest_route)
File: `wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-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' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
),
'allow_batch' => $this->allow_batch,
'schema' => array( $this, 'get_public_item_schema' ),
)
);
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/(?P<id>[\d]+)',
array(
'args' => array(
'id' => array(
'description' => __( 'Unique identifier for the term.' ),
'type' => 'integer',
),
),
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' ) ),
),
),
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(
'force' => array(
'type' => 'boolean',
'default' => false,
'description' => __( 'Required to be true, as terms do not support trashing.' ),
),
),
),
'allow_batch' => $this->allow_batch,
'schema' => array( $this, 'get_public_item_schema' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Terms\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-terms-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_Terms_Controller::get_collection_params(): array WP\_REST\_Terms\_Controller::get\_collection\_params(): array
=============================================================
Retrieves the query params for collections.
array Collection parameters.
File: `wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
public function get_collection_params() {
$query_params = parent::get_collection_params();
$taxonomy = get_taxonomy( $this->taxonomy );
$query_params['context']['default'] = 'view';
$query_params['exclude'] = array(
'description' => __( 'Ensure result set excludes specific IDs.' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'default' => array(),
);
$query_params['include'] = array(
'description' => __( 'Limit result set to specific IDs.' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'default' => array(),
);
if ( ! $taxonomy->hierarchical ) {
$query_params['offset'] = array(
'description' => __( 'Offset the result set by a specific number of items.' ),
'type' => 'integer',
);
}
$query_params['order'] = array(
'description' => __( 'Order sort attribute ascending or descending.' ),
'type' => 'string',
'default' => 'asc',
'enum' => array(
'asc',
'desc',
),
);
$query_params['orderby'] = array(
'description' => __( 'Sort collection by term attribute.' ),
'type' => 'string',
'default' => 'name',
'enum' => array(
'id',
'include',
'name',
'slug',
'include_slugs',
'term_group',
'description',
'count',
),
);
$query_params['hide_empty'] = array(
'description' => __( 'Whether to hide terms not assigned to any posts.' ),
'type' => 'boolean',
'default' => false,
);
if ( $taxonomy->hierarchical ) {
$query_params['parent'] = array(
'description' => __( 'Limit result set to terms assigned to a specific parent.' ),
'type' => 'integer',
);
}
$query_params['post'] = array(
'description' => __( 'Limit result set to terms assigned to a specific post.' ),
'type' => 'integer',
'default' => null,
);
$query_params['slug'] = array(
'description' => __( 'Limit result set to terms with one or more specific slugs.' ),
'type' => 'array',
'items' => array(
'type' => 'string',
),
);
/**
* Filters collection parameters for the terms controller.
*
* The dynamic part of the filter `$this->taxonomy` refers to the taxonomy
* slug for the controller.
*
* This filter registers the collection parameter, but does not map the
* collection parameter to an internal WP_Term_Query parameter. Use the
* `rest_{$this->taxonomy}_query` filter to set WP_Term_Query parameters.
*
* @since 4.7.0
*
* @param array $query_params JSON Schema-formatted collection parameters.
* @param WP_Taxonomy $taxonomy Taxonomy object.
*/
return apply_filters( "rest_{$this->taxonomy}_collection_params", $query_params, $taxonomy );
}
```
[apply\_filters( "rest\_{$this->taxonomy}\_collection\_params", array $query\_params, WP\_Taxonomy $taxonomy )](../../hooks/rest_this-taxonomy_collection_params)
Filters collection parameters for the terms controller.
| 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. |
| [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\_REST\_Terms\_Controller::register\_routes()](register_routes) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Registers the routes for terms. |
| [WP\_REST\_Terms\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Retrieves terms associated with a taxonomy. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Terms_Controller::__construct( string $taxonomy ) WP\_REST\_Terms\_Controller::\_\_construct( string $taxonomy )
==============================================================
Constructor.
`$taxonomy` string Required Taxonomy key. File: `wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
public function __construct( $taxonomy ) {
$this->taxonomy = $taxonomy;
$tax_obj = get_taxonomy( $taxonomy );
$this->rest_base = ! empty( $tax_obj->rest_base ) ? $tax_obj->rest_base : $tax_obj->name;
$this->namespace = ! empty( $tax_obj->rest_namespace ) ? $tax_obj->rest_namespace : 'wp/v2';
$this->meta = new WP_REST_Term_Meta_Fields( $taxonomy );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Term\_Meta\_Fields::\_\_construct()](../wp_rest_term_meta_fields/__construct) wp-includes/rest-api/fields/class-wp-rest-term-meta-fields.php | Constructor. |
| [get\_taxonomy()](../../functions/get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Terms_Controller::get_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Terms\_Controller::get\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
========================================================================================================
Checks if a request has access to read or edit the specified term.
`$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-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
public function get_item_permissions_check( $request ) {
$term = $this->get_term( $request['id'] );
if ( is_wp_error( $term ) ) {
return $term;
}
if ( 'edit' === $request['context'] && ! current_user_can( 'edit_term', $term->term_id ) ) {
return new WP_Error(
'rest_forbidden_context',
__( 'Sorry, you are not allowed to edit this term.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Terms\_Controller::get\_term()](get_term) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Get the term, if the ID is valid. |
| [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. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::get\_item\_permissions\_check()](../wp_rest_menus_controller/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 |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Terms_Controller::create_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Terms\_Controller::create\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
===========================================================================================================
Checks if a request has access to create a term.
`$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, false or [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
public function create_item_permissions_check( $request ) {
if ( ! $this->check_is_taxonomy_allowed( $this->taxonomy ) ) {
return false;
}
$taxonomy_obj = get_taxonomy( $this->taxonomy );
if ( ( is_taxonomy_hierarchical( $this->taxonomy )
&& ! current_user_can( $taxonomy_obj->cap->edit_terms ) )
|| ( ! is_taxonomy_hierarchical( $this->taxonomy )
&& ! current_user_can( $taxonomy_obj->cap->assign_terms ) ) ) {
return new WP_Error(
'rest_cannot_create',
__( 'Sorry, you are not allowed to create terms in this taxonomy.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Terms\_Controller::check\_is\_taxonomy\_allowed()](check_is_taxonomy_allowed) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks that the taxonomy is valid. |
| [is\_taxonomy\_hierarchical()](../../functions/is_taxonomy_hierarchical) wp-includes/taxonomy.php | Determines whether the taxonomy object is hierarchical. |
| [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_Terms_Controller::delete_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Terms\_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-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php/)
```
public function delete_item( $request ) {
$term = $this->get_term( $request['id'] );
if ( is_wp_error( $term ) ) {
return $term;
}
$force = isset( $request['force'] ) ? (bool) $request['force'] : false;
// We don't support trashing for terms.
if ( ! $force ) {
return new WP_Error(
'rest_trash_not_supported',
/* translators: %s: force=true */
sprintf( __( "Terms 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 );
$retval = wp_delete_term( $term->term_id, $term->taxonomy );
if ( ! $retval ) {
return new WP_Error(
'rest_cannot_delete',
__( 'The term cannot be deleted.' ),
array( 'status' => 500 )
);
}
$response = new WP_REST_Response();
$response->set_data(
array(
'deleted' => true,
'previous' => $previous->get_data(),
)
);
/**
* Fires after a single term is deleted via the REST API.
*
* The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `rest_delete_category`
* - `rest_delete_post_tag`
*
* @since 4.7.0
*
* @param WP_Term $term The deleted term.
* @param WP_REST_Response $response The response data.
* @param WP_REST_Request $request The request sent to the API.
*/
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\_Terms\_Controller::get\_term()](get_term) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Get the term, if the ID is valid. |
| [WP\_REST\_Terms\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares a single term output for response. |
| [wp\_delete\_term()](../../functions/wp_delete_term) wp-includes/taxonomy.php | Removes a term 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. |
| [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_Terms_Controller::get_item_schema(): array WP\_REST\_Terms\_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-terms-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-terms-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' => 'post_tag' === $this->taxonomy ? 'tag' : $this->taxonomy,
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'Unique identifier for the term.' ),
'type' => 'integer',
'context' => array( 'view', 'embed', 'edit' ),
'readonly' => true,
),
'count' => array(
'description' => __( 'Number of published posts for the term.' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'description' => array(
'description' => __( 'HTML description of the term.' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'link' => array(
'description' => __( 'URL of the term.' ),
'type' => 'string',
'format' => 'uri',
'context' => array( 'view', 'embed', 'edit' ),
'readonly' => true,
),
'name' => array(
'description' => __( 'HTML title for the term.' ),
'type' => 'string',
'context' => array( 'view', 'embed', 'edit' ),
'arg_options' => array(
'sanitize_callback' => 'sanitize_text_field',
),
'required' => true,
),
'slug' => array(
'description' => __( 'An alphanumeric identifier for the term unique to its type.' ),
'type' => 'string',
'context' => array( 'view', 'embed', 'edit' ),
'arg_options' => array(
'sanitize_callback' => array( $this, 'sanitize_slug' ),
),
),
'taxonomy' => array(
'description' => __( 'Type attribution for the term.' ),
'type' => 'string',
'enum' => array( $this->taxonomy ),
'context' => array( 'view', 'embed', 'edit' ),
'readonly' => true,
),
),
);
$taxonomy = get_taxonomy( $this->taxonomy );
if ( $taxonomy->hierarchical ) {
$schema['properties']['parent'] = array(
'description' => __( 'The parent term ID.' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
);
}
$schema['properties']['meta'] = $this->meta->get_field_schema();
$this->schema = $schema;
return $this->add_additional_fields_schema( $this->schema );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../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. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menus\_Controller::get\_item\_schema()](../wp_rest_menus_controller/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()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Prepares a single term for create or update. |
| [WP\_REST\_Terms\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Creates a single term in a taxonomy. |
| [WP\_REST\_Terms\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Updates a single term from a taxonomy. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Locale::get_list_item_separator(): string WP\_Locale::get\_list\_item\_separator(): string
================================================
Retrieves the localized list item separator.
string Localized list item separator.
File: `wp-includes/class-wp-locale.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale.php/)
```
public function get_list_item_separator() {
return $this->list_item_separator;
}
```
| Used By | 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. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_Locale::is_rtl(): bool WP\_Locale::is\_rtl(): bool
===========================
Checks if current locale is RTL.
bool Whether locale is RTL.
File: `wp-includes/class-wp-locale.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale.php/)
```
public function is_rtl() {
return 'rtl' === $this->text_direction;
}
```
| Used By | Description |
| --- | --- |
| [wp\_localize\_jquery\_ui\_datepicker()](../../functions/wp_localize_jquery_ui_datepicker) wp-includes/script-loader.php | Localizes the jQuery UI datepicker. |
| [is\_rtl()](../../functions/is_rtl) wp-includes/l10n.php | Determines whether the current locale is right-to-left (RTL). |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress WP_Locale::init() WP\_Locale::init()
==================
Sets up the translated strings and object properties.
The method creates the translatable strings for various calendar elements. Which allows for specifying locale specific calendar names and text direction.
File: `wp-includes/class-wp-locale.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale.php/)
```
public function init() {
// The weekdays.
$this->weekday[0] = /* translators: Weekday. */ __( 'Sunday' );
$this->weekday[1] = /* translators: Weekday. */ __( 'Monday' );
$this->weekday[2] = /* translators: Weekday. */ __( 'Tuesday' );
$this->weekday[3] = /* translators: Weekday. */ __( 'Wednesday' );
$this->weekday[4] = /* translators: Weekday. */ __( 'Thursday' );
$this->weekday[5] = /* translators: Weekday. */ __( 'Friday' );
$this->weekday[6] = /* translators: Weekday. */ __( 'Saturday' );
// The first letter of each day.
$this->weekday_initial[ $this->weekday[0] ] = /* translators: One-letter abbreviation of the weekday. */ _x( 'S', 'Sunday initial' );
$this->weekday_initial[ $this->weekday[1] ] = /* translators: One-letter abbreviation of the weekday. */ _x( 'M', 'Monday initial' );
$this->weekday_initial[ $this->weekday[2] ] = /* translators: One-letter abbreviation of the weekday. */ _x( 'T', 'Tuesday initial' );
$this->weekday_initial[ $this->weekday[3] ] = /* translators: One-letter abbreviation of the weekday. */ _x( 'W', 'Wednesday initial' );
$this->weekday_initial[ $this->weekday[4] ] = /* translators: One-letter abbreviation of the weekday. */ _x( 'T', 'Thursday initial' );
$this->weekday_initial[ $this->weekday[5] ] = /* translators: One-letter abbreviation of the weekday. */ _x( 'F', 'Friday initial' );
$this->weekday_initial[ $this->weekday[6] ] = /* translators: One-letter abbreviation of the weekday. */ _x( 'S', 'Saturday initial' );
// Abbreviations for each day.
$this->weekday_abbrev[ $this->weekday[0] ] = /* translators: Three-letter abbreviation of the weekday. */ __( 'Sun' );
$this->weekday_abbrev[ $this->weekday[1] ] = /* translators: Three-letter abbreviation of the weekday. */ __( 'Mon' );
$this->weekday_abbrev[ $this->weekday[2] ] = /* translators: Three-letter abbreviation of the weekday. */ __( 'Tue' );
$this->weekday_abbrev[ $this->weekday[3] ] = /* translators: Three-letter abbreviation of the weekday. */ __( 'Wed' );
$this->weekday_abbrev[ $this->weekday[4] ] = /* translators: Three-letter abbreviation of the weekday. */ __( 'Thu' );
$this->weekday_abbrev[ $this->weekday[5] ] = /* translators: Three-letter abbreviation of the weekday. */ __( 'Fri' );
$this->weekday_abbrev[ $this->weekday[6] ] = /* translators: Three-letter abbreviation of the weekday. */ __( 'Sat' );
// The months.
$this->month['01'] = /* translators: Month name. */ __( 'January' );
$this->month['02'] = /* translators: Month name. */ __( 'February' );
$this->month['03'] = /* translators: Month name. */ __( 'March' );
$this->month['04'] = /* translators: Month name. */ __( 'April' );
$this->month['05'] = /* translators: Month name. */ __( 'May' );
$this->month['06'] = /* translators: Month name. */ __( 'June' );
$this->month['07'] = /* translators: Month name. */ __( 'July' );
$this->month['08'] = /* translators: Month name. */ __( 'August' );
$this->month['09'] = /* translators: Month name. */ __( 'September' );
$this->month['10'] = /* translators: Month name. */ __( 'October' );
$this->month['11'] = /* translators: Month name. */ __( 'November' );
$this->month['12'] = /* translators: Month name. */ __( 'December' );
// The months, genitive.
$this->month_genitive['01'] = /* translators: Month name, genitive. */ _x( 'January', 'genitive' );
$this->month_genitive['02'] = /* translators: Month name, genitive. */ _x( 'February', 'genitive' );
$this->month_genitive['03'] = /* translators: Month name, genitive. */ _x( 'March', 'genitive' );
$this->month_genitive['04'] = /* translators: Month name, genitive. */ _x( 'April', 'genitive' );
$this->month_genitive['05'] = /* translators: Month name, genitive. */ _x( 'May', 'genitive' );
$this->month_genitive['06'] = /* translators: Month name, genitive. */ _x( 'June', 'genitive' );
$this->month_genitive['07'] = /* translators: Month name, genitive. */ _x( 'July', 'genitive' );
$this->month_genitive['08'] = /* translators: Month name, genitive. */ _x( 'August', 'genitive' );
$this->month_genitive['09'] = /* translators: Month name, genitive. */ _x( 'September', 'genitive' );
$this->month_genitive['10'] = /* translators: Month name, genitive. */ _x( 'October', 'genitive' );
$this->month_genitive['11'] = /* translators: Month name, genitive. */ _x( 'November', 'genitive' );
$this->month_genitive['12'] = /* translators: Month name, genitive. */ _x( 'December', 'genitive' );
// Abbreviations for each month.
$this->month_abbrev[ $this->month['01'] ] = /* translators: Three-letter abbreviation of the month. */ _x( 'Jan', 'January abbreviation' );
$this->month_abbrev[ $this->month['02'] ] = /* translators: Three-letter abbreviation of the month. */ _x( 'Feb', 'February abbreviation' );
$this->month_abbrev[ $this->month['03'] ] = /* translators: Three-letter abbreviation of the month. */ _x( 'Mar', 'March abbreviation' );
$this->month_abbrev[ $this->month['04'] ] = /* translators: Three-letter abbreviation of the month. */ _x( 'Apr', 'April abbreviation' );
$this->month_abbrev[ $this->month['05'] ] = /* translators: Three-letter abbreviation of the month. */ _x( 'May', 'May abbreviation' );
$this->month_abbrev[ $this->month['06'] ] = /* translators: Three-letter abbreviation of the month. */ _x( 'Jun', 'June abbreviation' );
$this->month_abbrev[ $this->month['07'] ] = /* translators: Three-letter abbreviation of the month. */ _x( 'Jul', 'July abbreviation' );
$this->month_abbrev[ $this->month['08'] ] = /* translators: Three-letter abbreviation of the month. */ _x( 'Aug', 'August abbreviation' );
$this->month_abbrev[ $this->month['09'] ] = /* translators: Three-letter abbreviation of the month. */ _x( 'Sep', 'September abbreviation' );
$this->month_abbrev[ $this->month['10'] ] = /* translators: Three-letter abbreviation of the month. */ _x( 'Oct', 'October abbreviation' );
$this->month_abbrev[ $this->month['11'] ] = /* translators: Three-letter abbreviation of the month. */ _x( 'Nov', 'November abbreviation' );
$this->month_abbrev[ $this->month['12'] ] = /* translators: Three-letter abbreviation of the month. */ _x( 'Dec', 'December abbreviation' );
// The meridiems.
$this->meridiem['am'] = __( 'am' );
$this->meridiem['pm'] = __( 'pm' );
$this->meridiem['AM'] = __( 'AM' );
$this->meridiem['PM'] = __( 'PM' );
// Numbers formatting.
// See https://www.php.net/number_format
/* translators: $thousands_sep argument for https://www.php.net/number_format, default is ',' */
$thousands_sep = __( 'number_format_thousands_sep' );
// Replace space with a non-breaking space to avoid wrapping.
$thousands_sep = str_replace( ' ', ' ', $thousands_sep );
$this->number_format['thousands_sep'] = ( 'number_format_thousands_sep' === $thousands_sep ) ? ',' : $thousands_sep;
/* translators: $dec_point argument for https://www.php.net/number_format, default is '.' */
$decimal_point = __( 'number_format_decimal_point' );
$this->number_format['decimal_point'] = ( 'number_format_decimal_point' === $decimal_point ) ? '.' : $decimal_point;
/* translators: used between list items, there is a space after the comma */
$this->list_item_separator = __( ', ' );
// Set text direction.
if ( isset( $GLOBALS['text_direction'] ) ) {
$this->text_direction = $GLOBALS['text_direction'];
/* translators: 'rtl' or 'ltr'. This sets the text direction for WordPress. */
} elseif ( 'rtl' === _x( 'ltr', 'text direction' ) ) {
$this->text_direction = 'rtl';
}
}
```
| 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. |
| Used By | Description |
| --- | --- |
| [WP\_Locale::\_\_construct()](__construct) wp-includes/class-wp-locale.php | Constructor which calls helper methods to set up object variables. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Locale::register_globals() WP\_Locale::register\_globals()
===============================
This method has been deprecated. For backward compatibility only instead.
Global variables are deprecated.
For backward compatibility only.
File: `wp-includes/class-wp-locale.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale.php/)
```
public function register_globals() {
$GLOBALS['weekday'] = $this->weekday;
$GLOBALS['weekday_initial'] = $this->weekday_initial;
$GLOBALS['weekday_abbrev'] = $this->weekday_abbrev;
$GLOBALS['month'] = $this->month;
$GLOBALS['month_abbrev'] = $this->month_abbrev;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Locale::\_\_construct()](__construct) wp-includes/class-wp-locale.php | Constructor which calls helper methods to set up object variables. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Locale::_strings_for_pot() WP\_Locale::\_strings\_for\_pot()
=================================
Registers date/time format strings for general POT.
Private, unused method to add some date/time formats translated on wp-admin/options-general.php to the general POT that would otherwise be added to the admin POT.
File: `wp-includes/class-wp-locale.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale.php/)
```
public function _strings_for_pot() {
/* translators: Localized date format, see https://www.php.net/manual/datetime.format.php */
__( 'F j, Y' );
/* translators: Localized time format, see https://www.php.net/manual/datetime.format.php */
__( 'g:i a' );
/* translators: Localized date and time format, see https://www.php.net/manual/datetime.format.php */
__( 'F j, Y g:i a' );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [3.6.0](https://developer.wordpress.org/reference/since/3.6.0/) | Introduced. |
| programming_docs |
wordpress WP_Locale::get_month( string|int $month_number ): string WP\_Locale::get\_month( string|int $month\_number ): string
===========================================================
Retrieves the full translated month by month number.
The $month\_number parameter has to be a string because it must have the ‘0’ in front of any number that is less than 10. Starts from ’01’ and ends at ’12’.
You can use an integer instead and it will add the ‘0’ before the numbers less than 10 for you.
`$month_number` string|int Required `'01'` through `'12'`. string Translated full month name.
File: `wp-includes/class-wp-locale.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale.php/)
```
public function get_month( $month_number ) {
return $this->month[ zeroise( $month_number, 2 ) ];
}
```
| Uses | Description |
| --- | --- |
| [zeroise()](../../functions/zeroise) wp-includes/formatting.php | Add leading zeros when necessary. |
| Used By | Description |
| --- | --- |
| [wp\_date()](../../functions/wp_date) wp-includes/functions.php | Retrieves the date, in localized format. |
| [WP\_Customize\_Date\_Time\_Control::get\_month\_choices()](../wp_customize_date_time_control/get_month_choices) wp-includes/customize/class-wp-customize-date-time-control.php | Generate options for the month Select. |
| [export\_date\_options()](../../functions/export_date_options) wp-admin/export.php | Create the date options fields for exporting a given post type. |
| [WP\_List\_Table::months\_dropdown()](../wp_list_table/months_dropdown) wp-admin/includes/class-wp-list-table.php | Displays a dropdown for filtering items in the list table by month. |
| [touch\_time()](../../functions/touch_time) wp-admin/includes/template.php | Prints out HTML form date elements for editing post or comment publish date. |
| [media\_upload\_library\_form()](../../functions/media_upload_library_form) wp-admin/includes/media.php | Outputs the legacy media upload form for the media library. |
| [single\_month\_title()](../../functions/single_month_title) wp-includes/general-template.php | Displays or retrieves page title for post archive based on date. |
| [wp\_get\_archives()](../../functions/wp_get_archives) wp-includes/general-template.php | Displays archive links based on type and format. |
| [get\_calendar()](../../functions/get_calendar) wp-includes/general-template.php | Displays calendar with days that have posts as links. |
| [wp\_title()](../../functions/wp_title) wp-includes/general-template.php | Displays or retrieves page title for all areas of blog. |
| [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. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Locale::get_weekday( int $weekday_number ): string WP\_Locale::get\_weekday( int $weekday\_number ): string
========================================================
Retrieves the full translated weekday word.
Week starts on translated Sunday and can be fetched by using 0 (zero). So the week starts with 0 (zero) and ends on Saturday with is fetched by using 6 (six).
`$weekday_number` int Required 0 for Sunday through 6 Saturday. string Full translated weekday.
File: `wp-includes/class-wp-locale.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale.php/)
```
public function get_weekday( $weekday_number ) {
return $this->weekday[ $weekday_number ];
}
```
| Used By | Description |
| --- | --- |
| [wp\_date()](../../functions/wp_date) wp-includes/functions.php | Retrieves the date, in localized format. |
| [the\_weekday()](../../functions/the_weekday) wp-includes/general-template.php | Displays the weekday on which the post was written. |
| [the\_weekday\_date()](../../functions/the_weekday_date) wp-includes/general-template.php | Displays the weekday on which the post was written. |
| [get\_calendar()](../../functions/get_calendar) wp-includes/general-template.php | Displays calendar with days that have posts as links. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Locale::get_month_abbrev( string $month_name ): string WP\_Locale::get\_month\_abbrev( string $month\_name ): string
=============================================================
Retrieves translated version of month abbreviation string.
The $month\_name parameter is expected to be the translated or translatable version of the month.
`$month_name` string Required Translated month to get abbreviated version. string Translated abbreviated month.
File: `wp-includes/class-wp-locale.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale.php/)
```
public function get_month_abbrev( $month_name ) {
return $this->month_abbrev[ $month_name ];
}
```
| Used By | Description |
| --- | --- |
| [wp\_date()](../../functions/wp_date) wp-includes/functions.php | Retrieves the date, in localized format. |
| [WP\_Customize\_Date\_Time\_Control::get\_month\_choices()](../wp_customize_date_time_control/get_month_choices) wp-includes/customize/class-wp-customize-date-time-control.php | Generate options for the month Select. |
| [touch\_time()](../../functions/touch_time) wp-admin/includes/template.php | Prints out HTML form date elements for editing post or comment publish date. |
| [get\_calendar()](../../functions/get_calendar) wp-includes/general-template.php | Displays calendar with days that have posts as links. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Locale::get_weekday_abbrev( string $weekday_name ): string WP\_Locale::get\_weekday\_abbrev( string $weekday\_name ): string
=================================================================
Retrieves the translated weekday abbreviation.
The weekday abbreviation is retrieved by the translated full weekday word.
`$weekday_name` string Required Full translated weekday word. string Translated weekday abbreviation.
File: `wp-includes/class-wp-locale.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale.php/)
```
public function get_weekday_abbrev( $weekday_name ) {
return $this->weekday_abbrev[ $weekday_name ];
}
```
| Used By | Description |
| --- | --- |
| [wp\_date()](../../functions/wp_date) wp-includes/functions.php | Retrieves the date, in localized format. |
| [get\_calendar()](../../functions/get_calendar) wp-includes/general-template.php | Displays calendar with days that have posts as links. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Locale::get_weekday_initial( string $weekday_name ): string WP\_Locale::get\_weekday\_initial( string $weekday\_name ): string
==================================================================
Retrieves the translated weekday initial.
The weekday initial is retrieved by the translated full weekday word. When translating the weekday initial pay attention to make sure that the starting letter does not conflict.
`$weekday_name` string Required Full translated weekday word. string Translated weekday initial.
File: `wp-includes/class-wp-locale.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale.php/)
```
public function get_weekday_initial( $weekday_name ) {
return $this->weekday_initial[ $weekday_name ];
}
```
| Used By | Description |
| --- | --- |
| [get\_calendar()](../../functions/get_calendar) wp-includes/general-template.php | Displays calendar with days that have posts as links. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Locale::__construct() WP\_Locale::\_\_construct()
===========================
Constructor which calls helper methods to set up object variables.
File: `wp-includes/class-wp-locale.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale.php/)
```
public function __construct() {
$this->init();
$this->register_globals();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Locale::register\_globals()](register_globals) wp-includes/class-wp-locale.php | Global variables are deprecated. |
| [WP\_Locale::init()](init) wp-includes/class-wp-locale.php | Sets up the translated strings and object properties. |
| Used By | Description |
| --- | --- |
| [WP\_Locale\_Switcher::change\_locale()](../wp_locale_switcher/change_locale) wp-includes/class-wp-locale-switcher.php | Changes the site’s locale to the given one. |
| [wp\_load\_translations\_early()](../../functions/wp_load_translations_early) wp-includes/load.php | Attempt an early load of translations. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Locale::get_meridiem( string $meridiem ): string WP\_Locale::get\_meridiem( string $meridiem ): string
=====================================================
Retrieves translated version of meridiem string.
The $meridiem parameter is expected to not be translated.
`$meridiem` string Required Either `'am'`, `'pm'`, `'AM'`, or `'PM'`. Not translated version. string Translated version
File: `wp-includes/class-wp-locale.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale.php/)
```
public function get_meridiem( $meridiem ) {
return $this->meridiem[ $meridiem ];
}
```
| Used By | Description |
| --- | --- |
| [wp\_date()](../../functions/wp_date) wp-includes/functions.php | Retrieves the date, in localized format. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress Requests_IDNAEncoder::punycode_encode( string $input ): string Requests\_IDNAEncoder::punycode\_encode( string $input ): string
================================================================
RFC3492-compliant encoder
`$input` string Required UTF-8 encoded string to encode string Punycode-encoded string
File: `wp-includes/Requests/IDNAEncoder.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/idnaencoder.php/)
```
public static function punycode_encode($input) {
$output = '';
// let n = initial_n
$n = self::BOOTSTRAP_INITIAL_N;
// let delta = 0
$delta = 0;
// let bias = initial_bias
$bias = self::BOOTSTRAP_INITIAL_BIAS;
// let h = b = the number of basic code points in the input
$h = 0;
$b = 0; // see loop
// copy them to the output in order
$codepoints = self::utf8_to_codepoints($input);
$extended = array();
foreach ($codepoints as $char) {
if ($char < 128) {
// Character is valid ASCII
// TODO: this should also check if it's valid for a URL
$output .= chr($char);
$h++;
}
// Check if the character is non-ASCII, but below initial n
// This never occurs for Punycode, so ignore in coverage
// @codeCoverageIgnoreStart
elseif ($char < $n) {
throw new Requests_Exception('Invalid character', 'idna.character_outside_domain', $char);
}
// @codeCoverageIgnoreEnd
else {
$extended[$char] = true;
}
}
$extended = array_keys($extended);
sort($extended);
$b = $h;
// [copy them] followed by a delimiter if b > 0
if (strlen($output) > 0) {
$output .= '-';
}
// {if the input contains a non-basic code point < n then fail}
// while h < length(input) do begin
$codepointcount = count($codepoints);
while ($h < $codepointcount) {
// let m = the minimum code point >= n in the input
$m = array_shift($extended);
//printf('next code point to insert is %s' . PHP_EOL, dechex($m));
// let delta = delta + (m - n) * (h + 1), fail on overflow
$delta += ($m - $n) * ($h + 1);
// let n = m
$n = $m;
// for each code point c in the input (in order) do begin
for ($num = 0; $num < $codepointcount; $num++) {
$c = $codepoints[$num];
// if c < n then increment delta, fail on overflow
if ($c < $n) {
$delta++;
}
// if c == n then begin
elseif ($c === $n) {
// let q = delta
$q = $delta;
// for k = base to infinity in steps of base do begin
for ($k = self::BOOTSTRAP_BASE; ; $k += self::BOOTSTRAP_BASE) {
// let t = tmin if k <= bias {+ tmin}, or
// tmax if k >= bias + tmax, or k - bias otherwise
if ($k <= ($bias + self::BOOTSTRAP_TMIN)) {
$t = self::BOOTSTRAP_TMIN;
}
elseif ($k >= ($bias + self::BOOTSTRAP_TMAX)) {
$t = self::BOOTSTRAP_TMAX;
}
else {
$t = $k - $bias;
}
// if q < t then break
if ($q < $t) {
break;
}
// output the code point for digit t + ((q - t) mod (base - t))
$digit = $t + (($q - $t) % (self::BOOTSTRAP_BASE - $t));
$output .= self::digit_to_char($digit);
// let q = (q - t) div (base - t)
$q = floor(($q - $t) / (self::BOOTSTRAP_BASE - $t));
} // end
// output the code point for digit q
$output .= self::digit_to_char($q);
// let bias = adapt(delta, h + 1, test h equals b?)
$bias = self::adapt($delta, $h + 1, $h === $b);
// let delta = 0
$delta = 0;
// increment h
$h++;
} // end
} // end
// increment delta and n
$delta++;
$n++;
} // end
return $output;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
| [Requests\_IDNAEncoder::utf8\_to\_codepoints()](utf8_to_codepoints) wp-includes/Requests/IDNAEncoder.php | Convert a UTF-8 string to a UCS-4 codepoint array |
| [Requests\_IDNAEncoder::digit\_to\_char()](digit_to_char) wp-includes/Requests/IDNAEncoder.php | Convert a digit to its respective character |
| [Requests\_IDNAEncoder::adapt()](adapt) wp-includes/Requests/IDNAEncoder.php | Adapt the bias |
| Used By | Description |
| --- | --- |
| [Requests\_IDNAEncoder::to\_ascii()](to_ascii) wp-includes/Requests/IDNAEncoder.php | Convert a UTF-8 string to an ASCII string using Punycode |
wordpress Requests_IDNAEncoder::is_ascii( string $string ): bool Requests\_IDNAEncoder::is\_ascii( string $string ): bool
========================================================
Check whether a given string contains only ASCII characters
`$string` string Required bool Is the string ASCII-only?
File: `wp-includes/Requests/IDNAEncoder.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/idnaencoder.php/)
```
protected static function is_ascii($string) {
return (preg_match('/(?:[^\x00-\x7F])/', $string) !== 1);
}
```
| Used By | Description |
| --- | --- |
| [Requests\_IDNAEncoder::to\_ascii()](to_ascii) wp-includes/Requests/IDNAEncoder.php | Convert a UTF-8 string to an ASCII string using Punycode |
wordpress Requests_IDNAEncoder::nameprep( string $string ): string Requests\_IDNAEncoder::nameprep( string $string ): string
=========================================================
Prepare a string for use as an IDNA name
`$string` string Required string Prepared string
File: `wp-includes/Requests/IDNAEncoder.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/idnaencoder.php/)
```
protected static function nameprep($string) {
return $string;
}
```
| Used By | Description |
| --- | --- |
| [Requests\_IDNAEncoder::to\_ascii()](to_ascii) wp-includes/Requests/IDNAEncoder.php | Convert a UTF-8 string to an ASCII string using Punycode |
wordpress Requests_IDNAEncoder::digit_to_char( int $digit ): string Requests\_IDNAEncoder::digit\_to\_char( int $digit ): string
============================================================
Convert a digit to its respective character
* <https://tools.ietf.org/html/rfc3492#section-5>
`$digit` int Required Digit in the range 0-35 string Single character corresponding to digit
File: `wp-includes/Requests/IDNAEncoder.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/idnaencoder.php/)
```
protected static function digit_to_char($digit) {
// @codeCoverageIgnoreStart
// As far as I know, this never happens, but still good to be sure.
if ($digit < 0 || $digit > 35) {
throw new Requests_Exception(sprintf('Invalid digit %d', $digit), 'idna.invalid_digit', $digit);
}
// @codeCoverageIgnoreEnd
$digits = 'abcdefghijklmnopqrstuvwxyz0123456789';
return substr($digits, $digit, 1);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
| Used By | Description |
| --- | --- |
| [Requests\_IDNAEncoder::punycode\_encode()](punycode_encode) wp-includes/Requests/IDNAEncoder.php | RFC3492-compliant encoder |
wordpress Requests_IDNAEncoder::to_ascii( string $string ): string Requests\_IDNAEncoder::to\_ascii( string $string ): string
==========================================================
Convert a UTF-8 string to an ASCII string using Punycode
`$string` string Required ASCII or UTF-8 string (max length 64 characters) string ASCII string
File: `wp-includes/Requests/IDNAEncoder.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/idnaencoder.php/)
```
public static function to_ascii($string) {
// Step 1: Check if the string is already ASCII
if (self::is_ascii($string)) {
// Skip to step 7
if (strlen($string) < 64) {
return $string;
}
throw new Requests_Exception('Provided string is too long', 'idna.provided_too_long', $string);
}
// Step 2: nameprep
$string = self::nameprep($string);
// Step 3: UseSTD3ASCIIRules is false, continue
// Step 4: Check if it's ASCII now
if (self::is_ascii($string)) {
// Skip to step 7
if (strlen($string) < 64) {
return $string;
}
throw new Requests_Exception('Prepared string is too long', 'idna.prepared_too_long', $string);
}
// Step 5: Check ACE prefix
if (strpos($string, self::ACE_PREFIX) === 0) {
throw new Requests_Exception('Provided string begins with ACE prefix', 'idna.provided_is_prefixed', $string);
}
// Step 6: Encode with Punycode
$string = self::punycode_encode($string);
// Step 7: Prepend ACE prefix
$string = self::ACE_PREFIX . $string;
// Step 8: Check size
if (strlen($string) < 64) {
return $string;
}
throw new Requests_Exception('Encoded string is too long', 'idna.encoded_too_long', $string);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
| [Requests\_IDNAEncoder::nameprep()](nameprep) wp-includes/Requests/IDNAEncoder.php | Prepare a string for use as an IDNA name |
| [Requests\_IDNAEncoder::punycode\_encode()](punycode_encode) wp-includes/Requests/IDNAEncoder.php | RFC3492-compliant encoder |
| [Requests\_IDNAEncoder::is\_ascii()](is_ascii) wp-includes/Requests/IDNAEncoder.php | Check whether a given string contains only ASCII characters |
| Used By | Description |
| --- | --- |
| [Requests\_IDNAEncoder::encode()](encode) wp-includes/Requests/IDNAEncoder.php | Encode a hostname using Punycode |
| programming_docs |
wordpress Requests_IDNAEncoder::adapt( int $delta, int $numpoints, bool $firsttime ): int Requests\_IDNAEncoder::adapt( int $delta, int $numpoints, bool $firsttime ): int
================================================================================
Adapt the bias
* <https://tools.ietf.org/html/rfc3492#section-6.1>
`$delta` int Required `$numpoints` int Required `$firsttime` bool Required int New bias function adapt(delta,numpoints,firsttime):
File: `wp-includes/Requests/IDNAEncoder.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/idnaencoder.php/)
```
protected static function adapt($delta, $numpoints, $firsttime) {
// if firsttime then let delta = delta div damp
if ($firsttime) {
$delta = floor($delta / self::BOOTSTRAP_DAMP);
}
// else let delta = delta div 2
else {
$delta = floor($delta / 2);
}
// let delta = delta + (delta div numpoints)
$delta += floor($delta / $numpoints);
// let k = 0
$k = 0;
// while delta > ((base - tmin) * tmax) div 2 do begin
$max = floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN) * self::BOOTSTRAP_TMAX) / 2);
while ($delta > $max) {
// let delta = delta div (base - tmin)
$delta = floor($delta / (self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN));
// let k = k + base
$k += self::BOOTSTRAP_BASE;
} // end
// return k + (((base - tmin + 1) * delta) div (delta + skew))
return $k + floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN + 1) * $delta) / ($delta + self::BOOTSTRAP_SKEW));
}
```
| Used By | Description |
| --- | --- |
| [Requests\_IDNAEncoder::punycode\_encode()](punycode_encode) wp-includes/Requests/IDNAEncoder.php | RFC3492-compliant encoder |
wordpress Requests_IDNAEncoder::encode( string $string ): string Requests\_IDNAEncoder::encode( string $string ): string
=======================================================
Encode a hostname using Punycode
`$string` string Required Hostname string Punycode-encoded hostname
File: `wp-includes/Requests/IDNAEncoder.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/idnaencoder.php/)
```
public static function encode($string) {
$parts = explode('.', $string);
foreach ($parts as &$part) {
$part = self::to_ascii($part);
}
return implode('.', $parts);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_IDNAEncoder::to\_ascii()](to_ascii) wp-includes/Requests/IDNAEncoder.php | Convert a UTF-8 string to an ASCII string using Punycode |
| Used By | Description |
| --- | --- |
| [Requests::set\_defaults()](../requests/set_defaults) wp-includes/class-requests.php | Set the default values |
wordpress Requests_IDNAEncoder::utf8_to_codepoints( string $input ): array Requests\_IDNAEncoder::utf8\_to\_codepoints( string $input ): array
===================================================================
Convert a UTF-8 string to a UCS-4 codepoint array
Based on [Requests\_IRI::replace\_invalid\_with\_pct\_encoding()](../requests_iri/replace_invalid_with_pct_encoding)
`$input` string Required array Unicode code points
File: `wp-includes/Requests/IDNAEncoder.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/idnaencoder.php/)
```
protected static function utf8_to_codepoints($input) {
$codepoints = array();
// Get number of bytes
$strlen = strlen($input);
// phpcs:ignore Generic.CodeAnalysis.JumbledIncrementer -- This is a deliberate choice.
for ($position = 0; $position < $strlen; $position++) {
$value = ord($input[$position]);
// One byte sequence:
if ((~$value & 0x80) === 0x80) {
$character = $value;
$length = 1;
$remaining = 0;
}
// Two byte sequence:
elseif (($value & 0xE0) === 0xC0) {
$character = ($value & 0x1F) << 6;
$length = 2;
$remaining = 1;
}
// Three byte sequence:
elseif (($value & 0xF0) === 0xE0) {
$character = ($value & 0x0F) << 12;
$length = 3;
$remaining = 2;
}
// Four byte sequence:
elseif (($value & 0xF8) === 0xF0) {
$character = ($value & 0x07) << 18;
$length = 4;
$remaining = 3;
}
// Invalid byte:
else {
throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $value);
}
if ($remaining > 0) {
if ($position + $length > $strlen) {
throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
}
for ($position++; $remaining > 0; $position++) {
$value = ord($input[$position]);
// If it is invalid, count the sequence as invalid and reprocess the current byte:
if (($value & 0xC0) !== 0x80) {
throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
}
--$remaining;
$character |= ($value & 0x3F) << ($remaining * 6);
}
$position--;
}
if (// Non-shortest form sequences are invalid
$length > 1 && $character <= 0x7F
|| $length > 2 && $character <= 0x7FF
|| $length > 3 && $character <= 0xFFFF
// Outside of range of ucschar codepoints
// Noncharacters
|| ($character & 0xFFFE) === 0xFFFE
|| $character >= 0xFDD0 && $character <= 0xFDEF
|| (
// Everything else not in ucschar
$character > 0xD7FF && $character < 0xF900
|| $character < 0x20
|| $character > 0x7E && $character < 0xA0
|| $character > 0xEFFFD
)
) {
throw new Requests_Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
}
$codepoints[] = $character;
}
return $codepoints;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
| Used By | Description |
| --- | --- |
| [Requests\_IDNAEncoder::punycode\_encode()](punycode_encode) wp-includes/Requests/IDNAEncoder.php | RFC3492-compliant encoder |
wordpress WP_Customize_Sidebar_Section::json(): array WP\_Customize\_Sidebar\_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/customize/class-wp-customize-sidebar-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-sidebar-section.php/)
```
public function json() {
$json = parent::json();
$json['sidebarId'] = $this->sidebar_id;
return $json;
}
```
| 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.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Sidebar_Section::active_callback(): bool WP\_Customize\_Sidebar\_Section::active\_callback(): bool
=========================================================
Whether the current sidebar is rendered on the page.
bool Whether sidebar is rendered.
File: `wp-includes/customize/class-wp-customize-sidebar-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-sidebar-section.php/)
```
public function active_callback() {
return $this->manager->widgets->is_sidebar_rendered( $this->sidebar_id );
}
```
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress Requests_Cookie::uri_matches( Requests_IRI $uri ): boolean Requests\_Cookie::uri\_matches( Requests\_IRI $uri ): boolean
=============================================================
Check if a cookie is valid for a given URI
`$uri` [Requests\_IRI](../requests_iri) Required URI to check boolean Whether the cookie is valid for the given URI
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public function uri_matches(Requests_IRI $uri) {
if (!$this->domain_matches($uri->host)) {
return false;
}
if (!$this->path_matches($uri->path)) {
return false;
}
return empty($this->attributes['secure']) || $uri->scheme === 'https';
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Cookie::domain\_matches()](domain_matches) wp-includes/Requests/Cookie.php | Check if a cookie is valid for a given domain |
| [Requests\_Cookie::path\_matches()](path_matches) wp-includes/Requests/Cookie.php | Check if a cookie is valid for a given path |
wordpress Requests_Cookie::domain_matches( string $string ): boolean Requests\_Cookie::domain\_matches( string $string ): boolean
============================================================
Check if a cookie is valid for a given domain
`$string` string Required Domain to check boolean Whether the cookie is valid for the given domain
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public function domain_matches($string) {
if (!isset($this->attributes['domain'])) {
// Cookies created manually; cookies created by Requests will set
// the domain to the requested domain
return true;
}
$domain_string = $this->attributes['domain'];
if ($domain_string === $string) {
// The domain string and the string are identical.
return true;
}
// If the cookie is marked as host-only and we don't have an exact
// match, reject the cookie
if ($this->flags['host-only'] === true) {
return false;
}
if (strlen($string) <= strlen($domain_string)) {
// For obvious reasons, the string cannot be a suffix if the domain
// is shorter than the domain string
return false;
}
if (substr($string, -1 * strlen($domain_string)) !== $domain_string) {
// The domain string should be a suffix of the string.
return false;
}
$prefix = substr($string, 0, strlen($string) - strlen($domain_string));
if (substr($prefix, -1) !== '.') {
// The last character of the string that is not included in the
// domain string should be a %x2E (".") character.
return false;
}
// The string should be a host name (i.e., not an IP address).
return !preg_match('#^(.+\.)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $string);
}
```
| Used By | Description |
| --- | --- |
| [Requests\_Cookie::uri\_matches()](uri_matches) wp-includes/Requests/Cookie.php | Check if a cookie is valid for a given URI |
wordpress Requests_Cookie::is_expired(): boolean Requests\_Cookie::is\_expired(): boolean
========================================
Check if a cookie is expired.
Checks the age against $this->reference\_time to determine if the cookie is expired.
boolean True if expired, false if time is valid.
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public function is_expired() {
// RFC6265, s. 4.1.2.2:
// If a cookie has both the Max-Age and the Expires attribute, the Max-
// Age attribute has precedence and controls the expiration date of the
// cookie.
if (isset($this->attributes['max-age'])) {
$max_age = $this->attributes['max-age'];
return $max_age < $this->reference_time;
}
if (isset($this->attributes['expires'])) {
$expires = $this->attributes['expires'];
return $expires < $this->reference_time;
}
return false;
}
```
wordpress Requests_Cookie::format_for_header(): string Requests\_Cookie::format\_for\_header(): string
===============================================
Format a cookie for a Cookie header
This is used when sending cookies to a server.
string Cookie formatted for Cookie header
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public function format_for_header() {
return sprintf('%s=%s', $this->name, $this->value);
}
```
| Used By | Description |
| --- | --- |
| [Requests\_Cookie::formatForHeader()](formatforheader) wp-includes/Requests/Cookie.php | Format a cookie for a Cookie header |
| [Requests\_Cookie::format\_for\_set\_cookie()](format_for_set_cookie) wp-includes/Requests/Cookie.php | Format a cookie for a Set-Cookie header |
wordpress Requests_Cookie::formatForHeader(): string Requests\_Cookie::formatForHeader(): string
===========================================
This method has been deprecated. Use [Requests\_Cookie::format\_for\_header()](format_for_header) instead.
Format a cookie for a Cookie header
string
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public function formatForHeader() {
return $this->format_for_header();
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Cookie::format\_for\_header()](format_for_header) wp-includes/Requests/Cookie.php | Format a cookie for a Cookie header |
wordpress Requests_Cookie::normalize_attribute( string $name, string|boolean $value ): mixed Requests\_Cookie::normalize\_attribute( string $name, string|boolean $value ): mixed
====================================================================================
Parse an individual cookie attribute
Handles parsing individual attributes from the cookie values.
`$name` string Required Attribute name `$value` string|boolean Required Attribute value (string value, or true if empty/flag) mixed Value if available, or null if the attribute value is invalid (and should be skipped)
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
protected function normalize_attribute($name, $value) {
switch (strtolower($name)) {
case 'expires':
// Expiration parsing, as per RFC 6265 section 5.2.1
if (is_int($value)) {
return $value;
}
$expiry_time = strtotime($value);
if ($expiry_time === false) {
return null;
}
return $expiry_time;
case 'max-age':
// Expiration parsing, as per RFC 6265 section 5.2.2
if (is_int($value)) {
return $value;
}
// Check that we have a valid age
if (!preg_match('/^-?\d+$/', $value)) {
return null;
}
$delta_seconds = (int) $value;
if ($delta_seconds <= 0) {
$expiry_time = 0;
}
else {
$expiry_time = $this->reference_time + $delta_seconds;
}
return $expiry_time;
case 'domain':
// Domains are not required as per RFC 6265 section 5.2.3
if (empty($value)) {
return null;
}
// Domain normalization, as per RFC 6265 section 5.2.3
if ($value[0] === '.') {
$value = substr($value, 1);
}
return $value;
default:
return $value;
}
}
```
| Used By | Description |
| --- | --- |
| [Requests\_Cookie::normalize()](normalize) wp-includes/Requests/Cookie.php | Normalize cookie and attributes |
wordpress Requests_Cookie::path_matches( string $request_path ): boolean Requests\_Cookie::path\_matches( string $request\_path ): boolean
=================================================================
Check if a cookie is valid for a given path
From the path-match check in RFC 6265 section 5.1.4
`$request_path` string Required Path to check boolean Whether the cookie is valid for the given path
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public function path_matches($request_path) {
if (empty($request_path)) {
// Normalize empty path to root
$request_path = '/';
}
if (!isset($this->attributes['path'])) {
// Cookies created manually; cookies created by Requests will set
// the path to the requested path
return true;
}
$cookie_path = $this->attributes['path'];
if ($cookie_path === $request_path) {
// The cookie-path and the request-path are identical.
return true;
}
if (strlen($request_path) > strlen($cookie_path) && substr($request_path, 0, strlen($cookie_path)) === $cookie_path) {
if (substr($cookie_path, -1) === '/') {
// The cookie-path is a prefix of the request-path, and the last
// character of the cookie-path is %x2F ("/").
return true;
}
if (substr($request_path, strlen($cookie_path), 1) === '/') {
// The cookie-path is a prefix of the request-path, and the
// first character of the request-path that is not included in
// the cookie-path is a %x2F ("/") character.
return true;
}
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [Requests\_Cookie::uri\_matches()](uri_matches) wp-includes/Requests/Cookie.php | Check if a cookie is valid for a given URI |
wordpress Requests_Cookie::parseFromHeaders( $headers ): array Requests\_Cookie::parseFromHeaders( $headers ): array
=====================================================
This method has been deprecated. Use [Requests\_Cookie::parse\_from\_headers()](parse_from_headers) instead.
Parse all Set-Cookie headers from request headers
array
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public static function parseFromHeaders(Requests_Response_Headers $headers) {
return self::parse_from_headers($headers);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Cookie::parse\_from\_headers()](parse_from_headers) wp-includes/Requests/Cookie.php | Parse all Set-Cookie headers from request headers |
wordpress Requests_Cookie::__toString() Requests\_Cookie::\_\_toString()
================================
Get the cookie value
Attributes and other data can be accessed via methods.
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public function __toString() {
return $this->value;
}
```
wordpress Requests_Cookie::format_for_set_cookie(): string Requests\_Cookie::format\_for\_set\_cookie(): string
====================================================
Format a cookie for a Set-Cookie header
This is used when sending cookies to clients. This isn’t really applicable to client-side usage, but might be handy for debugging.
string Cookie formatted for Set-Cookie header
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public function format_for_set_cookie() {
$header_value = $this->format_for_header();
if (!empty($this->attributes)) {
$parts = array();
foreach ($this->attributes as $key => $value) {
// Ignore non-associative attributes
if (is_numeric($key)) {
$parts[] = $value;
}
else {
$parts[] = sprintf('%s=%s', $key, $value);
}
}
$header_value .= '; ' . implode('; ', $parts);
}
return $header_value;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Cookie::format\_for\_header()](format_for_header) wp-includes/Requests/Cookie.php | Format a cookie for a Cookie header |
| Used By | Description |
| --- | --- |
| [Requests\_Cookie::formatForSetCookie()](formatforsetcookie) wp-includes/Requests/Cookie.php | Format a cookie for a Set-Cookie header |
wordpress Requests_Cookie::__construct( string $name, string $value, array|Requests_Utility_CaseInsensitiveDictionary $attributes = array(), $flags = array(), $reference_time = null ) Requests\_Cookie::\_\_construct( string $name, string $value, array|Requests\_Utility\_CaseInsensitiveDictionary $attributes = array(), $flags = array(), $reference\_time = null )
===================================================================================================================================================================================
Create a new cookie object
`$name` string Required `$value` string Required `$attributes` array|[Requests\_Utility\_CaseInsensitiveDictionary](../requests_utility_caseinsensitivedictionary) Optional Associative array of attribute data Default: `array()`
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public function __construct($name, $value, $attributes = array(), $flags = array(), $reference_time = null) {
$this->name = $name;
$this->value = $value;
$this->attributes = $attributes;
$default_flags = array(
'creation' => time(),
'last-access' => time(),
'persistent' => false,
'host-only' => true,
);
$this->flags = array_merge($default_flags, $flags);
$this->reference_time = time();
if ($reference_time !== null) {
$this->reference_time = $reference_time;
}
$this->normalize();
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Cookie::normalize()](normalize) wp-includes/Requests/Cookie.php | Normalize cookie and attributes |
| Used By | Description |
| --- | --- |
| [Requests\_Cookie::parse()](parse) wp-includes/Requests/Cookie.php | Parse a cookie string into a cookie object |
| [WP\_Http::normalize\_cookies()](../wp_http/normalize_cookies) wp-includes/class-wp-http.php | Normalizes cookies for using in Requests. |
| programming_docs |
wordpress Requests_Cookie::formatForSetCookie(): string Requests\_Cookie::formatForSetCookie(): string
==============================================
This method has been deprecated. Use [Requests\_Cookie::format\_for\_set\_cookie()](format_for_set_cookie) instead.
Format a cookie for a Set-Cookie header
string
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public function formatForSetCookie() {
return $this->format_for_set_cookie();
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Cookie::format\_for\_set\_cookie()](format_for_set_cookie) wp-includes/Requests/Cookie.php | Format a cookie for a Set-Cookie header |
wordpress Requests_Cookie::parse( $string, $name = '', $reference_time = null ): Requests_Cookie Requests\_Cookie::parse( $string, $name = '', $reference\_time = null ): Requests\_Cookie
=========================================================================================
Parse a cookie string into a cookie object
Based on Mozilla’s parsing code in Firefox and related projects, which is an intentional deviation from RFC 2109 and RFC 2616. RFC 6265 specifies some of this handling, but not in a thorough manner.
Cookie header value (from a Set-Cookie header) [Requests\_Cookie](../requests_cookie) Parsed cookie object
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public static function parse($string, $name = '', $reference_time = null) {
$parts = explode(';', $string);
$kvparts = array_shift($parts);
if (!empty($name)) {
$value = $string;
}
elseif (strpos($kvparts, '=') === false) {
// Some sites might only have a value without the equals separator.
// Deviate from RFC 6265 and pretend it was actually a blank name
// (`=foo`)
//
// https://bugzilla.mozilla.org/show_bug.cgi?id=169091
$name = '';
$value = $kvparts;
}
else {
list($name, $value) = explode('=', $kvparts, 2);
}
$name = trim($name);
$value = trim($value);
// Attribute key are handled case-insensitively
$attributes = new Requests_Utility_CaseInsensitiveDictionary();
if (!empty($parts)) {
foreach ($parts as $part) {
if (strpos($part, '=') === false) {
$part_key = $part;
$part_value = true;
}
else {
list($part_key, $part_value) = explode('=', $part, 2);
$part_value = trim($part_value);
}
$part_key = trim($part_key);
$attributes[$part_key] = $part_value;
}
}
return new Requests_Cookie($name, $value, $attributes, array(), $reference_time);
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Utility\_CaseInsensitiveDictionary::\_\_construct()](../requests_utility_caseinsensitivedictionary/__construct) wp-includes/Requests/Utility/CaseInsensitiveDictionary.php | Creates a case insensitive dictionary. |
| [Requests\_Cookie::\_\_construct()](__construct) wp-includes/Requests/Cookie.php | Create a new cookie object |
| Used By | Description |
| --- | --- |
| [Requests\_Cookie::parse\_from\_headers()](parse_from_headers) wp-includes/Requests/Cookie.php | Parse all Set-Cookie headers from request headers |
| [Requests\_Cookie\_Jar::normalize\_cookie()](../requests_cookie_jar/normalize_cookie) wp-includes/Requests/Cookie/Jar.php | Normalise cookie data into a [Requests\_Cookie](../requests_cookie) |
wordpress Requests_Cookie::normalize(): boolean Requests\_Cookie::normalize(): boolean
======================================
Normalize cookie and attributes
boolean Whether the cookie was successfully normalized
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public function normalize() {
foreach ($this->attributes as $key => $value) {
$orig_value = $value;
$value = $this->normalize_attribute($key, $value);
if ($value === null) {
unset($this->attributes[$key]);
continue;
}
if ($value !== $orig_value) {
$this->attributes[$key] = $value;
}
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Cookie::normalize\_attribute()](normalize_attribute) wp-includes/Requests/Cookie.php | Parse an individual cookie attribute |
| Used By | Description |
| --- | --- |
| [Requests\_Cookie::\_\_construct()](__construct) wp-includes/Requests/Cookie.php | Create a new cookie object |
wordpress Requests_Cookie::parse_from_headers( Requests_Response_Headers $headers, Requests_IRI|null $origin = null, int|null $time = null ): array Requests\_Cookie::parse\_from\_headers( Requests\_Response\_Headers $headers, Requests\_IRI|null $origin = null, int|null $time = null ): array
===============================================================================================================================================
Parse all Set-Cookie headers from request headers
`$headers` [Requests\_Response\_Headers](../requests_response_headers) Required Headers to parse from `$origin` [Requests\_IRI](../requests_iri)|null Optional URI for comparing cookie origins Default: `null`
`$time` int|null Optional Reference time for expiration calculation Default: `null`
array
File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/)
```
public static function parse_from_headers(Requests_Response_Headers $headers, Requests_IRI $origin = null, $time = null) {
$cookie_headers = $headers->getValues('Set-Cookie');
if (empty($cookie_headers)) {
return array();
}
$cookies = array();
foreach ($cookie_headers as $header) {
$parsed = self::parse($header, '', $time);
// Default domain/path attributes
if (empty($parsed->attributes['domain']) && !empty($origin)) {
$parsed->attributes['domain'] = $origin->host;
$parsed->flags['host-only'] = true;
}
else {
$parsed->flags['host-only'] = false;
}
$path_is_valid = (!empty($parsed->attributes['path']) && $parsed->attributes['path'][0] === '/');
if (!$path_is_valid && !empty($origin)) {
$path = $origin->path;
// Default path normalization as per RFC 6265 section 5.1.4
if (substr($path, 0, 1) !== '/') {
// If the uri-path is empty or if the first character of
// the uri-path is not a %x2F ("/") character, output
// %x2F ("/") and skip the remaining steps.
$path = '/';
}
elseif (substr_count($path, '/') === 1) {
// If the uri-path contains no more than one %x2F ("/")
// character, output %x2F ("/") and skip the remaining
// step.
$path = '/';
}
else {
// Output the characters of the uri-path from the first
// character up to, but not including, the right-most
// %x2F ("/").
$path = substr($path, 0, strrpos($path, '/'));
}
$parsed->attributes['path'] = $path;
}
// Reject invalid cookie domains
if (!empty($origin) && !$parsed->domain_matches($origin->host)) {
continue;
}
$cookies[$parsed->name] = $parsed;
}
return $cookies;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Cookie::parse()](parse) wp-includes/Requests/Cookie.php | Parse a cookie string into a cookie object |
| Used By | Description |
| --- | --- |
| [Requests\_Cookie::parseFromHeaders()](parsefromheaders) wp-includes/Requests/Cookie.php | Parse all Set-Cookie headers from request headers |
| [Requests\_Cookie\_Jar::before\_redirect\_check()](../requests_cookie_jar/before_redirect_check) wp-includes/Requests/Cookie/Jar.php | Parse all cookies from a response and attach them to the response |
wordpress WP_Users_List_Table::single_row( WP_User $user_object, string $style = '', string $role = '', int $numposts ): string WP\_Users\_List\_Table::single\_row( WP\_User $user\_object, string $style = '', string $role = '', int $numposts ): string
===========================================================================================================================
Generate HTML for a single row on the users.php admin panel.
`$user_object` [WP\_User](../wp_user) Required The current user object. `$style` string Optional Deprecated. Not used. Default: `''`
`$role` string Optional Deprecated. Not used. Default: `''`
`$numposts` int Optional Post count to display for this user. Defaults to zero, as in, a new user has made zero posts. string Output for a single row.
File: `wp-admin/includes/class-wp-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
public function single_row( $user_object, $style = '', $role = '', $numposts = 0 ) {
if ( ! ( $user_object instanceof WP_User ) ) {
$user_object = get_userdata( (int) $user_object );
}
$user_object->filter = 'display';
$email = $user_object->user_email;
if ( $this->is_site_users ) {
$url = "site-users.php?id={$this->site_id}&";
} else {
$url = 'users.php?';
}
$user_roles = $this->get_role_list( $user_object );
// Set up the hover actions for this user.
$actions = array();
$checkbox = '';
$super_admin = '';
if ( is_multisite() && current_user_can( 'manage_network_users' ) ) {
if ( in_array( $user_object->user_login, get_super_admins(), true ) ) {
$super_admin = ' — ' . __( 'Super Admin' );
}
}
// Check if the user for this row is editable.
if ( current_user_can( 'list_users' ) ) {
// Set up the user editing link.
$edit_link = esc_url(
add_query_arg(
'wp_http_referer',
urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ),
get_edit_user_link( $user_object->ID )
)
);
if ( current_user_can( 'edit_user', $user_object->ID ) ) {
$edit = "<strong><a href=\"{$edit_link}\">{$user_object->user_login}</a>{$super_admin}</strong><br />";
$actions['edit'] = '<a href="' . $edit_link . '">' . __( 'Edit' ) . '</a>';
} else {
$edit = "<strong>{$user_object->user_login}{$super_admin}</strong><br />";
}
if ( ! is_multisite()
&& get_current_user_id() !== $user_object->ID
&& current_user_can( 'delete_user', $user_object->ID )
) {
$actions['delete'] = "<a class='submitdelete' href='" . wp_nonce_url( "users.php?action=delete&user=$user_object->ID", 'bulk-users' ) . "'>" . __( 'Delete' ) . '</a>';
}
if ( is_multisite()
&& current_user_can( 'remove_user', $user_object->ID )
) {
$actions['remove'] = "<a class='submitdelete' href='" . wp_nonce_url( $url . "action=remove&user=$user_object->ID", 'bulk-users' ) . "'>" . __( 'Remove' ) . '</a>';
}
// Add a link to the user's author archive, if not empty.
$author_posts_url = get_author_posts_url( $user_object->ID );
if ( $author_posts_url ) {
$actions['view'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
esc_url( $author_posts_url ),
/* translators: %s: Author's display name. */
esc_attr( sprintf( __( 'View posts by %s' ), $user_object->display_name ) ),
__( 'View' )
);
}
// Add a link to send the user a reset password link by email.
if ( get_current_user_id() !== $user_object->ID
&& current_user_can( 'edit_user', $user_object->ID )
) {
$actions['resetpassword'] = "<a class='resetpassword' href='" . wp_nonce_url( "users.php?action=resetpassword&users=$user_object->ID", 'bulk-users' ) . "'>" . __( 'Send password reset' ) . '</a>';
}
/**
* Filters the action links displayed under each user in the Users list table.
*
* @since 2.8.0
*
* @param string[] $actions An array of action links to be displayed.
* Default 'Edit', 'Delete' for single site, and
* 'Edit', 'Remove' for Multisite.
* @param WP_User $user_object WP_User object for the currently listed user.
*/
$actions = apply_filters( 'user_row_actions', $actions, $user_object );
// Role classes.
$role_classes = esc_attr( implode( ' ', array_keys( $user_roles ) ) );
// Set up the checkbox (because the user is editable, otherwise it's empty).
$checkbox = sprintf(
'<label class="screen-reader-text" for="user_%1$s">%2$s</label>' .
'<input type="checkbox" name="users[]" id="user_%1$s" class="%3$s" value="%1$s" />',
$user_object->ID,
/* translators: %s: User login. */
sprintf( __( 'Select %s' ), $user_object->user_login ),
$role_classes
);
} else {
$edit = "<strong>{$user_object->user_login}{$super_admin}</strong>";
}
$avatar = get_avatar( $user_object->ID, 32 );
// Comma-separated list of user roles.
$roles_list = implode( ', ', $user_roles );
$row = "<tr id='user-$user_object->ID'>";
list( $columns, $hidden, $sortable, $primary ) = $this->get_column_info();
foreach ( $columns as $column_name => $column_display_name ) {
$classes = "$column_name column-$column_name";
if ( $primary === $column_name ) {
$classes .= ' has-row-actions column-primary';
}
if ( 'posts' === $column_name ) {
$classes .= ' num'; // Special case for that column.
}
if ( in_array( $column_name, $hidden, true ) ) {
$classes .= ' hidden';
}
$data = 'data-colname="' . esc_attr( wp_strip_all_tags( $column_display_name ) ) . '"';
$attributes = "class='$classes' $data";
if ( 'cb' === $column_name ) {
$row .= "<th scope='row' class='check-column'>$checkbox</th>";
} else {
$row .= "<td $attributes>";
switch ( $column_name ) {
case 'username':
$row .= "$avatar $edit";
break;
case 'name':
if ( $user_object->first_name && $user_object->last_name ) {
$row .= sprintf(
/* translators: 1: User's first name, 2: Last name. */
_x( '%1$s %2$s', 'Display name based on first name and last name' ),
$user_object->first_name,
$user_object->last_name
);
} elseif ( $user_object->first_name ) {
$row .= $user_object->first_name;
} elseif ( $user_object->last_name ) {
$row .= $user_object->last_name;
} else {
$row .= sprintf(
'<span aria-hidden="true">—</span><span class="screen-reader-text">%s</span>',
_x( 'Unknown', 'name' )
);
}
break;
case 'email':
$row .= "<a href='" . esc_url( "mailto:$email" ) . "'>$email</a>";
break;
case 'role':
$row .= esc_html( $roles_list );
break;
case 'posts':
if ( $numposts > 0 ) {
$row .= sprintf(
'<a href="%s" class="edit"><span aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></a>',
"edit.php?author={$user_object->ID}",
$numposts,
sprintf(
/* translators: %s: Number of posts. */
_n( '%s post by this author', '%s posts by this author', $numposts ),
number_format_i18n( $numposts )
)
);
} else {
$row .= 0;
}
break;
default:
/**
* Filters the display output of custom columns in the Users list table.
*
* @since 2.8.0
*
* @param string $output Custom column output. Default empty.
* @param string $column_name Column name.
* @param int $user_id ID of the currently-listed user.
*/
$row .= apply_filters( 'manage_users_custom_column', '', $column_name, $user_object->ID );
}
if ( $primary === $column_name ) {
$row .= $this->row_actions( $actions );
}
$row .= '</td>';
}
}
$row .= '</tr>';
return $row;
}
```
[apply\_filters( 'manage\_users\_custom\_column', string $output, string $column\_name, int $user\_id )](../../hooks/manage_users_custom_column)
Filters the display output of custom columns in the Users list table.
[apply\_filters( 'user\_row\_actions', string[] $actions, WP\_User $user\_object )](../../hooks/user_row_actions)
Filters the action links displayed under each user in the Users list table.
| Uses | Description |
| --- | --- |
| [WP\_Users\_List\_Table::get\_role\_list()](get_role_list) wp-admin/includes/class-wp-users-list-table.php | Returns an array of translated user role names for a given user object. |
| [wp\_strip\_all\_tags()](../../functions/wp_strip_all_tags) wp-includes/formatting.php | Properly strips all HTML tags including script and style |
| [get\_edit\_user\_link()](../../functions/get_edit_user_link) wp-includes/link-template.php | Retrieves the edit user link. |
| [get\_avatar()](../../functions/get_avatar) wp-includes/pluggable.php | Retrieves the avatar `<img>` tag for a user, email address, MD5 hash, comment, or post. |
| [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. |
| [get\_super\_admins()](../../functions/get_super_admins) wp-includes/capabilities.php | Retrieves a list of super admins. |
| [\_n()](../../functions/_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [\_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. |
| [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. |
| [\_\_()](../../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. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [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. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| [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. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| Used By | Description |
| --- | --- |
| [WP\_Users\_List\_Table::display\_rows()](display_rows) wp-admin/includes/class-wp-users-list-table.php | Generate the list table rows. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | The `$role` parameter was deprecated. |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | The `$style` parameter was deprecated. |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Users_List_Table::extra_tablenav( string $which ) WP\_Users\_List\_Table::extra\_tablenav( string $which )
========================================================
Output the controls to allow user roles to be changed in bulk.
`$which` string Required Whether this is being invoked above ("top") or below the table ("bottom"). File: `wp-admin/includes/class-wp-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
protected function extra_tablenav( $which ) {
$id = 'bottom' === $which ? 'new_role2' : 'new_role';
$button_id = 'bottom' === $which ? 'changeit2' : 'changeit';
?>
<div class="alignleft actions">
<?php if ( current_user_can( 'promote_users' ) && $this->has_items() ) : ?>
<label class="screen-reader-text" for="<?php echo $id; ?>"><?php _e( 'Change role to…' ); ?></label>
<select name="<?php echo $id; ?>" id="<?php echo $id; ?>">
<option value=""><?php _e( 'Change role to…' ); ?></option>
<?php wp_dropdown_roles(); ?>
<option value="none"><?php _e( '— No role for this site —' ); ?></option>
</select>
<?php
submit_button( __( 'Change' ), '', $button_id, false );
endif;
/**
* Fires just before the closing div containing the bulk role-change controls
* in the Users list table.
*
* @since 3.5.0
* @since 4.6.0 The `$which` parameter was added.
*
* @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
*/
do_action( 'restrict_manage_users', $which );
?>
</div>
<?php
/**
* Fires immediately following the closing "actions" div in the tablenav for the users
* list table.
*
* @since 4.9.0
*
* @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
*/
do_action( 'manage_users_extra_tablenav', $which );
}
```
[do\_action( 'manage\_users\_extra\_tablenav', string $which )](../../hooks/manage_users_extra_tablenav)
Fires immediately following the closing “actions” div in the tablenav for the users list table.
[do\_action( 'restrict\_manage\_users', string $which )](../../hooks/restrict_manage_users)
Fires just before the closing div containing the bulk role-change controls in the Users list table.
| Uses | Description |
| --- | --- |
| [submit\_button()](../../functions/submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [wp\_dropdown\_roles()](../../functions/wp_dropdown_roles) wp-admin/includes/template.php | Prints out option HTML elements for role selectors. |
| [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. |
| [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. |
| programming_docs |
wordpress WP_Users_List_Table::current_action(): string WP\_Users\_List\_Table::current\_action(): string
=================================================
Capture the bulk action required, and return it.
Overridden from the base class implementation to capture the role change drop-down.
string The bulk action required.
File: `wp-admin/includes/class-wp-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
public function current_action() {
if ( isset( $_REQUEST['changeit'] ) && ! empty( $_REQUEST['new_role'] ) ) {
return 'promote';
}
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. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Users_List_Table::prepare_items() WP\_Users\_List\_Table::prepare\_items()
========================================
Prepare the users list for display.
File: `wp-admin/includes/class-wp-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
public function prepare_items() {
global $role, $usersearch;
$usersearch = isset( $_REQUEST['s'] ) ? wp_unslash( trim( $_REQUEST['s'] ) ) : '';
$role = isset( $_REQUEST['role'] ) ? $_REQUEST['role'] : '';
$per_page = ( $this->is_site_users ) ? 'site_users_network_per_page' : 'users_per_page';
$users_per_page = $this->get_items_per_page( $per_page );
$paged = $this->get_pagenum();
if ( 'none' === $role ) {
$args = array(
'number' => $users_per_page,
'offset' => ( $paged - 1 ) * $users_per_page,
'include' => wp_get_users_with_no_role( $this->site_id ),
'search' => $usersearch,
'fields' => 'all_with_meta',
);
} else {
$args = array(
'number' => $users_per_page,
'offset' => ( $paged - 1 ) * $users_per_page,
'role' => $role,
'search' => $usersearch,
'fields' => 'all_with_meta',
);
}
if ( '' !== $args['search'] ) {
$args['search'] = '*' . $args['search'] . '*';
}
if ( $this->is_site_users ) {
$args['blog_id'] = $this->site_id;
}
if ( isset( $_REQUEST['orderby'] ) ) {
$args['orderby'] = $_REQUEST['orderby'];
}
if ( isset( $_REQUEST['order'] ) ) {
$args['order'] = $_REQUEST['order'];
}
/**
* Filters the query arguments used to retrieve users for the current users list table.
*
* @since 4.4.0
*
* @param array $args Arguments passed to WP_User_Query to retrieve items for the current
* users list table.
*/
$args = apply_filters( 'users_list_table_query_args', $args );
// Query the user IDs for this page.
$wp_user_search = new WP_User_Query( $args );
$this->items = $wp_user_search->get_results();
$this->set_pagination_args(
array(
'total_items' => $wp_user_search->get_total(),
'per_page' => $users_per_page,
)
);
}
```
[apply\_filters( 'users\_list\_table\_query\_args', array $args )](../../hooks/users_list_table_query_args)
Filters the query arguments used to retrieve users for the current users list table.
| Uses | Description |
| --- | --- |
| [wp\_get\_users\_with\_no\_role()](../../functions/wp_get_users_with_no_role) wp-includes/user.php | Gets the user IDs of all users with no role on this site. |
| [WP\_User\_Search::get\_results()](../wp_user_search/get_results) wp-admin/includes/deprecated.php | Retrieves the user search query results. |
| [WP\_User\_Query::\_\_construct()](../wp_user_query/__construct) wp-includes/class-wp-user-query.php | PHP5 constructor. |
| [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. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Users_List_Table::ajax_user_can(): bool WP\_Users\_List\_Table::ajax\_user\_can(): bool
===============================================
Check the current user’s permissions.
bool
File: `wp-admin/includes/class-wp-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
public function ajax_user_can() {
if ( $this->is_site_users ) {
return current_user_can( 'manage_sites' );
} else {
return current_user_can( 'list_users' );
}
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Users_List_Table::display_rows() WP\_Users\_List\_Table::display\_rows()
=======================================
Generate the list table rows.
File: `wp-admin/includes/class-wp-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
public function display_rows() {
// Query the post counts for this page.
if ( ! $this->is_site_users ) {
$post_counts = count_many_users_posts( array_keys( $this->items ) );
}
foreach ( $this->items as $userid => $user_object ) {
echo "\n\t" . $this->single_row( $user_object, '', '', isset( $post_counts ) ? $post_counts[ $userid ] : 0 );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Users\_List\_Table::single\_row()](single_row) wp-admin/includes/class-wp-users-list-table.php | Generate HTML for a single row on the users.php admin panel. |
| [count\_many\_users\_posts()](../../functions/count_many_users_posts) wp-includes/user.php | Gets the number of posts written by a list of users. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Users_List_Table::no_items() WP\_Users\_List\_Table::no\_items()
===================================
Output ‘no users’ message.
File: `wp-admin/includes/class-wp-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
public function no_items() {
_e( 'No users found.' );
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Users_List_Table::get_default_primary_column_name(): string WP\_Users\_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, `'username'`.
File: `wp-admin/includes/class-wp-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
protected function get_default_primary_column_name() {
return 'username';
}
```
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Users_List_Table::get_views(): string[] WP\_Users\_List\_Table::get\_views(): string[]
==============================================
Return an associative array listing all the views that can be used with this table.
Provides a list of roles and user count for that role for easy Filtersing of the user table.
string[] An array of HTML links keyed by their view.
File: `wp-admin/includes/class-wp-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
protected function get_views() {
global $role;
$wp_roles = wp_roles();
$count_users = ! wp_is_large_user_count();
if ( $this->is_site_users ) {
$url = 'site-users.php?id=' . $this->site_id;
} else {
$url = 'users.php';
}
$role_links = array();
$avail_roles = array();
$all_text = __( 'All' );
if ( $count_users ) {
if ( $this->is_site_users ) {
switch_to_blog( $this->site_id );
$users_of_blog = count_users( 'time', $this->site_id );
restore_current_blog();
} else {
$users_of_blog = count_users();
}
$total_users = $users_of_blog['total_users'];
$avail_roles =& $users_of_blog['avail_roles'];
unset( $users_of_blog );
$all_text = sprintf(
/* translators: %s: Number of users. */
_nx(
'All <span class="count">(%s)</span>',
'All <span class="count">(%s)</span>',
$total_users,
'users'
),
number_format_i18n( $total_users )
);
}
$role_links['all'] = array(
'url' => $url,
'label' => $all_text,
'current' => empty( $role ),
);
foreach ( $wp_roles->get_names() as $this_role => $name ) {
if ( $count_users && ! isset( $avail_roles[ $this_role ] ) ) {
continue;
}
$name = translate_user_role( $name );
if ( $count_users ) {
$name = sprintf(
/* translators: 1: User role name, 2: Number of users. */
__( '%1$s <span class="count">(%2$s)</span>' ),
$name,
number_format_i18n( $avail_roles[ $this_role ] )
);
}
$role_links[ $this_role ] = array(
'url' => esc_url( add_query_arg( 'role', $this_role, $url ) ),
'label' => $name,
'current' => $this_role === $role,
);
}
if ( ! empty( $avail_roles['none'] ) ) {
$name = __( 'No role' );
$name = sprintf(
/* translators: 1: User role name, 2: Number of users. */
__( '%1$s <span class="count">(%2$s)</span>' ),
$name,
number_format_i18n( $avail_roles['none'] )
);
$role_links['none'] = array(
'url' => esc_url( add_query_arg( 'role', 'none', $url ) ),
'label' => $name,
'current' => 'none' === $role,
);
}
return $this->get_views_links( $role_links );
}
```
| 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. |
| [wp\_roles()](../../functions/wp_roles) wp-includes/capabilities.php | Retrieves the global [WP\_Roles](../wp_roles) instance and instantiates it if necessary. |
| [WP\_Roles::get\_names()](../wp_roles/get_names) wp-includes/class-wp-roles.php | Retrieves a list of role names. |
| [translate\_user\_role()](../../functions/translate_user_role) wp-includes/l10n.php | Translates role name. |
| [\_nx()](../../functions/_nx) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number, with gettext context. |
| [count\_users()](../../functions/count_users) wp-includes/user.php | Counts number of users who have each of the user roles. |
| [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) . |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [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. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Users_List_Table::get_sortable_columns(): array WP\_Users\_List\_Table::get\_sortable\_columns(): array
=======================================================
Get a list of sortable columns for the list table.
array Array of sortable columns.
File: `wp-admin/includes/class-wp-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
protected function get_sortable_columns() {
$columns = array(
'username' => 'login',
'email' => 'email',
);
return $columns;
}
```
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Users_List_Table::get_columns(): string[] WP\_Users\_List\_Table::get\_columns(): string[]
================================================
Get a list of columns for the list table.
string[] Array of column titles keyed by their column name.
File: `wp-admin/includes/class-wp-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
public function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'username' => __( 'Username' ),
'name' => __( 'Name' ),
'email' => __( 'Email' ),
'role' => __( 'Role' ),
'posts' => _x( 'Posts', 'post type general name' ),
);
if ( $this->is_site_users ) {
unset( $columns['posts'] );
}
return $columns;
}
```
| 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. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Users_List_Table::get_role_list( WP_User $user_object ): string[] WP\_Users\_List\_Table::get\_role\_list( WP\_User $user\_object ): string[]
===========================================================================
Returns an array of translated user role names for a given user object.
`$user_object` [WP\_User](../wp_user) Required The [WP\_User](../wp_user) object. string[] An array of user role names keyed by role.
File: `wp-admin/includes/class-wp-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
protected function get_role_list( $user_object ) {
$wp_roles = wp_roles();
$role_list = array();
foreach ( $user_object->roles as $role ) {
if ( isset( $wp_roles->role_names[ $role ] ) ) {
$role_list[ $role ] = translate_user_role( $wp_roles->role_names[ $role ] );
}
}
if ( empty( $role_list ) ) {
$role_list['none'] = _x( 'None', 'no user roles' );
}
/**
* Filters the returned array of translated role names for a user.
*
* @since 4.4.0
*
* @param string[] $role_list An array of translated user role names keyed by role.
* @param WP_User $user_object A WP_User object.
*/
return apply_filters( 'get_role_list', $role_list, $user_object );
}
```
[apply\_filters( 'get\_role\_list', string[] $role\_list, WP\_User $user\_object )](../../hooks/get_role_list)
Filters the returned array of translated role names for a user.
| Uses | Description |
| --- | --- |
| [wp\_roles()](../../functions/wp_roles) wp-includes/capabilities.php | Retrieves the global [WP\_Roles](../wp_roles) instance and instantiates it if necessary. |
| [translate\_user\_role()](../../functions/translate_user_role) wp-includes/l10n.php | Translates role name. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [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\_Users\_List\_Table::single\_row()](single_row) wp-admin/includes/class-wp-users-list-table.php | Generate HTML for a single row on the users.php admin panel. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Users_List_Table::get_bulk_actions(): array WP\_Users\_List\_Table::get\_bulk\_actions(): array
===================================================
Retrieve an associative array of bulk actions available on this table.
array Array of bulk action labels keyed by their action.
File: `wp-admin/includes/class-wp-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
protected function get_bulk_actions() {
$actions = array();
if ( is_multisite() ) {
if ( current_user_can( 'remove_users' ) ) {
$actions['remove'] = __( 'Remove' );
}
} else {
if ( current_user_can( 'delete_users' ) ) {
$actions['delete'] = __( 'Delete' );
}
}
// Add a password reset link to the bulk actions dropdown.
if ( current_user_can( 'edit_users' ) ) {
$actions['resetpassword'] = __( 'Send password reset' );
}
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. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Users_List_Table::__construct( array $args = array() ) WP\_Users\_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-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-users-list-table.php/)
```
public function __construct( $args = array() ) {
parent::__construct(
array(
'singular' => 'user',
'plural' => 'users',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
$this->is_site_users = 'site-users-network' === $this->screen->id;
if ( $this->is_site_users ) {
$this->site_id = isset( $_REQUEST['id'] ) ? (int) $_REQUEST['id'] : 0;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::\_\_construct()](../wp_list_table/__construct) wp-admin/includes/class-wp-list-table.php | Constructor. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Locations_Control::content_template() WP\_Customize\_Nav\_Menu\_Locations\_Control::content\_template()
=================================================================
JS/Underscore template for the control UI.
File: `wp-includes/customize/class-wp-customize-nav-menu-locations-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-locations-control.php/)
```
public function content_template() {
if ( current_theme_supports( 'menus' ) ) :
?>
<# var elementId; #>
<ul class="menu-location-settings">
<li class="customize-control assigned-menu-locations-title">
<span class="customize-control-title">{{ wp.customize.Menus.data.l10n.locationsTitle }}</span>
<# if ( data.isCreating ) { #>
<p>
<?php echo _x( 'Where do you want this menu to appear?', 'menu locations' ); ?>
<?php
printf(
/* translators: 1: Documentation URL, 2: Additional link attributes, 3: Accessibility text. */
_x( '(If you plan to use a menu <a href="%1$s" %2$s>widget%3$s</a>, skip this step.)', 'menu locations' ),
__( 'https://wordpress.org/support/article/wordpress-widgets/' ),
' class="external-link" target="_blank"',
sprintf(
'<span class="screen-reader-text"> %s</span>',
/* translators: Accessibility text. */
__( '(opens in a new tab)' )
)
);
?>
</p>
<# } else { #>
<p><?php echo _x( 'Here’s where this menu appears. If you would like to change that, pick another location.', 'menu locations' ); ?></p>
<# } #>
</li>
<?php foreach ( get_registered_nav_menus() as $location => $description ) : ?>
<# elementId = _.uniqueId( 'customize-nav-menu-control-location-' ); #>
<li class="customize-control customize-control-checkbox assigned-menu-location">
<span class="customize-inside-control-row">
<input id="{{ elementId }}" type="checkbox" data-menu-id="{{ data.menu_id }}" data-location-id="<?php echo esc_attr( $location ); ?>" class="menu-location" />
<label for="{{ elementId }}">
<?php echo $description; ?>
<span class="theme-location-set">
<?php
printf(
/* translators: %s: Menu name. */
_x( '(Current: %s)', 'menu location' ),
'<span class="current-menu-location-name-' . esc_attr( $location ) . '"></span>'
);
?>
</span>
</label>
</span>
</li>
<?php endforeach; ?>
</ul>
<?php
endif;
}
```
| Uses | Description |
| --- | --- |
| [get\_registered\_nav\_menus()](../../functions/get_registered_nav_menus) wp-includes/nav-menu.php | Retrieves all registered navigation menu locations in a theme. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’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. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Nav_Menu_Locations_Control::render_content() WP\_Customize\_Nav\_Menu\_Locations\_Control::render\_content()
===============================================================
Don’t render the control’s content – it uses a JS template instead.
File: `wp-includes/customize/class-wp-customize-nav-menu-locations-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-locations-control.php/)
```
public function render_content() {}
```
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress Translation_Entry::Translation_Entry( $args = array() ) Translation\_Entry::Translation\_Entry( $args = array() )
=========================================================
This method has been deprecated. Use [Translation\_Entry::\_\_construct()](../translation_entry/__construct) instead.
PHP4 constructor.
* [Translation\_Entry::\_\_construct()](../translation_entry/__construct)
File: `wp-includes/pomo/entry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/entry.php/)
```
public function Translation_Entry( $args = array() ) {
_deprecated_constructor( self::class, '5.4.0', static::class );
self::__construct( $args );
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_constructor()](../../functions/_deprecated_constructor) wp-includes/functions.php | Marks a constructor as deprecated and informs when it has been used. |
| [Translation\_Entry::\_\_construct()](__construct) wp-includes/pomo/entry.php | |
| Version | Description |
| --- | --- |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | Introduced. |
wordpress Translation_Entry::merge_with( object $other ) Translation\_Entry::merge\_with( object $other )
================================================
`$other` object Required File: `wp-includes/pomo/entry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/entry.php/)
```
public function merge_with( &$other ) {
$this->flags = array_unique( array_merge( $this->flags, $other->flags ) );
$this->references = array_unique( array_merge( $this->references, $other->references ) );
if ( $this->extracted_comments != $other->extracted_comments ) {
$this->extracted_comments .= $other->extracted_comments;
}
}
```
wordpress Translation_Entry::key(): string|false Translation\_Entry::key(): string|false
=======================================
Generates a unique key for this entry.
string|false The key or false if the entry is null.
File: `wp-includes/pomo/entry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/entry.php/)
```
public function key() {
if ( null === $this->singular ) {
return false;
}
// Prepend context and EOT, like in MO files.
$key = ! $this->context ? $this->singular : $this->context . "\4" . $this->singular;
// Standardize on \n line endings.
$key = str_replace( array( "\r\n", "\r" ), "\n", $key );
return $key;
}
```
wordpress Translation_Entry::__construct( array $args = array() ) Translation\_Entry::\_\_construct( array $args = array() )
==========================================================
`$args` array Optional Arguments array, supports the following keys: * `singular`stringThe string to translate, if omitted an empty entry will be created.
* `plural`stringThe plural form of the string, setting this will set `$is_plural` to true.
* `translations`arrayTranslations of the string and possibly its plural forms.
* `context`stringA string differentiating two equal strings used in different contexts.
* `translator_comments`stringComments left by translators.
* `extracted_comments`stringComments left by developers.
* `references`arrayPlaces in the code this string is used, in relative\_to\_root\_path/file.php:linenum form.
* `flags`arrayFlags like php-format.
Default: `array()`
File: `wp-includes/pomo/entry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/entry.php/)
```
public function __construct( $args = array() ) {
// If no singular -- empty object.
if ( ! isset( $args['singular'] ) ) {
return;
}
// Get member variable values from args hash.
foreach ( $args as $varname => $value ) {
$this->$varname = $value;
}
if ( isset( $args['plural'] ) && $args['plural'] ) {
$this->is_plural = true;
}
if ( ! is_array( $this->translations ) ) {
$this->translations = array();
}
if ( ! is_array( $this->references ) ) {
$this->references = array();
}
if ( ! is_array( $this->flags ) ) {
$this->flags = array();
}
}
```
| Used By | Description |
| --- | --- |
| [PO::read\_entry()](../po/read_entry) wp-includes/pomo/po.php | |
| [Translations::add\_entry()](../translations/add_entry) wp-includes/pomo/translations.php | Add entry to the PO structure |
| [Translations::add\_entry\_or\_merge()](../translations/add_entry_or_merge) wp-includes/pomo/translations.php | |
| [Translations::translate()](../translations/translate) wp-includes/pomo/translations.php | |
| [Translations::translate\_plural()](../translations/translate_plural) wp-includes/pomo/translations.php | |
| [Translation\_Entry::Translation\_Entry()](translation_entry) wp-includes/pomo/entry.php | PHP4 constructor. |
| [MO::make\_entry()](../mo/make_entry) wp-includes/pomo/mo.php | Build a [Translation\_Entry](../translation_entry) from original string and translation strings, found in a MO file |
wordpress WP_Theme::markup_header( string $header, string|array $value, string $translate ): string WP\_Theme::markup\_header( string $header, string|array $value, string $translate ): 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.
Marks up a theme header.
`$header` string Required Theme header. Name, Description, Author, Version, ThemeURI, AuthorURI, Status, Tags. `$value` string|array Required Value to mark up. An array for Tags header, string otherwise. `$translate` string Required Whether the header has been translated. string Value, marked up.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
private function markup_header( $header, $value, $translate ) {
switch ( $header ) {
case 'Name':
if ( empty( $value ) ) {
$value = esc_html( $this->get_stylesheet() );
}
break;
case 'Description':
$value = wptexturize( $value );
break;
case 'Author':
if ( $this->get( 'AuthorURI' ) ) {
$value = sprintf( '<a href="%1$s">%2$s</a>', $this->display( 'AuthorURI', true, $translate ), $value );
} elseif ( ! $value ) {
$value = __( 'Anonymous' );
}
break;
case 'Tags':
static $comma = null;
if ( ! isset( $comma ) ) {
$comma = wp_get_list_item_separator();
}
$value = implode( $comma, $value );
break;
case 'ThemeURI':
case 'AuthorURI':
$value = esc_url( $value );
break;
}
return $value;
}
```
| 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. |
| [wptexturize()](../../functions/wptexturize) wp-includes/formatting.php | Replaces common plain text characters with formatted entities. |
| [WP\_Theme::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-theme.php | Returns the directory name of the theme’s “stylesheet” files, inside the theme root. |
| [WP\_Theme::get()](get) wp-includes/class-wp-theme.php | Gets a raw, unformatted theme header. |
| [WP\_Theme::display()](display) wp-includes/class-wp-theme.php | Gets a theme header, formatted and translated for display. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::display()](display) wp-includes/class-wp-theme.php | Gets a theme header, formatted and translated for display. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::get_file_path( string $file = '' ): string WP\_Theme::get\_file\_path( string $file = '' ): string
=======================================================
Retrieves the path of a file in the theme.
Searches in the stylesheet directory before the template directory so themes which inherit from a parent theme can just override one file.
`$file` string Optional File to search for in the stylesheet directory. Default: `''`
string The path of the file.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get_file_path( $file = '' ) {
$file = ltrim( $file, '/' );
$stylesheet_directory = $this->get_stylesheet_directory();
$template_directory = $this->get_template_directory();
if ( empty( $file ) ) {
$path = $stylesheet_directory;
} elseif ( file_exists( $stylesheet_directory . '/' . $file ) ) {
$path = $stylesheet_directory . '/' . $file;
} else {
$path = $template_directory . '/' . $file;
}
/** This filter is documented in wp-includes/link-template.php */
return apply_filters( 'theme_file_path', $path, $file );
}
```
[apply\_filters( 'theme\_file\_path', string $path, string $file )](../../hooks/theme_file_path)
Filters the path to a file in the theme.
| Uses | Description |
| --- | --- |
| [WP\_Theme::get\_stylesheet\_directory()](get_stylesheet_directory) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of a theme’s “stylesheet” files. |
| [WP\_Theme::get\_template\_directory()](get_template_directory) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of a theme’s “template” files. |
| [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::is\_block\_theme()](is_block_theme) wp-includes/class-wp-theme.php | Returns whether this theme is a block-based theme or not. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Theme::get_stylesheet(): string WP\_Theme::get\_stylesheet(): string
====================================
Returns the directory name of the theme’s “stylesheet” files, inside the theme root.
In the case of a child theme, this is directory name of the child theme.
Otherwise, [get\_stylesheet()](../../functions/get_stylesheet) is the same as [get\_template()](../../functions/get_template) .
string Stylesheet
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get_stylesheet() {
return $this->stylesheet;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Global\_Styles\_Controller::get\_theme\_items()](../wp_rest_global_styles_controller/get_theme_items) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Returns the given theme global styles variations. |
| [WP\_REST\_Global\_Styles\_Controller::get\_theme\_item()](../wp_rest_global_styles_controller/get_theme_item) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Returns the given theme global styles config. |
| [wp\_set\_unique\_slug\_on\_create\_template\_part()](../../functions/wp_set_unique_slug_on_create_template_part) wp-includes/theme-templates.php | Sets a custom slug when creating auto-draft template parts. |
| [get\_block\_file\_template()](../../functions/get_block_file_template) wp-includes/block-template-utils.php | Retrieves a unified template object based on a theme file. |
| [\_inject\_theme\_attribute\_in\_block\_template\_content()](../../functions/_inject_theme_attribute_in_block_template_content) wp-includes/block-template-utils.php | Parses wp\_template content and injects the active theme’s stylesheet as a theme attribute into each wp\_template\_part |
| [\_build\_block\_template\_result\_from\_file()](../../functions/_build_block_template_result_from_file) wp-includes/block-template-utils.php | Builds a unified template object based on a theme file. |
| [\_build\_block\_template\_result\_from\_post()](../../functions/_build_block_template_result_from_post) wp-includes/block-template-utils.php | Builds a unified template object based a post Object. |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_database()](../wp_rest_templates_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepares a single template for create or update. |
| [wp\_filter\_wp\_template\_unique\_post\_slug()](../../functions/wp_filter_wp_template_unique_post_slug) wp-includes/theme-templates.php | Generates a unique slug for templates. |
| [resolve\_block\_template()](../../functions/resolve_block_template) wp-includes/block-template.php | Returns the correct ‘wp\_template’ to render for the request template type. |
| [get\_block\_templates()](../../functions/get_block_templates) wp-includes/block-template-utils.php | Retrieves a list of unified template objects based on a query. |
| [WP\_Theme::markup\_header()](markup_header) wp-includes/class-wp-theme.php | Marks up a theme header. |
| [WP\_Theme::is\_allowed()](is_allowed) wp-includes/class-wp-theme.php | Determines whether the theme is allowed (multisite only). |
| [WP\_Theme::\_\_get()](__get) wp-includes/class-wp-theme.php | \_\_get() magic method for properties formerly returned by [current\_theme\_info()](../../functions/current_theme_info) |
| [WP\_Theme::offsetGet()](offsetget) wp-includes/class-wp-theme.php | |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::exists(): bool WP\_Theme::exists(): bool
=========================
Determines whether the theme exists.
A theme with errors exists. A theme with the error of ‘theme\_not\_found’, meaning that the theme’s directory was not found, does not exist.
bool Whether the theme exists.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function exists() {
return ! ( $this->errors() && in_array( 'theme_not_found', $this->errors()->get_error_codes(), true ) );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::errors()](errors) wp-includes/class-wp-theme.php | Returns errors property. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Themes\_Controller::get\_item()](../wp_rest_themes_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Retrieves a single theme. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::get_stylesheet_directory(): string WP\_Theme::get\_stylesheet\_directory(): string
===============================================
Returns the absolute path to the directory of a theme’s “stylesheet” files.
In the case of a child theme, this is the absolute path to the directory of the child theme’s files.
string Absolute path of the stylesheet directory.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get_stylesheet_directory() {
if ( $this->errors() && in_array( 'theme_root_missing', $this->errors()->get_error_codes(), true ) ) {
return '';
}
return $this->theme_root . '/' . $this->stylesheet;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::errors()](errors) wp-includes/class-wp-theme.php | Returns errors property. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::get\_file\_path()](get_file_path) wp-includes/class-wp-theme.php | Retrieves the path of a file in the theme. |
| [WP\_Theme::get\_screenshot()](get_screenshot) wp-includes/class-wp-theme.php | Returns the main screenshot file for the theme. |
| [WP\_Theme::get\_files()](get_files) wp-includes/class-wp-theme.php | Returns files in the theme’s directory. |
| [WP\_Theme::load\_textdomain()](load_textdomain) wp-includes/class-wp-theme.php | Loads the theme’s textdomain. |
| [WP\_Theme::\_\_get()](__get) wp-includes/class-wp-theme.php | \_\_get() magic method for properties formerly returned by [current\_theme\_info()](../../functions/current_theme_info) |
| [WP\_Theme::offsetGet()](offsetget) wp-includes/class-wp-theme.php | |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::offsetGet( $offset ) WP\_Theme::offsetGet( $offset )
===============================
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function offsetGet( $offset ) {
switch ( $offset ) {
case 'Name':
case 'Title':
/*
* See note above about using translated data. get() is not ideal.
* It is only for backward compatibility. Use display().
*/
return $this->get( 'Name' );
case 'Author':
return $this->display( 'Author' );
case 'Author Name':
return $this->display( 'Author', false );
case 'Author URI':
return $this->display( 'AuthorURI' );
case 'Description':
return $this->display( 'Description' );
case 'Version':
case 'Status':
return $this->get( $offset );
case 'Template':
return $this->get_template();
case 'Stylesheet':
return $this->get_stylesheet();
case 'Template Files':
return $this->get_files( 'php', 1, true );
case 'Stylesheet Files':
return $this->get_files( 'css', 0, false );
case 'Template Dir':
return $this->get_template_directory();
case 'Stylesheet Dir':
return $this->get_stylesheet_directory();
case 'Screenshot':
return $this->get_screenshot( 'relative' );
case 'Tags':
return $this->get( 'Tags' );
case 'Theme Root':
return $this->get_theme_root();
case 'Theme Root URI':
return $this->get_theme_root_uri();
case 'Parent Theme':
return $this->parent() ? $this->parent()->get( 'Name' ) : '';
default:
return null;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::get\_template()](get_template) wp-includes/class-wp-theme.php | Returns the directory name of the theme’s “template” files, inside the theme root. |
| [WP\_Theme::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-theme.php | Returns the directory name of the theme’s “stylesheet” files, inside the theme root. |
| [WP\_Theme::get\_files()](get_files) wp-includes/class-wp-theme.php | Returns files in the theme’s directory. |
| [WP\_Theme::get\_template\_directory()](get_template_directory) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of a theme’s “template” files. |
| [WP\_Theme::get\_stylesheet\_directory()](get_stylesheet_directory) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of a theme’s “stylesheet” files. |
| [WP\_Theme::get\_screenshot()](get_screenshot) wp-includes/class-wp-theme.php | Returns the main screenshot file for the theme. |
| [WP\_Theme::get\_theme\_root()](get_theme_root) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of the theme root. |
| [WP\_Theme::get\_theme\_root\_uri()](get_theme_root_uri) wp-includes/class-wp-theme.php | Returns the URL to the directory of the theme root. |
| [WP\_Theme::get()](get) wp-includes/class-wp-theme.php | Gets a raw, unformatted theme header. |
| [WP\_Theme::display()](display) wp-includes/class-wp-theme.php | Gets a theme header, formatted and translated for display. |
| [WP\_Theme::parent()](parent) wp-includes/class-wp-theme.php | Returns reference to the parent theme. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::\_\_get()](__get) wp-includes/class-wp-theme.php | \_\_get() magic method for properties formerly returned by [current\_theme\_info()](../../functions/current_theme_info) |
| programming_docs |
wordpress WP_Theme::offsetUnset( $offset ) WP\_Theme::offsetUnset( $offset )
=================================
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function offsetUnset( $offset ) {}
```
wordpress WP_Theme::get_theme_root(): string WP\_Theme::get\_theme\_root(): string
=====================================
Returns the absolute path to the directory of the theme root.
This is typically the absolute path to wp-content/themes.
string Theme root.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get_theme_root() {
return $this->theme_root;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Theme::\_\_get()](__get) wp-includes/class-wp-theme.php | \_\_get() magic method for properties formerly returned by [current\_theme\_info()](../../functions/current_theme_info) |
| [WP\_Theme::offsetGet()](offsetget) wp-includes/class-wp-theme.php | |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::offsetSet( $offset, $value ) WP\_Theme::offsetSet( $offset, $value )
=======================================
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function offsetSet( $offset, $value ) {}
```
wordpress WP_Theme::is_allowed( string $check = 'both', int $blog_id = null ): bool WP\_Theme::is\_allowed( string $check = 'both', int $blog\_id = null ): bool
============================================================================
Determines whether the theme is allowed (multisite only).
`$check` string Optional Whether to check only the `'network'`-wide settings, the `'site'` settings, or `'both'`. Defaults to `'both'`. Default: `'both'`
`$blog_id` int Optional Ignored if only network-wide settings are checked. Defaults to current site. Default: `null`
bool Whether the theme is allowed for the network. Returns true in single-site.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function is_allowed( $check = 'both', $blog_id = null ) {
if ( ! is_multisite() ) {
return true;
}
if ( 'both' === $check || 'network' === $check ) {
$allowed = self::get_allowed_on_network();
if ( ! empty( $allowed[ $this->get_stylesheet() ] ) ) {
return true;
}
}
if ( 'both' === $check || 'site' === $check ) {
$allowed = self::get_allowed_on_site( $blog_id );
if ( ! empty( $allowed[ $this->get_stylesheet() ] ) ) {
return true;
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::get\_allowed\_on\_network()](get_allowed_on_network) wp-includes/class-wp-theme.php | Returns array of stylesheet names of themes allowed on the network. |
| [WP\_Theme::get\_allowed\_on\_site()](get_allowed_on_site) wp-includes/class-wp-theme.php | Returns array of stylesheet names of themes allowed on the site. |
| [WP\_Theme::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-theme.php | Returns the directory name of the theme’s “stylesheet” files, inside the theme root. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::sort_by_name( WP_Theme[] $themes ) WP\_Theme::sort\_by\_name( WP\_Theme[] $themes )
================================================
Sorts themes by name.
`$themes` [WP\_Theme](../wp_theme)[] Required Array of theme objects to sort (passed by reference). File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public static function sort_by_name( &$themes ) {
if ( 0 === strpos( get_user_locale(), 'en_' ) ) {
uasort( $themes, array( 'WP_Theme', '_name_sort' ) );
} else {
foreach ( $themes as $key => $theme ) {
$theme->translate_header( 'Name', $theme->headers['Name'] );
}
uasort( $themes, array( 'WP_Theme', '_name_sort_i18n' ) );
}
}
```
| Uses | Description |
| --- | --- |
| [get\_user\_locale()](../../functions/get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| Used By | Description |
| --- | --- |
| [wp\_prepare\_themes\_for\_js()](../../functions/wp_prepare_themes_for_js) wp-admin/includes/theme.php | Prepares themes for JavaScript. |
| [WP\_MS\_Themes\_List\_Table::prepare\_items()](../wp_ms_themes_list_table/prepare_items) wp-admin/includes/class-wp-ms-themes-list-table.php | |
| [WP\_Themes\_List\_Table::prepare\_items()](../wp_themes_list_table/prepare_items) wp-admin/includes/class-wp-themes-list-table.php | |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::sanitize_header( string $header, string $value ): string|array WP\_Theme::sanitize\_header( string $header, string $value ): string|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.
Sanitizes a theme header.
`$header` string Required Theme header. Accepts `'Name'`, `'Description'`, `'Author'`, `'Version'`, `'ThemeURI'`, `'AuthorURI'`, `'Status'`, `'Tags'`, `'RequiresWP'`, `'RequiresPHP'`, `'UpdateURI'`. `$value` string Required Value to sanitize. string|array An array for Tags header, string otherwise.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
private function sanitize_header( $header, $value ) {
switch ( $header ) {
case 'Status':
if ( ! $value ) {
$value = 'publish';
break;
}
// Fall through otherwise.
case 'Name':
static $header_tags = array(
'abbr' => array( 'title' => true ),
'acronym' => array( 'title' => true ),
'code' => true,
'em' => true,
'strong' => true,
);
$value = wp_kses( $value, $header_tags );
break;
case 'Author':
// There shouldn't be anchor tags in Author, but some themes like to be challenging.
case 'Description':
static $header_tags_with_a = array(
'a' => array(
'href' => true,
'title' => true,
),
'abbr' => array( 'title' => true ),
'acronym' => array( 'title' => true ),
'code' => true,
'em' => true,
'strong' => true,
);
$value = wp_kses( $value, $header_tags_with_a );
break;
case 'ThemeURI':
case 'AuthorURI':
$value = sanitize_url( $value );
break;
case 'Tags':
$value = array_filter( array_map( 'trim', explode( ',', strip_tags( $value ) ) ) );
break;
case 'Version':
case 'RequiresWP':
case 'RequiresPHP':
case 'UpdateURI':
$value = strip_tags( $value );
break;
}
return $value;
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_url()](../../functions/sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [wp\_kses()](../../functions/wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::get()](get) wp-includes/class-wp-theme.php | Gets a raw, unformatted theme header. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Added support for `Update URI` header. |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | Added support for `Requires at least` and `Requires PHP` headers. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::get_theme_root_uri(): string WP\_Theme::get\_theme\_root\_uri(): string
==========================================
Returns the URL to the directory of the theme root.
This is typically the absolute URL to wp-content/themes. This forms the basis for all other URLs returned by [WP\_Theme](../wp_theme), so we pass it to the public function [get\_theme\_root\_uri()](../../functions/get_theme_root_uri) and allow it to run the [‘theme\_root\_uri’](../../hooks/theme_root_uri) filter.
string Theme root URI.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get_theme_root_uri() {
if ( ! isset( $this->theme_root_uri ) ) {
$this->theme_root_uri = get_theme_root_uri( $this->stylesheet, $this->theme_root );
}
return $this->theme_root_uri;
}
```
| Uses | Description |
| --- | --- |
| [get\_theme\_root\_uri()](../../functions/get_theme_root_uri) wp-includes/theme.php | Retrieves URI for themes directory. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::get\_stylesheet\_directory\_uri()](get_stylesheet_directory_uri) wp-includes/class-wp-theme.php | Returns the URL to the directory of a theme’s “stylesheet” files. |
| [WP\_Theme::get\_template\_directory\_uri()](get_template_directory_uri) wp-includes/class-wp-theme.php | Returns the URL to the directory of a theme’s “template” files. |
| [WP\_Theme::\_\_get()](__get) wp-includes/class-wp-theme.php | \_\_get() magic method for properties formerly returned by [current\_theme\_info()](../../functions/current_theme_info) |
| [WP\_Theme::offsetGet()](offsetget) wp-includes/class-wp-theme.php | |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::get_allowed_on_network(): string[] WP\_Theme::get\_allowed\_on\_network(): string[]
================================================
Returns array of stylesheet names of themes allowed on the network.
string[] Array of stylesheet names.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public static function get_allowed_on_network() {
static $allowed_themes;
if ( ! isset( $allowed_themes ) ) {
$allowed_themes = (array) get_site_option( 'allowedthemes' );
}
/**
* Filters the array of themes allowed on the network.
*
* @since MU (3.0.0)
*
* @param string[] $allowed_themes An array of theme stylesheet names.
*/
$allowed_themes = apply_filters( 'allowed_themes', $allowed_themes );
return $allowed_themes;
}
```
[apply\_filters( 'allowed\_themes', string[] $allowed\_themes )](../../hooks/allowed_themes)
Filters the array of themes allowed on the network.
| Uses | Description |
| --- | --- |
| [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 |
| --- | --- |
| [get\_site\_allowed\_themes()](../../functions/get_site_allowed_themes) wp-admin/includes/ms-deprecated.php | Deprecated functionality for getting themes network-enabled themes. |
| [wp\_get\_themes()](../../functions/wp_get_themes) wp-includes/theme.php | Returns an array of [WP\_Theme](../wp_theme) objects based on the arguments. |
| [WP\_Theme::get\_allowed()](get_allowed) wp-includes/class-wp-theme.php | Returns array of stylesheet names of themes allowed on the site or network. |
| [WP\_Theme::is\_allowed()](is_allowed) wp-includes/class-wp-theme.php | Determines whether the theme is allowed (multisite only). |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::cache_delete() WP\_Theme::cache\_delete()
==========================
Clears the cache for the theme.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function cache_delete() {
foreach ( array( 'theme', 'screenshot', 'headers', 'post_templates' ) as $key ) {
wp_cache_delete( $key . '-' . $this->cache_hash, 'themes' );
}
$this->template = null;
$this->textdomain_loaded = null;
$this->theme_root_uri = null;
$this->parent = null;
$this->errors = null;
$this->headers_sanitized = null;
$this->name_translated = null;
$this->headers = array();
$this->__construct( $this->stylesheet, $this->theme_root );
}
```
| Uses | Description |
| --- | --- |
| [wp\_cache\_delete()](../../functions/wp_cache_delete) wp-includes/cache.php | Removes the cache contents matching key and group. |
| [WP\_Theme::\_\_construct()](__construct) wp-includes/class-wp-theme.php | Constructor for [WP\_Theme](../wp_theme). |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::cache_add( string $key, array|string $data ): bool WP\_Theme::cache\_add( string $key, array|string $data ): 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.
Adds theme data to cache.
Cache entries keyed by the theme and the type of data.
`$key` string Required Type of data to store (theme, screenshot, headers, post\_templates) `$data` array|string Required Data to store bool Return value from [wp\_cache\_add()](../../functions/wp_cache_add)
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
private function cache_add( $key, $data ) {
return wp_cache_add( $key . '-' . $this->cache_hash, $data, 'themes', self::$cache_expiration );
}
```
| Uses | Description |
| --- | --- |
| [wp\_cache\_add()](../../functions/wp_cache_add) wp-includes/cache.php | Adds data to the cache, if the cache key doesn’t already exist. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::get\_post\_templates()](get_post_templates) wp-includes/class-wp-theme.php | Returns the theme’s post templates. |
| [WP\_Theme::get\_screenshot()](get_screenshot) wp-includes/class-wp-theme.php | Returns the main screenshot file for the theme. |
| [WP\_Theme::get()](get) wp-includes/class-wp-theme.php | Gets a raw, unformatted theme header. |
| [WP\_Theme::\_\_construct()](__construct) wp-includes/class-wp-theme.php | Constructor for [WP\_Theme](../wp_theme). |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::_name_sort( WP_Theme $a, WP_Theme $b ): int WP\_Theme::\_name\_sort( WP\_Theme $a, WP\_Theme $b ): 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.
Callback function for usort() to naturally sort themes by name.
Accesses the Name header directly from the class for maximum speed.
Would choke on HTML but we don’t care enough to slow it down with strip\_tags().
`$a` [WP\_Theme](../wp_theme) Required First theme. `$b` [WP\_Theme](../wp_theme) Required Second theme. int Negative if `$a` falls lower in the natural order than `$b`. Zero if they fall equally.
Greater than 0 if `$a` falls higher in the natural order than `$b`. Used with usort().
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
private static function _name_sort( $a, $b ) {
return strnatcasecmp( $a->headers['Name'], $b->headers['Name'] );
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::get_template_directory_uri(): string WP\_Theme::get\_template\_directory\_uri(): string
==================================================
Returns the URL to the directory of a theme’s “template” files.
In the case of a child theme, this is the URL to the directory of the parent theme’s files.
string URL to the template directory.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get_template_directory_uri() {
if ( $this->parent() ) {
$theme_root_uri = $this->parent()->get_theme_root_uri();
} else {
$theme_root_uri = $this->get_theme_root_uri();
}
return $theme_root_uri . '/' . str_replace( '%2F', '/', rawurlencode( $this->template ) );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::get\_theme\_root\_uri()](get_theme_root_uri) wp-includes/class-wp-theme.php | Returns the URL to the directory of the theme root. |
| [WP\_Theme::parent()](parent) wp-includes/class-wp-theme.php | Returns reference to the parent theme. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::get_stylesheet_directory_uri(): string WP\_Theme::get\_stylesheet\_directory\_uri(): string
====================================================
Returns the URL to the directory of a theme’s “stylesheet” files.
In the case of a child theme, this is the URL to the directory of the child theme’s files.
string URL to the stylesheet directory.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get_stylesheet_directory_uri() {
return $this->get_theme_root_uri() . '/' . str_replace( '%2F', '/', rawurlencode( $this->stylesheet ) );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::get\_theme\_root\_uri()](get_theme_root_uri) wp-includes/class-wp-theme.php | Returns the URL to the directory of the theme root. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::get\_screenshot()](get_screenshot) wp-includes/class-wp-theme.php | Returns the main screenshot file for the theme. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::get_page_templates( WP_Post|null $post = null, string $post_type = 'page' ): string[] WP\_Theme::get\_page\_templates( WP\_Post|null $post = null, string $post\_type = 'page' ): string[]
====================================================================================================
Returns the theme’s post templates for a given post type.
`$post` [WP\_Post](../wp_post)|null Optional The post being edited, provided for context. Default: `null`
`$post_type` string Optional Post type to get the templates for. Default `'page'`.
If a post is provided, its post type is used. Default: `'page'`
string[] Array of template header names keyed by the template file name.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get_page_templates( $post = null, $post_type = 'page' ) {
if ( $post ) {
$post_type = get_post_type( $post );
}
$post_templates = $this->get_post_templates();
$post_templates = isset( $post_templates[ $post_type ] ) ? $post_templates[ $post_type ] : array();
/**
* Filters list of page templates for a theme.
*
* @since 4.9.6
*
* @param string[] $post_templates Array of template header names keyed by the template file name.
* @param WP_Theme $theme The theme object.
* @param WP_Post|null $post The post being edited, provided for context, or null.
* @param string $post_type Post type to get the templates for.
*/
$post_templates = (array) apply_filters( 'theme_templates', $post_templates, $this, $post, $post_type );
/**
* Filters list of page templates for a theme.
*
* The dynamic portion of the hook name, `$post_type`, refers to the post type.
*
* Possible hook names include:
*
* - `theme_post_templates`
* - `theme_page_templates`
* - `theme_attachment_templates`
*
* @since 3.9.0
* @since 4.4.0 Converted to allow complete control over the `$page_templates` array.
* @since 4.7.0 Added the `$post_type` parameter.
*
* @param string[] $post_templates Array of template header names keyed by the template file name.
* @param WP_Theme $theme The theme object.
* @param WP_Post|null $post The post being edited, provided for context, or null.
* @param string $post_type Post type to get the templates for.
*/
$post_templates = (array) apply_filters( "theme_{$post_type}_templates", $post_templates, $this, $post, $post_type );
return $post_templates;
}
```
[apply\_filters( 'theme\_templates', string[] $post\_templates, WP\_Theme $theme, WP\_Post|null $post, string $post\_type )](../../hooks/theme_templates)
Filters list of page templates for a theme.
[apply\_filters( "theme\_{$post\_type}\_templates", string[] $post\_templates, WP\_Theme $theme, WP\_Post|null $post, string $post\_type )](../../hooks/theme_post_type_templates)
Filters list of page templates for a theme.
| Uses | Description |
| --- | --- |
| [WP\_Theme::get\_post\_templates()](get_post_templates) wp-includes/class-wp-theme.php | Returns the theme’s post templates. |
| [get\_post\_type()](../../functions/get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| [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\_Posts\_Controller::check\_template()](../wp_rest_posts_controller/check_template) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks whether the template is valid for the given post. |
| [WP\_REST\_Posts\_Controller::handle\_template()](../wp_rest_posts_controller/handle_template) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Sets the template for a post. |
| [get\_page\_templates()](../../functions/get_page_templates) wp-admin/includes/theme.php | Gets the page templates available in this theme. |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Added the `$post_type` parameter. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
| programming_docs |
wordpress WP_Theme::get_allowed_on_site( int $blog_id = null ): string[] WP\_Theme::get\_allowed\_on\_site( int $blog\_id = null ): string[]
===================================================================
Returns array of stylesheet names of themes allowed on the site.
`$blog_id` int Optional ID of the site. Defaults to the current site. Default: `null`
string[] Array of stylesheet names.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public static function get_allowed_on_site( $blog_id = null ) {
static $allowed_themes = array();
if ( ! $blog_id || ! is_multisite() ) {
$blog_id = get_current_blog_id();
}
if ( isset( $allowed_themes[ $blog_id ] ) ) {
/**
* Filters the array of themes allowed on the site.
*
* @since 4.5.0
*
* @param string[] $allowed_themes An array of theme stylesheet names.
* @param int $blog_id ID of the site. Defaults to current site.
*/
return (array) apply_filters( 'site_allowed_themes', $allowed_themes[ $blog_id ], $blog_id );
}
$current = get_current_blog_id() == $blog_id;
if ( $current ) {
$allowed_themes[ $blog_id ] = get_option( 'allowedthemes' );
} else {
switch_to_blog( $blog_id );
$allowed_themes[ $blog_id ] = get_option( 'allowedthemes' );
restore_current_blog();
}
// This is all super old MU back compat joy.
// 'allowedthemes' keys things by stylesheet. 'allowed_themes' keyed things by name.
if ( false === $allowed_themes[ $blog_id ] ) {
if ( $current ) {
$allowed_themes[ $blog_id ] = get_option( 'allowed_themes' );
} else {
switch_to_blog( $blog_id );
$allowed_themes[ $blog_id ] = get_option( 'allowed_themes' );
restore_current_blog();
}
if ( ! is_array( $allowed_themes[ $blog_id ] ) || empty( $allowed_themes[ $blog_id ] ) ) {
$allowed_themes[ $blog_id ] = array();
} else {
$converted = array();
$themes = wp_get_themes();
foreach ( $themes as $stylesheet => $theme_data ) {
if ( isset( $allowed_themes[ $blog_id ][ $theme_data->get( 'Name' ) ] ) ) {
$converted[ $stylesheet ] = true;
}
}
$allowed_themes[ $blog_id ] = $converted;
}
// Set the option so we never have to go through this pain again.
if ( is_admin() && $allowed_themes[ $blog_id ] ) {
if ( $current ) {
update_option( 'allowedthemes', $allowed_themes[ $blog_id ] );
delete_option( 'allowed_themes' );
} else {
switch_to_blog( $blog_id );
update_option( 'allowedthemes', $allowed_themes[ $blog_id ] );
delete_option( 'allowed_themes' );
restore_current_blog();
}
}
}
/** This filter is documented in wp-includes/class-wp-theme.php */
return (array) apply_filters( 'site_allowed_themes', $allowed_themes[ $blog_id ], $blog_id );
}
```
[apply\_filters( 'site\_allowed\_themes', string[] $allowed\_themes, int $blog\_id )](../../hooks/site_allowed_themes)
Filters the array of themes allowed on the site.
| Uses | Description |
| --- | --- |
| [delete\_option()](../../functions/delete_option) wp-includes/option.php | Removes option by name. Prevents removal of protected WordPress options. |
| [wp\_get\_themes()](../../functions/wp_get_themes) wp-includes/theme.php | Returns an array of [WP\_Theme](../wp_theme) objects based on the arguments. |
| [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) . |
| [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. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| [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. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [wpmu\_get\_blog\_allowedthemes()](../../functions/wpmu_get_blog_allowedthemes) wp-admin/includes/ms-deprecated.php | Deprecated functionality for getting themes allowed on a specific site. |
| [wp\_get\_themes()](../../functions/wp_get_themes) wp-includes/theme.php | Returns an array of [WP\_Theme](../wp_theme) objects based on the arguments. |
| [WP\_Theme::get\_allowed()](get_allowed) wp-includes/class-wp-theme.php | Returns array of stylesheet names of themes allowed on the site or network. |
| [WP\_Theme::is\_allowed()](is_allowed) wp-includes/class-wp-theme.php | Determines whether the theme is allowed (multisite only). |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::__get( string $offset ): mixed WP\_Theme::\_\_get( string $offset ): mixed
===========================================
\_\_get() magic method for properties formerly returned by [current\_theme\_info()](../../functions/current_theme_info)
`$offset` string Required Property to get. mixed Property value.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function __get( $offset ) {
switch ( $offset ) {
case 'name':
case 'title':
return $this->get( 'Name' );
case 'version':
return $this->get( 'Version' );
case 'parent_theme':
return $this->parent() ? $this->parent()->get( 'Name' ) : '';
case 'template_dir':
return $this->get_template_directory();
case 'stylesheet_dir':
return $this->get_stylesheet_directory();
case 'template':
return $this->get_template();
case 'stylesheet':
return $this->get_stylesheet();
case 'screenshot':
return $this->get_screenshot( 'relative' );
// 'author' and 'description' did not previously return translated data.
case 'description':
return $this->display( 'Description' );
case 'author':
return $this->display( 'Author' );
case 'tags':
return $this->get( 'Tags' );
case 'theme_root':
return $this->get_theme_root();
case 'theme_root_uri':
return $this->get_theme_root_uri();
// For cases where the array was converted to an object.
default:
return $this->offsetGet( $offset );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::get\_template\_directory()](get_template_directory) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of a theme’s “template” files. |
| [WP\_Theme::get\_stylesheet\_directory()](get_stylesheet_directory) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of a theme’s “stylesheet” files. |
| [WP\_Theme::get\_template()](get_template) wp-includes/class-wp-theme.php | Returns the directory name of the theme’s “template” files, inside the theme root. |
| [WP\_Theme::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-theme.php | Returns the directory name of the theme’s “stylesheet” files, inside the theme root. |
| [WP\_Theme::get\_screenshot()](get_screenshot) wp-includes/class-wp-theme.php | Returns the main screenshot file for the theme. |
| [WP\_Theme::get\_theme\_root()](get_theme_root) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of the theme root. |
| [WP\_Theme::get\_theme\_root\_uri()](get_theme_root_uri) wp-includes/class-wp-theme.php | Returns the URL to the directory of the theme root. |
| [WP\_Theme::get()](get) wp-includes/class-wp-theme.php | Gets a raw, unformatted theme header. |
| [WP\_Theme::parent()](parent) wp-includes/class-wp-theme.php | Returns reference to the parent theme. |
| [WP\_Theme::display()](display) wp-includes/class-wp-theme.php | Gets a theme header, formatted and translated for display. |
| [WP\_Theme::offsetGet()](offsetget) wp-includes/class-wp-theme.php | |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::get_screenshot( string $uri = 'uri' ): string|false WP\_Theme::get\_screenshot( string $uri = 'uri' ): string|false
===============================================================
Returns the main screenshot file for the theme.
The main screenshot is called screenshot.png. gif and jpg extensions are also allowed.
Screenshots for a theme must be in the stylesheet directory. (In the case of child themes, parent theme screenshots are not inherited.)
`$uri` string Optional Type of URL to return, either `'relative'` or an absolute URI. Defaults to absolute URI. Default: `'uri'`
string|false Screenshot file. False if the theme does not have a screenshot.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get_screenshot( $uri = 'uri' ) {
$screenshot = $this->cache_get( 'screenshot' );
if ( $screenshot ) {
if ( 'relative' === $uri ) {
return $screenshot;
}
return $this->get_stylesheet_directory_uri() . '/' . $screenshot;
} elseif ( 0 === $screenshot ) {
return false;
}
foreach ( array( 'png', 'gif', 'jpg', 'jpeg', 'webp' ) as $ext ) {
if ( file_exists( $this->get_stylesheet_directory() . "/screenshot.$ext" ) ) {
$this->cache_add( 'screenshot', 'screenshot.' . $ext );
if ( 'relative' === $uri ) {
return 'screenshot.' . $ext;
}
return $this->get_stylesheet_directory_uri() . '/' . 'screenshot.' . $ext;
}
}
$this->cache_add( 'screenshot', 0 );
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::get\_stylesheet\_directory\_uri()](get_stylesheet_directory_uri) wp-includes/class-wp-theme.php | Returns the URL to the directory of a theme’s “stylesheet” files. |
| [WP\_Theme::get\_stylesheet\_directory()](get_stylesheet_directory) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of a theme’s “stylesheet” files. |
| [WP\_Theme::cache\_get()](cache_get) wp-includes/class-wp-theme.php | Gets theme data from cache. |
| [WP\_Theme::cache\_add()](cache_add) wp-includes/class-wp-theme.php | Adds theme data to cache. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::\_\_get()](__get) wp-includes/class-wp-theme.php | \_\_get() magic method for properties formerly returned by [current\_theme\_info()](../../functions/current_theme_info) |
| [WP\_Theme::offsetGet()](offsetget) wp-includes/class-wp-theme.php | |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::display( string $header, bool $markup = true, bool $translate = true ): string|array|false WP\_Theme::display( string $header, bool $markup = true, bool $translate = true ): string|array|false
=====================================================================================================
Gets a theme header, formatted and translated for display.
`$header` string Required Theme header. Name, Description, Author, Version, ThemeURI, AuthorURI, Status, Tags. `$markup` bool Optional Whether to mark up the header. Defaults to true. Default: `true`
`$translate` bool Optional Whether to translate the header. Defaults to true. Default: `true`
string|array|false Processed header. An array for Tags if `$markup` is false, string otherwise.
False on failure.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function display( $header, $markup = true, $translate = true ) {
$value = $this->get( $header );
if ( false === $value ) {
return false;
}
if ( $translate && ( empty( $value ) || ! $this->load_textdomain() ) ) {
$translate = false;
}
if ( $translate ) {
$value = $this->translate_header( $header, $value );
}
if ( $markup ) {
$value = $this->markup_header( $header, $value, $translate );
}
return $value;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::load\_textdomain()](load_textdomain) wp-includes/class-wp-theme.php | Loads the theme’s textdomain. |
| [WP\_Theme::translate\_header()](translate_header) wp-includes/class-wp-theme.php | Translates a theme header. |
| [WP\_Theme::markup\_header()](markup_header) wp-includes/class-wp-theme.php | Marks up a theme header. |
| [WP\_Theme::get()](get) wp-includes/class-wp-theme.php | Gets a raw, unformatted theme header. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::markup\_header()](markup_header) wp-includes/class-wp-theme.php | Marks up a theme header. |
| [WP\_Theme::\_\_toString()](__tostring) wp-includes/class-wp-theme.php | When converting the object to a string, the theme name is returned. |
| [WP\_Theme::\_\_get()](__get) wp-includes/class-wp-theme.php | \_\_get() magic method for properties formerly returned by [current\_theme\_info()](../../functions/current_theme_info) |
| [WP\_Theme::offsetGet()](offsetget) wp-includes/class-wp-theme.php | |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::__isset( string $offset ): bool WP\_Theme::\_\_isset( string $offset ): bool
============================================
\_\_isset() magic method for properties formerly returned by [current\_theme\_info()](../../functions/current_theme_info)
`$offset` string Required Property to check if set. bool Whether the given property is set.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function __isset( $offset ) {
static $properties = array(
'name',
'title',
'version',
'parent_theme',
'template_dir',
'stylesheet_dir',
'template',
'stylesheet',
'screenshot',
'description',
'author',
'tags',
'theme_root',
'theme_root_uri',
);
return in_array( $offset, $properties, true );
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::scandir( string $path, array|string|null $extensions = null, int $depth, string $relative_path = '' ): string[]|false WP\_Theme::scandir( string $path, array|string|null $extensions = null, int $depth, string $relative\_path = '' ): 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.
Scans a directory for files of a certain extension.
`$path` string Required Absolute path to search. `$extensions` array|string|null Optional Array of extensions to find, string of a single extension, or null for all extensions. Default: `null`
`$depth` int Optional How many levels deep to search for files. Accepts 0, 1+, or -1 (infinite depth). Default 0. `$relative_path` string Optional The basename of the absolute path. Used to control the returned path for the found files, particularly when this function recurses to lower depths. Default: `''`
string[]|false Array of files, keyed by the path to the file relative to the `$path` directory prepended with `$relative_path`, with the values being absolute paths. False otherwise.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
private static function scandir( $path, $extensions = null, $depth = 0, $relative_path = '' ) {
if ( ! is_dir( $path ) ) {
return false;
}
if ( $extensions ) {
$extensions = (array) $extensions;
$_extensions = implode( '|', $extensions );
}
$relative_path = trailingslashit( $relative_path );
if ( '/' === $relative_path ) {
$relative_path = '';
}
$results = scandir( $path );
$files = array();
/**
* Filters the array of excluded directories and files while scanning theme folder.
*
* @since 4.7.4
*
* @param string[] $exclusions Array of excluded directories and files.
*/
$exclusions = (array) apply_filters( 'theme_scandir_exclusions', array( 'CVS', 'node_modules', 'vendor', 'bower_components' ) );
foreach ( $results as $result ) {
if ( '.' === $result[0] || in_array( $result, $exclusions, true ) ) {
continue;
}
if ( is_dir( $path . '/' . $result ) ) {
if ( ! $depth ) {
continue;
}
$found = self::scandir( $path . '/' . $result, $extensions, $depth - 1, $relative_path . $result );
$files = array_merge_recursive( $files, $found );
} elseif ( ! $extensions || preg_match( '~\.(' . $_extensions . ')$~', $result ) ) {
$files[ $relative_path . $result ] = $path . '/' . $result;
}
}
return $files;
}
```
[apply\_filters( 'theme\_scandir\_exclusions', string[] $exclusions )](../../hooks/theme_scandir_exclusions)
Filters the array of excluded directories and files while scanning theme folder.
| Uses | Description |
| --- | --- |
| [WP\_Theme::scandir()](scandir) wp-includes/class-wp-theme.php | Scans a directory for files of a certain extension. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [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::get\_files()](get_files) wp-includes/class-wp-theme.php | Returns files in the theme’s directory. |
| [WP\_Theme::scandir()](scandir) wp-includes/class-wp-theme.php | Scans a directory for files of a certain extension. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::translate_header( string $header, string|array $value ): string|array WP\_Theme::translate\_header( string $header, string|array $value ): string|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.
Translates a theme header.
`$header` string Required Theme header. Name, Description, Author, Version, ThemeURI, AuthorURI, Status, Tags. `$value` string|array Required Value to translate. An array for Tags header, string otherwise. string|array Translated value. An array for Tags header, string otherwise.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
private function translate_header( $header, $value ) {
switch ( $header ) {
case 'Name':
// Cached for sorting reasons.
if ( isset( $this->name_translated ) ) {
return $this->name_translated;
}
// phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText,WordPress.WP.I18n.NonSingularStringLiteralDomain
$this->name_translated = translate( $value, $this->get( 'TextDomain' ) );
return $this->name_translated;
case 'Tags':
if ( empty( $value ) || ! function_exists( 'get_theme_feature_list' ) ) {
return $value;
}
static $tags_list;
if ( ! isset( $tags_list ) ) {
$tags_list = array(
// As of 4.6, deprecated tags which are only used to provide translation for older themes.
'black' => __( 'Black' ),
'blue' => __( 'Blue' ),
'brown' => __( 'Brown' ),
'gray' => __( 'Gray' ),
'green' => __( 'Green' ),
'orange' => __( 'Orange' ),
'pink' => __( 'Pink' ),
'purple' => __( 'Purple' ),
'red' => __( 'Red' ),
'silver' => __( 'Silver' ),
'tan' => __( 'Tan' ),
'white' => __( 'White' ),
'yellow' => __( 'Yellow' ),
'dark' => _x( 'Dark', 'color scheme' ),
'light' => _x( 'Light', 'color scheme' ),
'fixed-layout' => __( 'Fixed Layout' ),
'fluid-layout' => __( 'Fluid Layout' ),
'responsive-layout' => __( 'Responsive Layout' ),
'blavatar' => __( 'Blavatar' ),
'photoblogging' => __( 'Photoblogging' ),
'seasonal' => __( 'Seasonal' ),
);
$feature_list = get_theme_feature_list( false ); // No API.
foreach ( $feature_list as $tags ) {
$tags_list += $tags;
}
}
foreach ( $value as &$tag ) {
if ( isset( $tags_list[ $tag ] ) ) {
$tag = $tags_list[ $tag ];
} elseif ( isset( self::$tag_map[ $tag ] ) ) {
$tag = $tags_list[ self::$tag_map[ $tag ] ];
}
}
return $value;
default:
// phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText,WordPress.WP.I18n.NonSingularStringLiteralDomain
$value = translate( $value, $this->get( 'TextDomain' ) );
}
return $value;
}
```
| Uses | Description |
| --- | --- |
| [get\_theme\_feature\_list()](../../functions/get_theme_feature_list) wp-admin/includes/theme.php | Retrieves list of WordPress theme features (aka theme tags). |
| [translate()](../../functions/translate) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Theme::get()](get) wp-includes/class-wp-theme.php | Gets a raw, unformatted theme header. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::get\_post\_templates()](get_post_templates) wp-includes/class-wp-theme.php | Returns the theme’s post templates. |
| [WP\_Theme::display()](display) wp-includes/class-wp-theme.php | Gets a theme header, formatted and translated for display. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
| programming_docs |
wordpress WP_Theme::get_template(): string WP\_Theme::get\_template(): string
==================================
Returns the directory name of the theme’s “template” files, inside the theme root.
In the case of a child theme, this is the directory name of the parent theme.
Otherwise, the [get\_template()](../../functions/get_template) is the same as [get\_stylesheet()](../../functions/get_stylesheet) .
string Template
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get_template() {
return $this->template;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Theme::\_\_get()](__get) wp-includes/class-wp-theme.php | \_\_get() magic method for properties formerly returned by [current\_theme\_info()](../../functions/current_theme_info) |
| [WP\_Theme::offsetGet()](offsetget) wp-includes/class-wp-theme.php | |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::get_core_default_theme(): WP_Theme|false WP\_Theme::get\_core\_default\_theme(): WP\_Theme|false
=======================================================
Determines the latest WordPress default theme that is installed.
This hits the filesystem.
[WP\_Theme](../wp_theme)|false Object, or false if no theme is installed, which would be bad.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public static function get_core_default_theme() {
foreach ( array_reverse( self::$default_themes ) as $slug => $name ) {
$theme = wp_get_theme( $slug );
if ( $theme->exists() ) {
return $theme;
}
}
return false;
}
```
| 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\_Site\_Health::get\_test\_theme\_version()](../wp_site_health/get_test_theme_version) wp-admin/includes/class-wp-site-health.php | Tests if themes are outdated, or unnecessary. |
| [populate\_network\_meta()](../../functions/populate_network_meta) wp-admin/includes/schema.php | Creates WordPress network meta and sets the default values. |
| [populate\_options()](../../functions/populate_options) wp-admin/includes/schema.php | Create WordPress options and set the default values. |
| [validate\_current\_theme()](../../functions/validate_current_theme) wp-includes/theme.php | Checks that the active theme has the required files. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Theme::offsetExists( $offset ) WP\_Theme::offsetExists( $offset )
==================================
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function offsetExists( $offset ) {
static $keys = array(
'Name',
'Version',
'Status',
'Title',
'Author',
'Author Name',
'Author URI',
'Description',
'Template',
'Stylesheet',
'Template Files',
'Stylesheet Files',
'Template Dir',
'Stylesheet Dir',
'Screenshot',
'Tags',
'Theme Root',
'Theme Root URI',
'Parent Theme',
);
return in_array( $offset, $keys, true );
}
```
wordpress WP_Theme::__toString(): string WP\_Theme::\_\_toString(): string
=================================
When converting the object to a string, the theme name is returned.
string Theme name, ready for display (translated)
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function __toString() {
return (string) $this->display( 'Name' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::display()](display) wp-includes/class-wp-theme.php | Gets a theme header, formatted and translated for display. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::errors(): WP_Error|false WP\_Theme::errors(): WP\_Error|false
====================================
Returns errors property.
[WP\_Error](../wp_error)|false [WP\_Error](../wp_error) if there are errors, or false.
Returns [WP\_Error](../wp_error "Class Reference/WP Error") object with error information. If there isn’t any error information then it returns false.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function errors() {
return is_wp_error( $this->errors ) ? $this->errors : 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\_Theme::get\_post\_templates()](get_post_templates) wp-includes/class-wp-theme.php | Returns the theme’s post templates. |
| [wp\_get\_themes()](../../functions/wp_get_themes) wp-includes/theme.php | Returns an array of [WP\_Theme](../wp_theme) objects based on the arguments. |
| [WP\_Theme::get\_stylesheet\_directory()](get_stylesheet_directory) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of a theme’s “stylesheet” files. |
| [WP\_Theme::exists()](exists) wp-includes/class-wp-theme.php | Determines whether the theme exists. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::__construct( string $theme_dir, string $theme_root, WP_Theme|null $_child = null ) WP\_Theme::\_\_construct( string $theme\_dir, string $theme\_root, WP\_Theme|null $\_child = null )
===================================================================================================
Constructor for [WP\_Theme](../wp_theme).
`$theme_dir` string Required Directory of the theme within the theme\_root. `$theme_root` string Required Theme root. `$_child` [WP\_Theme](../wp_theme)|null Optional If this theme is a parent theme, the child may be passed for validation purposes. Default: `null`
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function __construct( $theme_dir, $theme_root, $_child = null ) {
global $wp_theme_directories;
// Initialize caching on first run.
if ( ! isset( self::$persistently_cache ) ) {
/** This action is documented in wp-includes/theme.php */
self::$persistently_cache = apply_filters( 'wp_cache_themes_persistently', false, 'WP_Theme' );
if ( self::$persistently_cache ) {
wp_cache_add_global_groups( 'themes' );
if ( is_int( self::$persistently_cache ) ) {
self::$cache_expiration = self::$persistently_cache;
}
} else {
wp_cache_add_non_persistent_groups( 'themes' );
}
}
$this->theme_root = $theme_root;
$this->stylesheet = $theme_dir;
// Correct a situation where the theme is 'some-directory/some-theme' but 'some-directory' was passed in as part of the theme root instead.
if ( ! in_array( $theme_root, (array) $wp_theme_directories, true )
&& in_array( dirname( $theme_root ), (array) $wp_theme_directories, true )
) {
$this->stylesheet = basename( $this->theme_root ) . '/' . $this->stylesheet;
$this->theme_root = dirname( $theme_root );
}
$this->cache_hash = md5( $this->theme_root . '/' . $this->stylesheet );
$theme_file = $this->stylesheet . '/style.css';
$cache = $this->cache_get( 'theme' );
if ( is_array( $cache ) ) {
foreach ( array( 'errors', 'headers', 'template' ) as $key ) {
if ( isset( $cache[ $key ] ) ) {
$this->$key = $cache[ $key ];
}
}
if ( $this->errors ) {
return;
}
if ( isset( $cache['theme_root_template'] ) ) {
$theme_root_template = $cache['theme_root_template'];
}
} elseif ( ! file_exists( $this->theme_root . '/' . $theme_file ) ) {
$this->headers['Name'] = $this->stylesheet;
if ( ! file_exists( $this->theme_root . '/' . $this->stylesheet ) ) {
$this->errors = new WP_Error(
'theme_not_found',
sprintf(
/* translators: %s: Theme directory name. */
__( 'The theme directory "%s" does not exist.' ),
esc_html( $this->stylesheet )
)
);
} else {
$this->errors = new WP_Error( 'theme_no_stylesheet', __( 'Stylesheet is missing.' ) );
}
$this->template = $this->stylesheet;
$this->cache_add(
'theme',
array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
'template' => $this->template,
)
);
if ( ! file_exists( $this->theme_root ) ) { // Don't cache this one.
$this->errors->add( 'theme_root_missing', __( '<strong>Error:</strong> The themes directory is either empty or does not exist. Please check your installation.' ) );
}
return;
} elseif ( ! is_readable( $this->theme_root . '/' . $theme_file ) ) {
$this->headers['Name'] = $this->stylesheet;
$this->errors = new WP_Error( 'theme_stylesheet_not_readable', __( 'Stylesheet is not readable.' ) );
$this->template = $this->stylesheet;
$this->cache_add(
'theme',
array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
'template' => $this->template,
)
);
return;
} else {
$this->headers = get_file_data( $this->theme_root . '/' . $theme_file, self::$file_headers, 'theme' );
// Default themes always trump their pretenders.
// Properly identify default themes that are inside a directory within wp-content/themes.
$default_theme_slug = array_search( $this->headers['Name'], self::$default_themes, true );
if ( $default_theme_slug ) {
if ( basename( $this->stylesheet ) != $default_theme_slug ) {
$this->headers['Name'] .= '/' . $this->stylesheet;
}
}
}
if ( ! $this->template && $this->stylesheet === $this->headers['Template'] ) {
$this->errors = new WP_Error(
'theme_child_invalid',
sprintf(
/* translators: %s: Template. */
__( 'The theme defines itself as its parent theme. Please check the %s header.' ),
'<code>Template</code>'
)
);
$this->cache_add(
'theme',
array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
)
);
return;
}
// (If template is set from cache [and there are no errors], we know it's good.)
if ( ! $this->template ) {
$this->template = $this->headers['Template'];
}
if ( ! $this->template ) {
$this->template = $this->stylesheet;
$theme_path = $this->theme_root . '/' . $this->stylesheet;
if (
! file_exists( $theme_path . '/templates/index.html' )
&& ! file_exists( $theme_path . '/block-templates/index.html' ) // Deprecated path support since 5.9.0.
&& ! file_exists( $theme_path . '/index.php' )
) {
$error_message = sprintf(
/* translators: 1: templates/index.html, 2: index.php, 3: Documentation URL, 4: Template, 5: style.css */
__( 'Template is missing. Standalone themes need to have a %1$s or %2$s template file. <a href="%3$s">Child themes</a> need to have a %4$s header in the %5$s stylesheet.' ),
'<code>templates/index.html</code>',
'<code>index.php</code>',
__( 'https://developer.wordpress.org/themes/advanced-topics/child-themes/' ),
'<code>Template</code>',
'<code>style.css</code>'
);
$this->errors = new WP_Error( 'theme_no_index', $error_message );
$this->cache_add(
'theme',
array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
'template' => $this->template,
)
);
return;
}
}
// If we got our data from cache, we can assume that 'template' is pointing to the right place.
if ( ! is_array( $cache ) && $this->template != $this->stylesheet && ! file_exists( $this->theme_root . '/' . $this->template . '/index.php' ) ) {
// If we're in a directory of themes inside /themes, look for the parent nearby.
// wp-content/themes/directory-of-themes/*
$parent_dir = dirname( $this->stylesheet );
$directories = search_theme_directories();
if ( '.' !== $parent_dir && file_exists( $this->theme_root . '/' . $parent_dir . '/' . $this->template . '/index.php' ) ) {
$this->template = $parent_dir . '/' . $this->template;
} elseif ( $directories && isset( $directories[ $this->template ] ) ) {
// Look for the template in the search_theme_directories() results, in case it is in another theme root.
// We don't look into directories of themes, just the theme root.
$theme_root_template = $directories[ $this->template ]['theme_root'];
} else {
// Parent theme is missing.
$this->errors = new WP_Error(
'theme_no_parent',
sprintf(
/* translators: %s: Theme directory name. */
__( 'The parent theme is missing. Please install the "%s" parent theme.' ),
esc_html( $this->template )
)
);
$this->cache_add(
'theme',
array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
'template' => $this->template,
)
);
$this->parent = new WP_Theme( $this->template, $this->theme_root, $this );
return;
}
}
// Set the parent, if we're a child theme.
if ( $this->template != $this->stylesheet ) {
// If we are a parent, then there is a problem. Only two generations allowed! Cancel things out.
if ( $_child instanceof WP_Theme && $_child->template == $this->stylesheet ) {
$_child->parent = null;
$_child->errors = new WP_Error(
'theme_parent_invalid',
sprintf(
/* translators: %s: Theme directory name. */
__( 'The "%s" theme is not a valid parent theme.' ),
esc_html( $_child->template )
)
);
$_child->cache_add(
'theme',
array(
'headers' => $_child->headers,
'errors' => $_child->errors,
'stylesheet' => $_child->stylesheet,
'template' => $_child->template,
)
);
// The two themes actually reference each other with the Template header.
if ( $_child->stylesheet == $this->template ) {
$this->errors = new WP_Error(
'theme_parent_invalid',
sprintf(
/* translators: %s: Theme directory name. */
__( 'The "%s" theme is not a valid parent theme.' ),
esc_html( $this->template )
)
);
$this->cache_add(
'theme',
array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
'template' => $this->template,
)
);
}
return;
}
// Set the parent. Pass the current instance so we can do the crazy checks above and assess errors.
$this->parent = new WP_Theme( $this->template, isset( $theme_root_template ) ? $theme_root_template : $this->theme_root, $this );
}
if ( wp_paused_themes()->get( $this->stylesheet ) && ( ! is_wp_error( $this->errors ) || ! isset( $this->errors->errors['theme_paused'] ) ) ) {
$this->errors = new WP_Error( 'theme_paused', __( 'This theme failed to load properly and was paused within the admin backend.' ) );
}
// We're good. If we didn't retrieve from cache, set it.
if ( ! is_array( $cache ) ) {
$cache = array(
'headers' => $this->headers,
'errors' => $this->errors,
'stylesheet' => $this->stylesheet,
'template' => $this->template,
);
// If the parent theme is in another root, we'll want to cache this. Avoids an entire branch of filesystem calls above.
if ( isset( $theme_root_template ) ) {
$cache['theme_root_template'] = $theme_root_template;
}
$this->cache_add( 'theme', $cache );
}
}
```
[apply\_filters( 'wp\_cache\_themes\_persistently', bool $cache\_expiration, string $context )](../../hooks/wp_cache_themes_persistently)
Filters whether to get the cache of the registered theme directories.
| Uses | Description |
| --- | --- |
| [wp\_paused\_themes()](../../functions/wp_paused_themes) wp-includes/error-protection.php | Get the instance for storing paused extensions. |
| [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. |
| [wp\_cache\_add\_non\_persistent\_groups()](../../functions/wp_cache_add_non_persistent_groups) wp-includes/cache.php | Adds a group or set of groups to the list of non-persistent groups. |
| [search\_theme\_directories()](../../functions/search_theme_directories) wp-includes/theme.php | Searches all registered theme directories for complete and valid themes. |
| [WP\_Theme::cache\_get()](cache_get) wp-includes/class-wp-theme.php | Gets theme data from cache. |
| [WP\_Theme::cache\_add()](cache_add) wp-includes/class-wp-theme.php | Adds theme data to cache. |
| [WP\_Theme::\_\_construct()](__construct) wp-includes/class-wp-theme.php | Constructor for [WP\_Theme](../wp_theme). |
| [get\_file\_data()](../../functions/get_file_data) wp-includes/functions.php | Retrieves metadata from a file. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [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. |
| [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\_get\_themes()](../../functions/wp_get_themes) wp-includes/theme.php | Returns an array of [WP\_Theme](../wp_theme) objects based on the arguments. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [get\_theme\_data()](../../functions/get_theme_data) wp-includes/deprecated.php | Retrieve theme data from parsed theme file. |
| [WP\_Theme::cache\_delete()](cache_delete) wp-includes/class-wp-theme.php | Clears the cache for the theme. |
| [WP\_Theme::\_\_construct()](__construct) wp-includes/class-wp-theme.php | Constructor for [WP\_Theme](../wp_theme). |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::network_enable_theme( string|string[] $stylesheets ) WP\_Theme::network\_enable\_theme( string|string[] $stylesheets )
=================================================================
Enables a theme for all sites on the current network.
`$stylesheets` string|string[] Required Stylesheet name or array of stylesheet names. File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public static function network_enable_theme( $stylesheets ) {
if ( ! is_multisite() ) {
return;
}
if ( ! is_array( $stylesheets ) ) {
$stylesheets = array( $stylesheets );
}
$allowed_themes = get_site_option( 'allowedthemes' );
foreach ( $stylesheets as $stylesheet ) {
$allowed_themes[ $stylesheet ] = true;
}
update_site_option( 'allowedthemes', $allowed_themes );
}
```
| 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. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [get\_site\_option()](../../functions/get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
| programming_docs |
wordpress WP_Theme::parent(): WP_Theme|false WP\_Theme::parent(): WP\_Theme|false
====================================
Returns reference to the parent theme.
[WP\_Theme](../wp_theme)|false Parent theme, or false if the active theme is not a child theme.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function parent() {
return isset( $this->parent ) ? $this->parent : false;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Resolver::get\_theme\_data()](../wp_theme_json_resolver/get_theme_data) wp-includes/class-wp-theme-json-resolver.php | Returns the theme’s data. |
| [WP\_Theme::get\_template\_directory()](get_template_directory) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of a theme’s “template” files. |
| [WP\_Theme::get\_template\_directory\_uri()](get_template_directory_uri) wp-includes/class-wp-theme.php | Returns the URL to the directory of a theme’s “template” files. |
| [WP\_Theme::get\_files()](get_files) wp-includes/class-wp-theme.php | Returns files in the theme’s directory. |
| [WP\_Theme::\_\_get()](__get) wp-includes/class-wp-theme.php | \_\_get() magic method for properties formerly returned by [current\_theme\_info()](../../functions/current_theme_info) |
| [WP\_Theme::offsetGet()](offsetget) wp-includes/class-wp-theme.php | |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::get_template_directory(): string WP\_Theme::get\_template\_directory(): string
=============================================
Returns the absolute path to the directory of a theme’s “template” files.
In the case of a child theme, this is the absolute path to the directory of the parent theme’s files.
string Absolute path of the template directory.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get_template_directory() {
if ( $this->parent() ) {
$theme_root = $this->parent()->theme_root;
} else {
$theme_root = $this->theme_root;
}
return $theme_root . '/' . $this->template;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::parent()](parent) wp-includes/class-wp-theme.php | Returns reference to the parent theme. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::get\_file\_path()](get_file_path) wp-includes/class-wp-theme.php | Retrieves the path of a file in the theme. |
| [WP\_Theme::get\_files()](get_files) wp-includes/class-wp-theme.php | Returns files in the theme’s directory. |
| [WP\_Theme::\_\_get()](__get) wp-includes/class-wp-theme.php | \_\_get() magic method for properties formerly returned by [current\_theme\_info()](../../functions/current_theme_info) |
| [WP\_Theme::offsetGet()](offsetget) wp-includes/class-wp-theme.php | |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::get_files( string[]|string $type = null, int $depth, bool $search_parent = false ): string[] WP\_Theme::get\_files( string[]|string $type = null, int $depth, bool $search\_parent = false ): string[]
=========================================================================================================
Returns files in the theme’s directory.
`$type` string[]|string Optional Array of extensions to find, string of a single extension, or null for all extensions. Default: `null`
`$depth` int Optional How deep to search for files. Defaults to a flat scan (0 depth).
-1 depth is infinite. `$search_parent` bool Optional Whether to return parent files. Default: `false`
string[] Array of files, keyed by the path to the file relative to the theme's directory, with the values being absolute paths.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get_files( $type = null, $depth = 0, $search_parent = false ) {
$files = (array) self::scandir( $this->get_stylesheet_directory(), $type, $depth );
if ( $search_parent && $this->parent() ) {
$files += (array) self::scandir( $this->get_template_directory(), $type, $depth );
}
return array_filter( $files );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::scandir()](scandir) wp-includes/class-wp-theme.php | Scans a directory for files of a certain extension. |
| [WP\_Theme::get\_stylesheet\_directory()](get_stylesheet_directory) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of a theme’s “stylesheet” files. |
| [WP\_Theme::get\_template\_directory()](get_template_directory) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of a theme’s “template” files. |
| [WP\_Theme::parent()](parent) wp-includes/class-wp-theme.php | Returns reference to the parent theme. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::get\_post\_templates()](get_post_templates) wp-includes/class-wp-theme.php | Returns the theme’s post templates. |
| [WP\_Theme::offsetGet()](offsetget) wp-includes/class-wp-theme.php | |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::get_allowed( int $blog_id = null ): string[] WP\_Theme::get\_allowed( int $blog\_id = null ): string[]
=========================================================
Returns array of stylesheet names of themes allowed on the site or network.
`$blog_id` int Optional ID of the site. Defaults to the current site. Default: `null`
string[] Array of stylesheet names.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public static function get_allowed( $blog_id = null ) {
/**
* Filters the array of themes allowed on the network.
*
* Site is provided as context so that a list of network allowed themes can
* be filtered further.
*
* @since 4.5.0
*
* @param string[] $allowed_themes An array of theme stylesheet names.
* @param int $blog_id ID of the site.
*/
$network = (array) apply_filters( 'network_allowed_themes', self::get_allowed_on_network(), $blog_id );
return $network + self::get_allowed_on_site( $blog_id );
}
```
[apply\_filters( 'network\_allowed\_themes', string[] $allowed\_themes, int $blog\_id )](../../hooks/network_allowed_themes)
Filters the array of themes allowed on the network.
| Uses | Description |
| --- | --- |
| [WP\_Theme::get\_allowed\_on\_network()](get_allowed_on_network) wp-includes/class-wp-theme.php | Returns array of stylesheet names of themes allowed on the network. |
| [WP\_Theme::get\_allowed\_on\_site()](get_allowed_on_site) wp-includes/class-wp-theme.php | Returns array of stylesheet names of themes allowed on the site. |
| [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\_get\_themes()](../../functions/wp_get_themes) wp-includes/theme.php | Returns an array of [WP\_Theme](../wp_theme) objects based on the arguments. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::load_textdomain(): bool WP\_Theme::load\_textdomain(): bool
===================================
Loads the theme’s textdomain.
Translation files are not inherited from the parent theme. TODO: If this fails for the child theme, it should probably try to load the parent theme’s translations.
bool True if the textdomain was successfully loaded or has already been loaded.
False if no textdomain was specified in the file headers, or if the domain could not be loaded.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function load_textdomain() {
if ( isset( $this->textdomain_loaded ) ) {
return $this->textdomain_loaded;
}
$textdomain = $this->get( 'TextDomain' );
if ( ! $textdomain ) {
$this->textdomain_loaded = false;
return false;
}
if ( is_textdomain_loaded( $textdomain ) ) {
$this->textdomain_loaded = true;
return true;
}
$path = $this->get_stylesheet_directory();
$domainpath = $this->get( 'DomainPath' );
if ( $domainpath ) {
$path .= $domainpath;
} else {
$path .= '/languages';
}
$this->textdomain_loaded = load_theme_textdomain( $textdomain, $path );
return $this->textdomain_loaded;
}
```
| Uses | Description |
| --- | --- |
| [is\_textdomain\_loaded()](../../functions/is_textdomain_loaded) wp-includes/l10n.php | Determines whether there are translations for the text domain. |
| [load\_theme\_textdomain()](../../functions/load_theme_textdomain) wp-includes/l10n.php | Loads the theme’s translated strings. |
| [WP\_Theme::get\_stylesheet\_directory()](get_stylesheet_directory) wp-includes/class-wp-theme.php | Returns the absolute path to the directory of a theme’s “stylesheet” files. |
| [WP\_Theme::get()](get) wp-includes/class-wp-theme.php | Gets a raw, unformatted theme header. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::get\_post\_templates()](get_post_templates) wp-includes/class-wp-theme.php | Returns the theme’s post templates. |
| [WP\_Theme::display()](display) wp-includes/class-wp-theme.php | Gets a theme header, formatted and translated for display. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::network_disable_theme( string|string[] $stylesheets ) WP\_Theme::network\_disable\_theme( string|string[] $stylesheets )
==================================================================
Disables a theme for all sites on the current network.
`$stylesheets` string|string[] Required Stylesheet name or array of stylesheet names. File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public static function network_disable_theme( $stylesheets ) {
if ( ! is_multisite() ) {
return;
}
if ( ! is_array( $stylesheets ) ) {
$stylesheets = array( $stylesheets );
}
$allowed_themes = get_site_option( 'allowedthemes' );
foreach ( $stylesheets as $stylesheet ) {
if ( isset( $allowed_themes[ $stylesheet ] ) ) {
unset( $allowed_themes[ $stylesheet ] );
}
}
update_site_option( 'allowedthemes', $allowed_themes );
}
```
| 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. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [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 |
| --- | --- |
| [delete\_theme()](../../functions/delete_theme) wp-admin/includes/theme.php | Removes a theme. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Theme::get( string $header ): string|array|false WP\_Theme::get( string $header ): string|array|false
====================================================
Gets a raw, unformatted theme header.
The header is sanitized, but is not translated, and is not marked up for display.
To get a theme header for display, use the display() method.
Use the [get\_template()](../../functions/get_template) method, not the ‘Template’ header, for finding the template.
The ‘Template’ header is only good for what was written in the style.css, while [get\_template()](../../functions/get_template) takes into account where WordPress actually located the theme and whether it is actually valid.
`$header` string Required Theme header. Name, Description, Author, Version, ThemeURI, AuthorURI, Status, Tags. string|array|false String or array (for Tags header) on success, false on failure.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get( $header ) {
if ( ! isset( $this->headers[ $header ] ) ) {
return false;
}
if ( ! isset( $this->headers_sanitized ) ) {
$this->headers_sanitized = $this->cache_get( 'headers' );
if ( ! is_array( $this->headers_sanitized ) ) {
$this->headers_sanitized = array();
}
}
if ( isset( $this->headers_sanitized[ $header ] ) ) {
return $this->headers_sanitized[ $header ];
}
// If themes are a persistent group, sanitize everything and cache it. One cache add is better than many cache sets.
if ( self::$persistently_cache ) {
foreach ( array_keys( $this->headers ) as $_header ) {
$this->headers_sanitized[ $_header ] = $this->sanitize_header( $_header, $this->headers[ $_header ] );
}
$this->cache_add( 'headers', $this->headers_sanitized );
} else {
$this->headers_sanitized[ $header ] = $this->sanitize_header( $header, $this->headers[ $header ] );
}
return $this->headers_sanitized[ $header ];
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::cache\_get()](cache_get) wp-includes/class-wp-theme.php | Gets theme data from cache. |
| [WP\_Theme::sanitize\_header()](sanitize_header) wp-includes/class-wp-theme.php | Sanitizes a theme header. |
| [WP\_Theme::cache\_add()](cache_add) wp-includes/class-wp-theme.php | Adds theme data to cache. |
| Used By | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Resolver::get\_style\_variations()](../wp_theme_json_resolver/get_style_variations) wp-includes/class-wp-theme-json-resolver.php | Returns the style variations defined by the theme. |
| [WP\_Theme\_JSON\_Resolver::get\_theme\_data()](../wp_theme_json_resolver/get_theme_data) wp-includes/class-wp-theme-json-resolver.php | Returns the theme’s data. |
| [remove\_theme\_mods()](../../functions/remove_theme_mods) wp-includes/theme.php | Removes theme modifications option for the active theme. |
| [get\_theme\_mods()](../../functions/get_theme_mods) wp-includes/theme.php | Retrieves all theme modifications. |
| [get\_current\_theme()](../../functions/get_current_theme) wp-includes/deprecated.php | Retrieve current theme name. |
| [WP\_Theme::markup\_header()](markup_header) wp-includes/class-wp-theme.php | Marks up a theme header. |
| [WP\_Theme::translate\_header()](translate_header) wp-includes/class-wp-theme.php | Translates a theme header. |
| [WP\_Theme::load\_textdomain()](load_textdomain) wp-includes/class-wp-theme.php | Loads the theme’s textdomain. |
| [WP\_Theme::\_\_get()](__get) wp-includes/class-wp-theme.php | \_\_get() magic method for properties formerly returned by [current\_theme\_info()](../../functions/current_theme_info) |
| [WP\_Theme::offsetGet()](offsetget) wp-includes/class-wp-theme.php | |
| [WP\_Theme::display()](display) wp-includes/class-wp-theme.php | Gets a theme header, formatted and translated for display. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::cache_get( string $key ): mixed WP\_Theme::cache\_get( string $key ): mixed
===========================================
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 theme data from cache.
Cache entries are keyed by the theme and the type of data.
`$key` string Required Type of data to retrieve (theme, screenshot, headers, post\_templates) mixed Retrieved data
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
private function cache_get( $key ) {
return wp_cache_get( $key . '-' . $this->cache_hash, 'themes' );
}
```
| Uses | Description |
| --- | --- |
| [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\_Theme::get\_post\_templates()](get_post_templates) wp-includes/class-wp-theme.php | Returns the theme’s post templates. |
| [WP\_Theme::get\_screenshot()](get_screenshot) wp-includes/class-wp-theme.php | Returns the main screenshot file for the theme. |
| [WP\_Theme::get()](get) wp-includes/class-wp-theme.php | Gets a raw, unformatted theme header. |
| [WP\_Theme::\_\_construct()](__construct) wp-includes/class-wp-theme.php | Constructor for [WP\_Theme](../wp_theme). |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Theme::get_post_templates(): array[] WP\_Theme::get\_post\_templates(): array[]
==========================================
Returns the theme’s post templates.
array[] Array of page template arrays, keyed by post type and filename, with the value of the translated header name.
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function get_post_templates() {
// If you screw up your active theme and we invalidate your parent, most things still work. Let it slide.
if ( $this->errors() && $this->errors()->get_error_codes() !== array( 'theme_parent_invalid' ) ) {
return array();
}
$post_templates = $this->cache_get( 'post_templates' );
if ( ! is_array( $post_templates ) ) {
$post_templates = array();
$files = (array) $this->get_files( 'php', 1, true );
foreach ( $files as $file => $full_path ) {
if ( ! preg_match( '|Template Name:(.*)$|mi', file_get_contents( $full_path ), $header ) ) {
continue;
}
$types = array( 'page' );
if ( preg_match( '|Template Post Type:(.*)$|mi', file_get_contents( $full_path ), $type ) ) {
$types = explode( ',', _cleanup_header_comment( $type[1] ) );
}
foreach ( $types as $type ) {
$type = sanitize_key( $type );
if ( ! isset( $post_templates[ $type ] ) ) {
$post_templates[ $type ] = array();
}
$post_templates[ $type ][ $file ] = _cleanup_header_comment( $header[1] );
}
}
if ( current_theme_supports( 'block-templates' ) ) {
$block_templates = get_block_templates( array(), 'wp_template' );
foreach ( get_post_types( array( 'public' => true ) ) as $type ) {
foreach ( $block_templates as $block_template ) {
if ( ! $block_template->is_custom ) {
continue;
}
if ( isset( $block_template->post_types ) && ! in_array( $type, $block_template->post_types, true ) ) {
continue;
}
$post_templates[ $type ][ $block_template->slug ] = $block_template->title;
}
}
}
$this->cache_add( 'post_templates', $post_templates );
}
if ( $this->load_textdomain() ) {
foreach ( $post_templates as &$post_type ) {
foreach ( $post_type as &$post_template ) {
$post_template = $this->translate_header( 'Template Name', $post_template );
}
}
}
return $post_templates;
}
```
| Uses | Description |
| --- | --- |
| [get\_block\_templates()](../../functions/get_block_templates) wp-includes/block-template-utils.php | Retrieves a list of unified template objects based on a query. |
| [WP\_Theme::get\_files()](get_files) wp-includes/class-wp-theme.php | Returns files in the theme’s directory. |
| [WP\_Theme::load\_textdomain()](load_textdomain) wp-includes/class-wp-theme.php | Loads the theme’s textdomain. |
| [WP\_Theme::translate\_header()](translate_header) wp-includes/class-wp-theme.php | Translates a theme header. |
| [WP\_Theme::errors()](errors) wp-includes/class-wp-theme.php | Returns errors property. |
| [WP\_Theme::cache\_get()](cache_get) wp-includes/class-wp-theme.php | Gets theme data from cache. |
| [WP\_Theme::cache\_add()](cache_add) wp-includes/class-wp-theme.php | Adds theme data to cache. |
| [\_cleanup\_header\_comment()](../../functions/_cleanup_header_comment) wp-includes/functions.php | Strips close comment and close php tags from file headers used by WP. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [sanitize\_key()](../../functions/sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [get\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| Used By | Description |
| --- | --- |
| [WP\_Theme::get\_page\_templates()](get_page_templates) wp-includes/class-wp-theme.php | Returns the theme’s post templates for a given post type. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Include block templates. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Theme::is_block_theme(): bool WP\_Theme::is\_block\_theme(): bool
===================================
Returns whether this theme is a block-based theme or not.
bool
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
public function is_block_theme() {
$paths_to_index_block_template = array(
$this->get_file_path( '/block-templates/index.html' ),
$this->get_file_path( '/templates/index.html' ),
);
foreach ( $paths_to_index_block_template as $path_to_index_block_template ) {
if ( is_file( $path_to_index_block_template ) && is_readable( $path_to_index_block_template ) ) {
return true;
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::get\_file\_path()](get_file_path) wp-includes/class-wp-theme.php | Retrieves the path of a file in the theme. |
| Used By | Description |
| --- | --- |
| [wp\_is\_block\_theme()](../../functions/wp_is_block_theme) wp-includes/theme.php | Returns whether the active theme is a block-based theme or not. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Theme::_name_sort_i18n( WP_Theme $a, WP_Theme $b ): int WP\_Theme::\_name\_sort\_i18n( WP\_Theme $a, WP\_Theme $b ): 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.
Callback function for usort() to naturally sort themes by translated name.
`$a` [WP\_Theme](../wp_theme) Required First theme. `$b` [WP\_Theme](../wp_theme) Required Second theme. int Negative if `$a` falls lower in the natural order than `$b`. Zero if they fall equally.
Greater than 0 if `$a` falls higher in the natural order than `$b`. Used with usort().
File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/)
```
private static function _name_sort_i18n( $a, $b ) {
return strnatcasecmp( $a->name_translated, $b->name_translated );
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_REST_Pattern_Directory_Controller::prepare_item_for_response( object $item, WP_REST_Request $request ): WP_REST_Response WP\_REST\_Pattern\_Directory\_Controller::prepare\_item\_for\_response( object $item, WP\_REST\_Request $request ): WP\_REST\_Response
======================================================================================================================================
Prepare a raw block pattern before it gets output in a REST API response.
`$item` object Required Raw pattern from api.wordpress.org, before any changes. `$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. [WP\_REST\_Response](../wp_rest_response)
File: `wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php/)
```
public function prepare_item_for_response( $item, $request ) {
// Restores the more descriptive, specific name for use within this method.
$raw_pattern = $item;
$prepared_pattern = array(
'id' => absint( $raw_pattern->id ),
'title' => sanitize_text_field( $raw_pattern->title->rendered ),
'content' => wp_kses_post( $raw_pattern->pattern_content ),
'categories' => array_map( 'sanitize_title', $raw_pattern->category_slugs ),
'keywords' => array_map( 'sanitize_text_field', explode( ',', $raw_pattern->meta->wpop_keywords ) ),
'description' => sanitize_text_field( $raw_pattern->meta->wpop_description ),
'viewport_width' => absint( $raw_pattern->meta->wpop_viewport_width ),
);
$prepared_pattern = $this->add_additional_fields_to_object( $prepared_pattern, $request );
$response = new WP_REST_Response( $prepared_pattern );
/**
* Filters the REST API response for a block pattern.
*
* @since 5.8.0
*
* @param WP_REST_Response $response The response object.
* @param object $raw_pattern The unprepared block pattern.
* @param WP_REST_Request $request The request object.
*/
return apply_filters( 'rest_prepare_block_pattern', $response, $raw_pattern, $request );
}
```
[apply\_filters( 'rest\_prepare\_block\_pattern', WP\_REST\_Response $response, object $raw\_pattern, WP\_REST\_Request $request )](../../hooks/rest_prepare_block_pattern)
Filters the REST API response for a block pattern.
| Uses | Description |
| --- | --- |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [wp\_kses\_post()](../../functions/wp_kses_post) wp-includes/kses.php | Sanitizes content for allowed HTML tags for post content. |
| [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. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Pattern\_Directory\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php | Search and retrieve block patterns metadata |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$raw_pattern` 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_Pattern_Directory_Controller::get_items( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Pattern\_Directory\_Controller::get\_items( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
================================================================================================================
Search and retrieve block patterns metadata
`$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-pattern-directory-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php/)
```
public function get_items( $request ) {
/*
* Include an unmodified `$wp_version`, so the API can craft a response that's tailored to
* it. Some plugins modify the version in a misguided attempt to improve security by
* obscuring the version, which can cause invalid requests.
*/
require ABSPATH . WPINC . '/version.php';
$query_args = array(
'locale' => get_user_locale(),
'wp-version' => $wp_version,
);
$category_id = $request['category'];
$keyword_id = $request['keyword'];
$search_term = $request['search'];
$slug = $request['slug'];
if ( $category_id ) {
$query_args['pattern-categories'] = $category_id;
}
if ( $keyword_id ) {
$query_args['pattern-keywords'] = $keyword_id;
}
if ( $search_term ) {
$query_args['search'] = $search_term;
}
if ( $slug ) {
$query_args['slug'] = $slug;
}
$transient_key = $this->get_transient_key( $query_args );
/*
* Use network-wide transient to improve performance. The locale is the only site
* configuration that affects the response, and it's included in the transient key.
*/
$raw_patterns = get_site_transient( $transient_key );
if ( ! $raw_patterns ) {
$api_url = 'http://api.wordpress.org/patterns/1.0/?' . build_query( $query_args );
if ( wp_http_supports( array( 'ssl' ) ) ) {
$api_url = set_url_scheme( $api_url, 'https' );
}
/*
* Default to a short TTL, to mitigate cache stampedes on high-traffic sites.
* This assumes that most errors will be short-lived, e.g., packet loss that causes the
* first request to fail, but a follow-up one will succeed. The value should be high
* enough to avoid stampedes, but low enough to not interfere with users manually
* re-trying a failed request.
*/
$cache_ttl = 5;
$wporg_response = wp_remote_get( $api_url );
$raw_patterns = json_decode( wp_remote_retrieve_body( $wporg_response ) );
if ( is_wp_error( $wporg_response ) ) {
$raw_patterns = $wporg_response;
} elseif ( ! is_array( $raw_patterns ) ) {
// HTTP request succeeded, but response data is invalid.
$raw_patterns = new WP_Error(
'pattern_api_failed',
sprintf(
/* translators: %s: Support forums URL. */
__( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the <a href="%s">support forums</a>.' ),
__( 'https://wordpress.org/support/forums/' )
),
array(
'response' => wp_remote_retrieve_body( $wporg_response ),
)
);
} else {
// Response has valid data.
$cache_ttl = HOUR_IN_SECONDS;
}
set_site_transient( $transient_key, $raw_patterns, $cache_ttl );
}
if ( is_wp_error( $raw_patterns ) ) {
$raw_patterns->add_data( array( 'status' => 500 ) );
return $raw_patterns;
}
$response = array();
if ( $raw_patterns ) {
foreach ( $raw_patterns as $pattern ) {
$response[] = $this->prepare_response_for_collection(
$this->prepare_item_for_response( $pattern, $request )
);
}
}
return new WP_REST_Response( $response );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Pattern\_Directory\_Controller::get\_transient\_key()](get_transient_key) wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php | |
| [WP\_REST\_Pattern\_Directory\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php | Prepare a raw block pattern before it gets output in a REST API response. |
| [get\_user\_locale()](../../functions/get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| [build\_query()](../../functions/build_query) wp-includes/functions.php | Builds URL query based on an associative and, or indexed array. |
| [set\_url\_scheme()](../../functions/set_url_scheme) wp-includes/link-template.php | Sets the scheme for a URL. |
| [wp\_http\_supports()](../../functions/wp_http_supports) wp-includes/http.php | Determines if there is an HTTP Transport that can process this request. |
| [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\_body()](../../functions/wp_remote_retrieve_body) wp-includes/http.php | Retrieve only the body from the raw response. |
| [set\_site\_transient()](../../functions/set_site_transient) wp-includes/option.php | Sets/updates the value of a site transient. |
| [get\_site\_transient()](../../functions/get_site_transient) wp-includes/option.php | Retrieves the value of a site transient. |
| [\_\_()](../../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 |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Added `'slug'` to request. |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Pattern_Directory_Controller::get_transient_key( $query_args ) WP\_REST\_Pattern\_Directory\_Controller::get\_transient\_key( $query\_args )
=============================================================================
File: `wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php/)
```
protected function get_transient_key( $query_args ) {
if ( isset( $query_args['slug'] ) ) {
// This is an additional precaution because the "sort" function expects an array.
$query_args['slug'] = wp_parse_list( $query_args['slug'] );
// Empty arrays should not affect the transient key.
if ( empty( $query_args['slug'] ) ) {
unset( $query_args['slug'] );
} else {
// Sort the array so that the transient key doesn't depend on the order of slugs.
sort( $query_args['slug'] );
}
}
return 'wp_remote_block_patterns_' . md5( serialize( $query_args ) );
}
```
| Uses | Description |
| --- | --- |
| [wp\_parse\_list()](../../functions/wp_parse_list) wp-includes/functions.php | Converts a comma- or space-separated list of scalar values to an array. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Pattern\_Directory\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php | Search and retrieve block patterns metadata |
wordpress WP_REST_Pattern_Directory_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Pattern\_Directory\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
======================================================================================================================
Checks whether a given request has permission to view the local block pattern directory.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has permission, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-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_pattern_directory_cannot_view',
__( 'Sorry, you are not allowed to browse the local block pattern directory.' ),
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 |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Pattern_Directory_Controller::register_routes() WP\_REST\_Pattern\_Directory\_Controller::register\_routes()
============================================================
Registers the necessary REST API routes.
File: `wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php/)
```
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/patterns',
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' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Pattern\_Directory\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php | Retrieves the search parameters for the block pattern’s collection. |
| [register\_rest\_route()](../../functions/register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Pattern_Directory_Controller::get_collection_params(): array WP\_REST\_Pattern\_Directory\_Controller::get\_collection\_params(): array
==========================================================================
Retrieves the search parameters for the block pattern’s collection.
array Collection parameters.
File: `wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php/)
```
public function get_collection_params() {
$query_params = parent::get_collection_params();
// Pagination is not supported.
unset( $query_params['page'] );
unset( $query_params['per_page'] );
$query_params['search']['minLength'] = 1;
$query_params['context']['default'] = 'view';
$query_params['category'] = array(
'description' => __( 'Limit results to those matching a category ID.' ),
'type' => 'integer',
'minimum' => 1,
);
$query_params['keyword'] = array(
'description' => __( 'Limit results to those matching a keyword ID.' ),
'type' => 'integer',
'minimum' => 1,
);
$query_params['slug'] = array(
'description' => __( 'Limit results to those matching a pattern (slug).' ),
'type' => 'array',
);
/**
* Filter collection parameters for the block pattern directory controller.
*
* @since 5.8.0
*
* @param array $query_params JSON Schema-formatted collection parameters.
*/
return apply_filters( 'rest_pattern_directory_collection_params', $query_params );
}
```
[apply\_filters( 'rest\_pattern\_directory\_collection\_params', array $query\_params )](../../hooks/rest_pattern_directory_collection_params)
Filter collection parameters for the block pattern directory controller.
| 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. |
| [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\_Pattern\_Directory\_Controller::register\_routes()](register_routes) wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php | Registers the necessary REST API routes. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Pattern_Directory_Controller::__construct() WP\_REST\_Pattern\_Directory\_Controller::\_\_construct()
=========================================================
Constructs the controller.
File: `wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php/)
```
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'pattern-directory';
}
```
| 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_Pattern_Directory_Controller::get_item_schema(): array WP\_REST\_Pattern\_Directory\_Controller::get\_item\_schema(): array
====================================================================
Retrieves the block pattern’s schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-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' => 'pattern-directory-item',
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'The pattern ID.' ),
'type' => 'integer',
'minimum' => 1,
'context' => array( 'view', 'edit', 'embed' ),
),
'title' => array(
'description' => __( 'The pattern title, in human readable format.' ),
'type' => 'string',
'minLength' => 1,
'context' => array( 'view', 'edit', 'embed' ),
),
'content' => array(
'description' => __( 'The pattern content.' ),
'type' => 'string',
'minLength' => 1,
'context' => array( 'view', 'edit', 'embed' ),
),
'categories' => array(
'description' => __( "The pattern's category slugs." ),
'type' => 'array',
'uniqueItems' => true,
'items' => array( 'type' => 'string' ),
'context' => array( 'view', 'edit', 'embed' ),
),
'keywords' => array(
'description' => __( "The pattern's keywords." ),
'type' => 'array',
'uniqueItems' => true,
'items' => array( 'type' => 'string' ),
'context' => array( 'view', 'edit', 'embed' ),
),
'description' => array(
'description' => __( 'A description of the pattern.' ),
'type' => 'string',
'minLength' => 1,
'context' => array( 'view', 'edit', 'embed' ),
),
'viewport_width' => array(
'description' => __( 'The preferred width of the viewport when previewing a pattern, in pixels.' ),
'type' => 'integer',
'context' => array( 'view', 'edit', 'embed' ),
),
),
);
return $this->add_additional_fields_schema( $this->schema );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../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_List_Table::single_row( object|array $item ) WP\_List\_Table::single\_row( object|array $item )
==================================================
Generates content for a single row of the table.
`$item` object|array Required The current item This echos a single item (from the items property) to the page. Generally, you don’t need to call this explicitly as it is handled automatically on display().
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function single_row( $item ) {
echo '<tr>';
$this->single_row_columns( $item );
echo '</tr>';
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::single\_row\_columns()](single_row_columns) wp-admin/includes/class-wp-list-table.php | Generates the columns for a single row of the table. |
| Used By | Description |
| --- | --- |
| [display\_theme()](../../functions/display_theme) wp-admin/includes/theme-install.php | Prints a theme on the Install Themes pages. |
| [WP\_List\_Table::display\_rows()](display_rows) wp-admin/includes/class-wp-list-table.php | Generates the table rows. |
| [wp\_ajax\_add\_user()](../../functions/wp_ajax_add_user) wp-admin/includes/ajax-actions.php | Ajax handler for adding a user. |
| [wp\_ajax\_inline\_save\_tax()](../../functions/wp_ajax_inline_save_tax) wp-admin/includes/ajax-actions.php | Ajax handler for quick edit saving for a term. |
| [wp\_ajax\_add\_tag()](../../functions/wp_ajax_add_tag) wp-admin/includes/ajax-actions.php | Ajax handler to add a tag. |
| [wp\_ajax\_get\_comments()](../../functions/wp_ajax_get_comments) wp-admin/includes/ajax-actions.php | Ajax handler for getting comments. |
| [wp\_ajax\_replyto\_comment()](../../functions/wp_ajax_replyto_comment) wp-admin/includes/ajax-actions.php | Ajax handler for replying to a comment. |
| [wp\_ajax\_edit\_comment()](../../functions/wp_ajax_edit_comment) wp-admin/includes/ajax-actions.php | Ajax handler for editing a comment. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::extra_tablenav( string $which ) WP\_List\_Table::extra\_tablenav( string $which )
=================================================
Extra controls to be displayed between bulk actions and pagination.
`$which` string Required File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function extra_tablenav( $which ) {}
```
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::display\_tablenav()](display_tablenav) wp-admin/includes/class-wp-list-table.php | Generates the table navigation above or below the table |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::current_action(): string|false WP\_List\_Table::current\_action(): string|false
================================================
Gets the current action selected from the bulk actions dropdown.
string|false The action name. False if no action was selected.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function current_action() {
if ( isset( $_REQUEST['filter_action'] ) && ! empty( $_REQUEST['filter_action'] ) ) {
return false;
}
if ( isset( $_REQUEST['action'] ) && -1 != $_REQUEST['action'] ) {
return $_REQUEST['action'];
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Plugins\_List\_Table::current\_action()](../wp_plugins_list_table/current_action) wp-admin/includes/class-wp-plugins-list-table.php | |
| [WP\_Users\_List\_Table::current\_action()](../wp_users_list_table/current_action) wp-admin/includes/class-wp-users-list-table.php | Capture the bulk action required, and return it. |
| [WP\_Media\_List\_Table::current\_action()](../wp_media_list_table/current_action) wp-admin/includes/class-wp-media-list-table.php | |
| [WP\_Comments\_List\_Table::current\_action()](../wp_comments_list_table/current_action) wp-admin/includes/class-wp-comments-list-table.php | |
| [WP\_Terms\_List\_Table::current\_action()](../wp_terms_list_table/current_action) wp-admin/includes/class-wp-terms-list-table.php | |
| [WP\_Posts\_List\_Table::current\_action()](../wp_posts_list_table/current_action) wp-admin/includes/class-wp-posts-list-table.php | |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::prepare_items() WP\_List\_Table::prepare\_items()
=================================
Prepares the list of items for displaying.
Developers should use this class to query and filter data, handle sorting, and pagination, and any other data-manipulation required prior to rendering. This method should be called explicitly after instantiating your class, and before rendering.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function prepare_items() {
die( 'function WP_List_Table::prepare_items() must be overridden in a subclass.' );
}
```
| Used By | Description |
| --- | --- |
| [wp\_ajax\_search\_install\_plugins()](../../functions/wp_ajax_search_install_plugins) wp-admin/includes/ajax-actions.php | Ajax handler for searching plugins to install. |
| [wp\_ajax\_search\_plugins()](../../functions/wp_ajax_search_plugins) wp-admin/includes/ajax-actions.php | Ajax handler for searching plugins. |
| [display\_theme()](../../functions/display_theme) wp-admin/includes/theme-install.php | Prints a theme on the Install Themes pages. |
| [display\_themes()](../../functions/display_themes) wp-admin/includes/theme-install.php | Displays theme content based on theme list. |
| [WP\_List\_Table::ajax\_response()](ajax_response) wp-admin/includes/class-wp-list-table.php | Handles an incoming ajax request (called from admin-ajax.php) |
| [wp\_ajax\_get\_comments()](../../functions/wp_ajax_get_comments) wp-admin/includes/ajax-actions.php | Ajax handler for getting comments. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::ajax_user_can() WP\_List\_Table::ajax\_user\_can()
==================================
Checks the current user’s permissions
Can be overridden to provide some permissions functionality to your table.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function ajax_user_can() {
die( 'function WP_List_Table::ajax_user_can() must be overridden in a subclass.' );
}
```
| Used By | Description |
| --- | --- |
| [wp\_ajax\_search\_install\_plugins()](../../functions/wp_ajax_search_install_plugins) wp-admin/includes/ajax-actions.php | Ajax handler for searching plugins to install. |
| [wp\_ajax\_search\_plugins()](../../functions/wp_ajax_search_plugins) wp-admin/includes/ajax-actions.php | Ajax handler for searching plugins. |
| [wp\_ajax\_fetch\_list()](../../functions/wp_ajax_fetch_list) wp-admin/includes/ajax-actions.php | Ajax handler for fetching a list table. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::display_rows() WP\_List\_Table::display\_rows()
================================
Generates the table rows.
This loops through the items property and renders them to the page as table rows. Generally, you don’t need to call this explicitly as it is handled automatically on display().
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function display_rows() {
foreach ( $this->items as $item ) {
$this->single_row( $item );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::single\_row()](single_row) wp-admin/includes/class-wp-list-table.php | Generates content for a single row of the table. |
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::display\_rows\_or\_placeholder()](display_rows_or_placeholder) wp-admin/includes/class-wp-list-table.php | Generates the tbody element for the list table. |
| [WP\_List\_Table::ajax\_response()](ajax_response) wp-admin/includes/class-wp-list-table.php | Handles an incoming ajax request (called from admin-ajax.php) |
| [wp\_ajax\_inline\_save()](../../functions/wp_ajax_inline_save) wp-admin/includes/ajax-actions.php | Ajax handler for Quick Edit saving a post from a list table. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::no_items() WP\_List\_Table::no\_items()
============================
Message to be displayed when there are no items
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function no_items() {
_e( 'No items found.' );
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::display\_rows\_or\_placeholder()](display_rows_or_placeholder) wp-admin/includes/class-wp-list-table.php | Generates the tbody element for the list table. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::pagination( string $which ) WP\_List\_Table::pagination( string $which )
============================================
Displays the pagination.
`$which` string Required Creates the pagination HTML and assigns it to the \_pagination property. Generally, you don’t need to call this directly as it’s handled for you on display().
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function pagination( $which ) {
if ( empty( $this->_pagination_args ) ) {
return;
}
$total_items = $this->_pagination_args['total_items'];
$total_pages = $this->_pagination_args['total_pages'];
$infinite_scroll = false;
if ( isset( $this->_pagination_args['infinite_scroll'] ) ) {
$infinite_scroll = $this->_pagination_args['infinite_scroll'];
}
if ( 'top' === $which && $total_pages > 1 ) {
$this->screen->render_screen_reader_content( 'heading_pagination' );
}
$output = '<span class="displaying-num">' . sprintf(
/* translators: %s: Number of items. */
_n( '%s item', '%s items', $total_items ),
number_format_i18n( $total_items )
) . '</span>';
$current = $this->get_pagenum();
$removable_query_args = wp_removable_query_args();
$current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
$current_url = remove_query_arg( $removable_query_args, $current_url );
$page_links = array();
$total_pages_before = '<span class="paging-input">';
$total_pages_after = '</span></span>';
$disable_first = false;
$disable_last = false;
$disable_prev = false;
$disable_next = false;
if ( 1 == $current ) {
$disable_first = true;
$disable_prev = true;
}
if ( $total_pages == $current ) {
$disable_last = true;
$disable_next = true;
}
if ( $disable_first ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">«</span>';
} else {
$page_links[] = sprintf(
"<a class='first-page button' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
esc_url( remove_query_arg( 'paged', $current_url ) ),
__( 'First page' ),
'«'
);
}
if ( $disable_prev ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹</span>';
} else {
$page_links[] = sprintf(
"<a class='prev-page button' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
esc_url( add_query_arg( 'paged', max( 1, $current - 1 ), $current_url ) ),
__( 'Previous page' ),
'‹'
);
}
if ( 'bottom' === $which ) {
$html_current_page = $current;
$total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
} else {
$html_current_page = sprintf(
"%s<input class='current-page' id='current-page-selector' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
'<label for="current-page-selector" class="screen-reader-text">' . __( 'Current Page' ) . '</label>',
$current,
strlen( $total_pages )
);
}
$html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
$page_links[] = $total_pages_before . sprintf(
/* translators: 1: Current page, 2: Total pages. */
_x( '%1$s of %2$s', 'paging' ),
$html_current_page,
$html_total_pages
) . $total_pages_after;
if ( $disable_next ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">›</span>';
} else {
$page_links[] = sprintf(
"<a class='next-page button' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
esc_url( add_query_arg( 'paged', min( $total_pages, $current + 1 ), $current_url ) ),
__( 'Next page' ),
'›'
);
}
if ( $disable_last ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">»</span>';
} else {
$page_links[] = sprintf(
"<a class='last-page button' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
esc_url( add_query_arg( 'paged', $total_pages, $current_url ) ),
__( 'Last page' ),
'»'
);
}
$pagination_links_class = 'pagination-links';
if ( ! empty( $infinite_scroll ) ) {
$pagination_links_class .= ' hide-if-js';
}
$output .= "\n<span class='$pagination_links_class'>" . implode( "\n", $page_links ) . '</span>';
if ( $total_pages ) {
$page_class = $total_pages < 2 ? ' one-page' : '';
} else {
$page_class = ' no-pages';
}
$this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";
echo $this->_pagination;
}
```
| Uses | Description |
| --- | --- |
| [wp\_removable\_query\_args()](../../functions/wp_removable_query_args) wp-includes/functions.php | Returns an array of single-use query variable names that can be removed from a URL. |
| [WP\_List\_Table::get\_pagenum()](get_pagenum) wp-admin/includes/class-wp-list-table.php | Gets the current page number. |
| [\_n()](../../functions/_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [remove\_query\_arg()](../../functions/remove_query_arg) wp-includes/functions.php | Removes an item or items from a query string. |
| [set\_url\_scheme()](../../functions/set_url_scheme) wp-includes/link-template.php | Sets the scheme for a URL. |
| [\_\_()](../../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. |
| [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. |
| Used By | Description |
| --- | --- |
| [WP\_MS\_Users\_List\_Table::pagination()](../wp_ms_users_list_table/pagination) wp-admin/includes/class-wp-ms-users-list-table.php | |
| [WP\_List\_Table::display\_tablenav()](display_tablenav) wp-admin/includes/class-wp-list-table.php | Generates the table navigation above or below the table |
| [WP\_MS\_Sites\_List\_Table::pagination()](../wp_ms_sites_list_table/pagination) wp-admin/includes/class-wp-ms-sites-list-table.php | |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
| programming_docs |
wordpress WP_List_Table::get_default_primary_column_name(): string WP\_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, an empty string.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function get_default_primary_column_name() {
$columns = $this->get_columns();
$column = '';
if ( empty( $columns ) ) {
return $column;
}
// We need a primary defined so responsive views show something,
// so let's fall back to the first non-checkbox column.
foreach ( $columns as $col => $column_name ) {
if ( 'cb' === $col ) {
continue;
}
$column = $col;
break;
}
return $column;
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::get\_columns()](get_columns) wp-admin/includes/class-wp-list-table.php | Gets a list of columns. |
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::get\_primary\_column\_name()](get_primary_column_name) wp-admin/includes/class-wp-list-table.php | Gets the name of the primary column. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_List_Table::_js_vars() WP\_List\_Table::\_js\_vars()
=============================
Sends required variables to JavaScript land.
It outputs key Javascript variables that were dynamically created by the class.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function _js_vars() {
$args = array(
'class' => get_class( $this ),
'screen' => array(
'id' => $this->screen->id,
'base' => $this->screen->base,
),
);
printf( "<script type='text/javascript'>list_args = %s;</script>\n", wp_json_encode( $args ) );
}
```
| Uses | Description |
| --- | --- |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| Used By | 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.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::handle_row_actions( object|array $item, string $column_name, string $primary ): string WP\_List\_Table::handle\_row\_actions( object|array $item, string $column\_name, string $primary ): string
==========================================================================================================
Generates and display row actions links for the list table.
`$item` object|array Required The item being acted upon. `$column_name` string Required Current column name. `$primary` string Required Primary column name. string The row actions HTML, or an empty string if the current column is not the primary column.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function handle_row_actions( $item, $column_name, $primary ) {
return $column_name === $primary ? '<button type="button" class="toggle-row"><span class="screen-reader-text">' . __( 'Show more details' ) . '</span></button>' : '';
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::single\_row\_columns()](single_row_columns) wp-admin/includes/class-wp-list-table.php | Generates the columns for a single row of the table. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_List_Table::__unset( string $name ) WP\_List\_Table::\_\_unset( string $name )
==========================================
Make private properties un-settable for backward compatibility.
`$name` string Required Property to unset. File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.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_List_Table::get_views(): array WP\_List\_Table::get\_views(): array
====================================
Gets the list of views available on this table.
The format is an associative array:
* `'id' => 'link'`
array
This method returns an associative array listing all the views that can be used with this table.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function get_views() {
return array();
}
```
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::views()](views) wp-admin/includes/class-wp-list-table.php | Displays the list of views available on this table. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::get_column_count(): int WP\_List\_Table::get\_column\_count(): int
==========================================
Returns the number of visible columns.
int
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function get_column_count() {
list ( $columns, $hidden ) = $this->get_column_info();
$hidden = array_intersect( array_keys( $columns ), array_filter( $hidden ) );
return count( $columns ) - count( $hidden );
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::get\_column\_info()](get_column_info) wp-admin/includes/class-wp-list-table.php | Gets a list of all, hidden, and sortable columns, with filter applied. |
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::display\_rows\_or\_placeholder()](display_rows_or_placeholder) wp-admin/includes/class-wp-list-table.php | Generates the tbody element for the list table. |
| [wp\_plugin\_update\_row()](../../functions/wp_plugin_update_row) wp-admin/includes/update.php | Displays update information for a plugin. |
| [wp\_theme\_update\_row()](../../functions/wp_theme_update_row) wp-admin/includes/update.php | Displays update information for a theme. |
| [wp\_comment\_reply()](../../functions/wp_comment_reply) wp-admin/includes/template.php | Outputs the in-line comment reply-to form in the Comments list table. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::get_sortable_columns(): array WP\_List\_Table::get\_sortable\_columns(): array
================================================
Gets a list of sortable columns.
The format is:
* `'internal-name' => 'orderby'`
* `'internal-name' => array( 'orderby', 'asc' )` – The second element sets the initial sorting order.
* `'internal-name' => array( 'orderby', true )` – The second element makes the initial order descending.
array
This method should be overridden to return an associative array of columns that you want to make sortable. The associative array should follow the format 'column\_slug'=>array('sortby',true), where the second property states whether the field is presorted. This is frequently used to provide part of the \_column\_headers property.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function get_sortable_columns() {
return array();
}
```
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::get\_column\_info()](get_column_info) wp-admin/includes/class-wp-list-table.php | Gets a list of all, hidden, and sortable columns, with filter applied. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::display_rows_or_placeholder() WP\_List\_Table::display\_rows\_or\_placeholder()
=================================================
Generates the tbody element for the list table.
This generates the tbody part of the table. Generally, you don’t need to call this explicitly as it is handled in the display() method.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function display_rows_or_placeholder() {
if ( $this->has_items() ) {
$this->display_rows();
} else {
echo '<tr class="no-items"><td class="colspanchange" colspan="' . $this->get_column_count() . '">';
$this->no_items();
echo '</td></tr>';
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::display\_rows()](display_rows) wp-admin/includes/class-wp-list-table.php | Generates the table rows. |
| [WP\_List\_Table::get\_column\_count()](get_column_count) wp-admin/includes/class-wp-list-table.php | Returns the number of visible columns. |
| [WP\_List\_Table::has\_items()](has_items) wp-admin/includes/class-wp-list-table.php | Whether the table has items to display or not |
| [WP\_List\_Table::no\_items()](no_items) wp-admin/includes/class-wp-list-table.php | Message to be displayed when there are no items |
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::ajax\_response()](ajax_response) wp-admin/includes/class-wp-list-table.php | Handles an incoming ajax request (called from admin-ajax.php) |
| [WP\_List\_Table::display()](display) wp-admin/includes/class-wp-list-table.php | Displays the table. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::__call( string $name, array $arguments ): mixed|bool WP\_List\_Table::\_\_call( string $name, array $arguments ): mixed|bool
=======================================================================
Make private/protected methods readable for backward compatibility.
`$name` string Required Method to call. `$arguments` array Required Arguments to pass when calling. mixed|bool Return value of the callback, false otherwise.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function __call( $name, $arguments ) {
if ( in_array( $name, $this->compat_methods, true ) ) {
return $this->$name( ...$arguments );
}
return false;
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_List_Table::get_pagenum(): int WP\_List\_Table::get\_pagenum(): int
====================================
Gets the current page number.
int
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function get_pagenum() {
$pagenum = isset( $_REQUEST['paged'] ) ? absint( $_REQUEST['paged'] ) : 0;
if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] ) {
$pagenum = $this->_pagination_args['total_pages'];
}
return max( 1, $pagenum );
}
```
| Uses | Description |
| --- | --- |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::pagination()](pagination) wp-admin/includes/class-wp-list-table.php | Displays the pagination. |
| [WP\_List\_Table::set\_pagination\_args()](set_pagination_args) wp-admin/includes/class-wp-list-table.php | An internal method that sets all the necessary pagination arguments |
| [WP\_List\_Table::get\_pagination\_arg()](get_pagination_arg) wp-admin/includes/class-wp-list-table.php | Access the pagination args. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::has_items(): bool WP\_List\_Table::has\_items(): bool
===================================
Whether the table has items to display or not
bool
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function has_items() {
return ! empty( $this->items );
}
```
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::display\_rows\_or\_placeholder()](display_rows_or_placeholder) wp-admin/includes/class-wp-list-table.php | Generates the tbody element for the list table. |
| [WP\_List\_Table::display\_tablenav()](display_tablenav) wp-admin/includes/class-wp-list-table.php | Generates the table navigation above or below the table |
| [WP\_List\_Table::search\_box()](search_box) wp-admin/includes/class-wp-list-table.php | Displays the search box. |
| [wp\_ajax\_get\_comments()](../../functions/wp_ajax_get_comments) wp-admin/includes/ajax-actions.php | Ajax handler for getting comments. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::__set( string $name, mixed $value ): mixed WP\_List\_Table::\_\_set( string $name, mixed $value ): mixed
=============================================================
Make 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-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.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_List_Table::get_items_per_page( string $option, int $default_value = 20 ): int WP\_List\_Table::get\_items\_per\_page( string $option, int $default\_value = 20 ): int
=======================================================================================
Gets the number of items to display on a single page.
`$option` string Required User option name. `$default_value` int Optional The number of items to display. Default: `20`
int
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function get_items_per_page( $option, $default_value = 20 ) {
$per_page = (int) get_user_option( $option );
if ( empty( $per_page ) || $per_page < 1 ) {
$per_page = $default_value;
}
/**
* Filters the number of items to be displayed on each page of the list table.
*
* The dynamic hook name, `$option`, refers to the `per_page` option depending
* on the type of list table in use. Possible filter names include:
*
* - `edit_comments_per_page`
* - `sites_network_per_page`
* - `site_themes_network_per_page`
* - `themes_network_per_page'`
* - `users_network_per_page`
* - `edit_post_per_page`
* - `edit_page_per_page'`
* - `edit_{$post_type}_per_page`
* - `edit_post_tag_per_page`
* - `edit_category_per_page`
* - `edit_{$taxonomy}_per_page`
* - `site_users_network_per_page`
* - `users_per_page`
*
* @since 2.9.0
*
* @param int $per_page Number of items to be displayed. Default 20.
*/
return (int) apply_filters( "{$option}", $per_page );
}
```
[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. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::__get( string $name ): mixed WP\_List\_Table::\_\_get( string $name ): mixed
===============================================
Make private properties readable for backward compatibility.
`$name` string Required Property to get. mixed Property.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.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_List_Table::display() WP\_List\_Table::display()
==========================
Displays the table.
Call this method to render the completed list table to the page.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function display() {
$singular = $this->_args['singular'];
$this->display_tablenav( 'top' );
$this->screen->render_screen_reader_content( 'heading_list' );
?>
<table class="wp-list-table <?php echo implode( ' ', $this->get_table_classes() ); ?>">
<thead>
<tr>
<?php $this->print_column_headers(); ?>
</tr>
</thead>
<tbody id="the-list"
<?php
if ( $singular ) {
echo " data-wp-lists='list:$singular'";
}
?>
>
<?php $this->display_rows_or_placeholder(); ?>
</tbody>
<tfoot>
<tr>
<?php $this->print_column_headers( false ); ?>
</tr>
</tfoot>
</table>
<?php
$this->display_tablenav( 'bottom' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::display\_rows\_or\_placeholder()](display_rows_or_placeholder) wp-admin/includes/class-wp-list-table.php | Generates the tbody element for the list table. |
| [WP\_List\_Table::display\_tablenav()](display_tablenav) wp-admin/includes/class-wp-list-table.php | Generates the table navigation above or below the table |
| [WP\_List\_Table::get\_table\_classes()](get_table_classes) wp-admin/includes/class-wp-list-table.php | Gets a list of CSS classes for the [WP\_List\_Table](../wp_list_table) table tag. |
| [WP\_List\_Table::print\_column\_headers()](print_column_headers) wp-admin/includes/class-wp-list-table.php | Prints column headers, accounting for hidden and sortable columns. |
| Used By | Description |
| --- | --- |
| [wp\_ajax\_search\_install\_plugins()](../../functions/wp_ajax_search_install_plugins) wp-admin/includes/ajax-actions.php | Ajax handler for searching plugins to install. |
| [wp\_ajax\_search\_plugins()](../../functions/wp_ajax_search_plugins) wp-admin/includes/ajax-actions.php | Ajax handler for searching plugins. |
| [display\_themes()](../../functions/display_themes) wp-admin/includes/theme-install.php | Displays theme content based on theme list. |
| [display\_plugins\_table()](../../functions/display_plugins_table) wp-admin/includes/plugin-install.php | Displays plugin content based on plugin list. |
| [post\_comment\_meta\_box()](../../functions/post_comment_meta_box) wp-admin/includes/meta-boxes.php | Displays comments for post. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
| programming_docs |
wordpress WP_List_Table::row_actions( string[] $actions, bool $always_visible = false ): string WP\_List\_Table::row\_actions( string[] $actions, bool $always\_visible = false ): string
=========================================================================================
Generates the required HTML for a list of row action links.
`$actions` string[] Required An array of action links. `$always_visible` bool Optional Whether the actions should be always visible. Default: `false`
string The HTML for the row actions.
Call this method (usually from one of your column methods) to insert a row actions div. The $actions parameter should be an associative array, where the key is the name of the action and the value is a link.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function row_actions( $actions, $always_visible = false ) {
$action_count = count( $actions );
if ( ! $action_count ) {
return '';
}
$mode = get_user_setting( 'posts_list_mode', 'list' );
if ( 'excerpt' === $mode ) {
$always_visible = true;
}
$output = '<div class="' . ( $always_visible ? 'row-actions visible' : 'row-actions' ) . '">';
$i = 0;
foreach ( $actions as $action => $link ) {
++$i;
$separator = ( $i < $action_count ) ? ' | ' : '';
$output .= "<span class='$action'>{$link}{$separator}</span>";
}
$output .= '</div>';
$output .= '<button type="button" class="toggle-row"><span class="screen-reader-text">' . __( 'Show more details' ) . '</span></button>';
return $output;
}
```
| Uses | Description |
| --- | --- |
| [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. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::months_dropdown( string $post_type ) WP\_List\_Table::months\_dropdown( string $post\_type )
=======================================================
Displays a dropdown for filtering items in the list table by month.
`$post_type` string Required The post type. File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function months_dropdown( $post_type ) {
global $wpdb, $wp_locale;
/**
* Filters whether to remove the 'Months' drop-down from the post list table.
*
* @since 4.2.0
*
* @param bool $disable Whether to disable the drop-down. Default false.
* @param string $post_type The post type.
*/
if ( apply_filters( 'disable_months_dropdown', false, $post_type ) ) {
return;
}
/**
* Filters whether to short-circuit performing the months dropdown query.
*
* @since 5.7.0
*
* @param object[]|false $months 'Months' drop-down results. Default false.
* @param string $post_type The post type.
*/
$months = apply_filters( 'pre_months_dropdown_query', false, $post_type );
if ( ! is_array( $months ) ) {
$extra_checks = "AND post_status != 'auto-draft'";
if ( ! isset( $_GET['post_status'] ) || 'trash' !== $_GET['post_status'] ) {
$extra_checks .= " AND post_status != 'trash'";
} elseif ( isset( $_GET['post_status'] ) ) {
$extra_checks = $wpdb->prepare( ' AND post_status = %s', $_GET['post_status'] );
}
$months = $wpdb->get_results(
$wpdb->prepare(
"
SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
FROM $wpdb->posts
WHERE post_type = %s
$extra_checks
ORDER BY post_date DESC
",
$post_type
)
);
}
/**
* Filters the 'Months' drop-down results.
*
* @since 3.7.0
*
* @param object[] $months Array of the months drop-down query results.
* @param string $post_type The post type.
*/
$months = apply_filters( 'months_dropdown_results', $months, $post_type );
$month_count = count( $months );
if ( ! $month_count || ( 1 == $month_count && 0 == $months[0]->month ) ) {
return;
}
$m = isset( $_GET['m'] ) ? (int) $_GET['m'] : 0;
?>
<label for="filter-by-date" class="screen-reader-text"><?php echo get_post_type_object( $post_type )->labels->filter_by_date; ?></label>
<select name="m" id="filter-by-date">
<option<?php selected( $m, 0 ); ?> value="0"><?php _e( 'All dates' ); ?></option>
<?php
foreach ( $months as $arc_row ) {
if ( 0 == $arc_row->year ) {
continue;
}
$month = zeroise( $arc_row->month, 2 );
$year = $arc_row->year;
printf(
"<option %s value='%s'>%s</option>\n",
selected( $m, $year . $month, false ),
esc_attr( $arc_row->year . $month ),
/* translators: 1: Month name, 2: 4-digit year. */
sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month ), $year )
);
}
?>
</select>
<?php
}
```
[apply\_filters( 'disable\_months\_dropdown', bool $disable, string $post\_type )](../../hooks/disable_months_dropdown)
Filters whether to remove the ‘Months’ drop-down from the post list table.
[apply\_filters( 'months\_dropdown\_results', object[] $months, string $post\_type )](../../hooks/months_dropdown_results)
Filters the ‘Months’ drop-down results.
[apply\_filters( 'pre\_months\_dropdown\_query', object[]|false $months, string $post\_type )](../../hooks/pre_months_dropdown_query)
Filters whether to short-circuit performing the months dropdown query.
| Uses | Description |
| --- | --- |
| [zeroise()](../../functions/zeroise) wp-includes/formatting.php | Add leading zeros when necessary. |
| [selected()](../../functions/selected) wp-includes/general-template.php | Outputs the HTML selected attribute. |
| [WP\_Locale::get\_month()](../wp_locale/get_month) wp-includes/class-wp-locale.php | Retrieves the full translated month by month number. |
| [\_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. |
| [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. |
| [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 |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::display_tablenav( string $which ) WP\_List\_Table::display\_tablenav( string $which )
===================================================
Generates the table navigation above or below the table
`$which` string Required This generates the table navigation *above* or *below* the table. Generally, you don’t need to call this explicitly as it is handled in the display() method.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function display_tablenav( $which ) {
if ( 'top' === $which ) {
wp_nonce_field( 'bulk-' . $this->_args['plural'] );
}
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>">
<?php if ( $this->has_items() ) : ?>
<div class="alignleft actions bulkactions">
<?php $this->bulk_actions( $which ); ?>
</div>
<?php
endif;
$this->extra_tablenav( $which );
$this->pagination( $which );
?>
<br class="clear" />
</div>
<?php
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::extra\_tablenav()](extra_tablenav) wp-admin/includes/class-wp-list-table.php | Extra controls to be displayed between bulk actions and pagination. |
| [WP\_List\_Table::pagination()](pagination) wp-admin/includes/class-wp-list-table.php | Displays the pagination. |
| [WP\_List\_Table::has\_items()](has_items) wp-admin/includes/class-wp-list-table.php | Whether the table has items to display or not |
| [WP\_List\_Table::bulk\_actions()](bulk_actions) wp-admin/includes/class-wp-list-table.php | Displays the bulk actions dropdown. |
| [wp\_nonce\_field()](../../functions/wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::display()](display) wp-admin/includes/class-wp-list-table.php | Displays the table. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::get_table_classes(): string[] WP\_List\_Table::get\_table\_classes(): string[]
================================================
Gets a list of CSS classes for the [WP\_List\_Table](../wp_list_table) table tag.
string[] Array of CSS classes for the table tag.
Returns a list of css classes to be attached to the table element. Override to customize table classes.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function get_table_classes() {
$mode = get_user_setting( 'posts_list_mode', 'list' );
$mode_class = esc_attr( 'table-view-' . $mode );
return array( 'widefat', 'fixed', 'striped', $mode_class, $this->_args['plural'] );
}
```
| Uses | Description |
| --- | --- |
| [get\_user\_setting()](../../functions/get_user_setting) wp-includes/option.php | Retrieves user interface setting value based on setting name. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::display()](display) wp-admin/includes/class-wp-list-table.php | Displays the table. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::column_cb( object|array $item ) WP\_List\_Table::column\_cb( object|array $item )
=================================================
`$item` object|array Required File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function column_cb( $item ) {}
```
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::single\_row\_columns()](single_row_columns) wp-admin/includes/class-wp-list-table.php | Generates the columns for a single row of the table. |
wordpress WP_List_Table::set_pagination_args( array|string $args ) WP\_List\_Table::set\_pagination\_args( array|string $args )
============================================================
An internal method that sets all the necessary pagination arguments
`$args` array|string Required Array or string of arguments with information about the pagination. This method should be called internally (usually from prepare\_items()) to set basic pagination arguments. Available arguments include: * **total\_items** – the total number of items to be displayed. Usually as simple as count($data)
* **per\_page** – the number of items to show per page
* **total\_pages** – the total number of pages. Can be left blank or calculated manually, like so: ceil($total\_items/$per\_page)
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function set_pagination_args( $args ) {
$args = wp_parse_args(
$args,
array(
'total_items' => 0,
'total_pages' => 0,
'per_page' => 0,
)
);
if ( ! $args['total_pages'] && $args['per_page'] > 0 ) {
$args['total_pages'] = ceil( $args['total_items'] / $args['per_page'] );
}
// Redirect if page number is invalid and headers are not already sent.
if ( ! headers_sent() && ! wp_doing_ajax() && $args['total_pages'] > 0 && $this->get_pagenum() > $args['total_pages'] ) {
wp_redirect( add_query_arg( 'paged', $args['total_pages'] ) );
exit;
}
$this->_pagination_args = $args;
}
```
| Uses | Description |
| --- | --- |
| [wp\_doing\_ajax()](../../functions/wp_doing_ajax) wp-includes/load.php | Determines whether the current request is a WordPress Ajax request. |
| [WP\_List\_Table::get\_pagenum()](get_pagenum) wp-admin/includes/class-wp-list-table.php | Gets the current page number. |
| [wp\_redirect()](../../functions/wp_redirect) wp-includes/pluggable.php | Redirects to another page. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::__isset( string $name ): bool WP\_List\_Table::\_\_isset( string $name ): bool
================================================
Make private properties checkable for backward compatibility.
`$name` string Required Property to check if set. bool Whether the property is a back-compat property and it is set.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function __isset( $name ) {
if ( in_array( $name, $this->compat_fields, true ) ) {
return isset( $this->$name );
}
return false;
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_List_Table::get_columns(): array WP\_List\_Table::get\_columns(): array
======================================
Gets a list of columns.
The format is:
* `'internal-name' => 'Title'`
array
This method should be overridden to return an associative array of columns. The associative array should follow the format 'slug' => array( 'Title', true ). Typically, you will use this in the prepare\_items() method to build part of the \_column\_headers property.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function get_columns() {
die( 'function WP_List_Table::get_columns() must be overridden in a subclass.' );
}
```
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::get\_default\_primary\_column\_name()](get_default_primary_column_name) wp-admin/includes/class-wp-list-table.php | Gets the name of the default primary column. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::comments_bubble( int $post_id, int $pending_comments ) WP\_List\_Table::comments\_bubble( int $post\_id, int $pending\_comments )
==========================================================================
Displays a comment count bubble.
`$post_id` int Required The post ID. `$pending_comments` int Required Number of pending comments. File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function comments_bubble( $post_id, $pending_comments ) {
$approved_comments = get_comments_number();
$approved_comments_number = number_format_i18n( $approved_comments );
$pending_comments_number = number_format_i18n( $pending_comments );
$approved_only_phrase = sprintf(
/* translators: %s: Number of comments. */
_n( '%s comment', '%s comments', $approved_comments ),
$approved_comments_number
);
$approved_phrase = sprintf(
/* translators: %s: Number of comments. */
_n( '%s approved comment', '%s approved comments', $approved_comments ),
$approved_comments_number
);
$pending_phrase = sprintf(
/* translators: %s: Number of comments. */
_n( '%s pending comment', '%s pending comments', $pending_comments ),
$pending_comments_number
);
if ( ! $approved_comments && ! $pending_comments ) {
// No comments at all.
printf(
'<span aria-hidden="true">—</span><span class="screen-reader-text">%s</span>',
__( 'No comments' )
);
} elseif ( $approved_comments && 'trash' === get_post_status( $post_id ) ) {
// Don't link the comment bubble for a trashed post.
printf(
'<span class="post-com-count post-com-count-approved"><span class="comment-count-approved" aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></span>',
$approved_comments_number,
$pending_comments ? $approved_phrase : $approved_only_phrase
);
} elseif ( $approved_comments ) {
// Link the comment bubble to approved comments.
printf(
'<a href="%s" class="post-com-count post-com-count-approved"><span class="comment-count-approved" aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></a>',
esc_url(
add_query_arg(
array(
'p' => $post_id,
'comment_status' => 'approved',
),
admin_url( 'edit-comments.php' )
)
),
$approved_comments_number,
$pending_comments ? $approved_phrase : $approved_only_phrase
);
} else {
// Don't link the comment bubble when there are no approved comments.
printf(
'<span class="post-com-count post-com-count-no-comments"><span class="comment-count comment-count-no-comments" aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></span>',
$approved_comments_number,
$pending_comments ? __( 'No approved comments' ) : __( 'No comments' )
);
}
if ( $pending_comments ) {
printf(
'<a href="%s" class="post-com-count post-com-count-pending"><span class="comment-count-pending" aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></a>',
esc_url(
add_query_arg(
array(
'p' => $post_id,
'comment_status' => 'moderated',
),
admin_url( 'edit-comments.php' )
)
),
$pending_comments_number,
$pending_phrase
);
} else {
printf(
'<span class="post-com-count post-com-count-pending post-com-count-no-pending"><span class="comment-count comment-count-no-pending" aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></span>',
$pending_comments_number,
$approved_comments ? __( 'No pending comments' ) : __( 'No comments' )
);
}
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_status()](../../functions/get_post_status) wp-includes/post.php | Retrieves the post status based on the post ID. |
| [\_n()](../../functions/_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [get\_comments\_number()](../../functions/get_comments_number) wp-includes/comment-template.php | Retrieves the amount of comments a post has. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [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. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
| programming_docs |
wordpress WP_List_Table::search_box( string $text, string $input_id ) WP\_List\_Table::search\_box( string $text, string $input\_id )
===============================================================
Displays the search box.
`$text` string Required The `'submit'` button label. `$input_id` string Required ID attribute value for the search input field. This renders a search box. To use this, you will still need to manually wrap your list table (including search box) in a form.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function search_box( $text, $input_id ) {
if ( empty( $_REQUEST['s'] ) && ! $this->has_items() ) {
return;
}
$input_id = $input_id . '-search-input';
if ( ! empty( $_REQUEST['orderby'] ) ) {
echo '<input type="hidden" name="orderby" value="' . esc_attr( $_REQUEST['orderby'] ) . '" />';
}
if ( ! empty( $_REQUEST['order'] ) ) {
echo '<input type="hidden" name="order" value="' . esc_attr( $_REQUEST['order'] ) . '" />';
}
if ( ! empty( $_REQUEST['post_mime_type'] ) ) {
echo '<input type="hidden" name="post_mime_type" value="' . esc_attr( $_REQUEST['post_mime_type'] ) . '" />';
}
if ( ! empty( $_REQUEST['detached'] ) ) {
echo '<input type="hidden" name="detached" value="' . esc_attr( $_REQUEST['detached'] ) . '" />';
}
?>
<p class="search-box">
<label class="screen-reader-text" for="<?php echo esc_attr( $input_id ); ?>"><?php echo $text; ?>:</label>
<input type="search" id="<?php echo esc_attr( $input_id ); ?>" name="s" value="<?php _admin_search_query(); ?>" />
<?php submit_button( $text, '', '', false, array( 'id' => 'search-submit' ) ); ?>
</p>
<?php
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::has\_items()](has_items) wp-admin/includes/class-wp-list-table.php | Whether the table has items to display or not |
| [\_admin\_search\_query()](../../functions/_admin_search_query) wp-admin/includes/template.php | Displays the search query. |
| [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/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::get_bulk_actions(): array WP\_List\_Table::get\_bulk\_actions(): array
============================================
Retrieves the list of bulk actions available for this table.
The format is an associative array where each element represents either a top level option value and label, or an array representing an optgroup and its options.
For a standard option, the array element key is the field value and the array element value is the field label.
For an optgroup, the array element key is the label and the array element value is an associative array of options as above.
Example:
```
[
'edit' => 'Edit',
'delete' => 'Delete',
'Change State' => [
'feature' => 'Featured',
'sale' => 'On Sale',
]
]
```
array
Override this method to return an associative array ( action\_slug => action\_title ) containing all the bulk actions available for the table. File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function get_bulk_actions() {
return array();
}
```
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::bulk\_actions()](bulk_actions) wp-admin/includes/class-wp-list-table.php | Displays the bulk actions dropdown. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | A bulk action can now contain an array of options in order to create an optgroup. |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::get_primary_column(): string WP\_List\_Table::get\_primary\_column(): string
===============================================
Public wrapper for [WP\_List\_Table::get\_default\_primary\_column\_name()](get_default_primary_column_name).
string Name of the default primary column.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function get_primary_column() {
return $this->get_primary_column_name();
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::get\_primary\_column\_name()](get_primary_column_name) wp-admin/includes/class-wp-list-table.php | Gets the name of the primary column. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_List_Table::__construct( array|string $args = array() ) WP\_List\_Table::\_\_construct( array|string $args = array() )
==============================================================
Constructor.
The child class should call this constructor from its own constructor to override the default $args.
`$args` array|string Optional Array or string of arguments.
* `plural`stringPlural value used for labels and the objects being listed.
This affects things such as CSS class-names and nonces used in the list table, e.g. `'posts'`.
* `singular`stringSingular label for an object being listed, e.g. `'post'`.
Default empty
* `ajax`boolWhether the list table supports Ajax. This includes loading and sorting data, for example. If true, the class will call the \_js\_vars() method in the footer to provide variables to any scripts handling Ajax events. Default false.
* `screen`stringString containing the hook name used to determine the current screen. If left null, the current screen will be automatically set.
Default null.
Default: `array()`
This sets default arguments and filters. Developers should override this, calling the parent constructor to provide values for singular and plural labels, as well as whether the class supports AJAX.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function __construct( $args = array() ) {
$args = wp_parse_args(
$args,
array(
'plural' => '',
'singular' => '',
'ajax' => false,
'screen' => null,
)
);
$this->screen = convert_to_screen( $args['screen'] );
add_filter( "manage_{$this->screen->id}_columns", array( $this, 'get_columns' ), 0 );
if ( ! $args['plural'] ) {
$args['plural'] = $this->screen->base;
}
$args['plural'] = sanitize_key( $args['plural'] );
$args['singular'] = sanitize_key( $args['singular'] );
$this->_args = $args;
if ( $args['ajax'] ) {
// wp_enqueue_script( 'list-table' );
add_action( 'admin_footer', array( $this, '_js_vars' ) );
}
if ( empty( $this->modes ) ) {
$this->modes = array(
'list' => __( 'Compact view' ),
'excerpt' => __( 'Extended view' ),
);
}
}
```
| Uses | Description |
| --- | --- |
| [convert\_to\_screen()](../../functions/convert_to_screen) wp-admin/includes/template.php | Converts a screen string to a screen object. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [sanitize\_key()](../../functions/sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [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\_Plugins\_List\_Table::\_\_construct()](../wp_plugins_list_table/__construct) wp-admin/includes/class-wp-plugins-list-table.php | Constructor. |
| [WP\_Links\_List\_Table::\_\_construct()](../wp_links_list_table/__construct) wp-admin/includes/class-wp-links-list-table.php | Constructor. |
| [WP\_MS\_Themes\_List\_Table::\_\_construct()](../wp_ms_themes_list_table/__construct) wp-admin/includes/class-wp-ms-themes-list-table.php | Constructor. |
| [WP\_Themes\_List\_Table::\_\_construct()](../wp_themes_list_table/__construct) wp-admin/includes/class-wp-themes-list-table.php | Constructor. |
| [WP\_MS\_Sites\_List\_Table::\_\_construct()](../wp_ms_sites_list_table/__construct) wp-admin/includes/class-wp-ms-sites-list-table.php | Constructor. |
| [WP\_Users\_List\_Table::\_\_construct()](../wp_users_list_table/__construct) wp-admin/includes/class-wp-users-list-table.php | Constructor. |
| [WP\_Media\_List\_Table::\_\_construct()](../wp_media_list_table/__construct) wp-admin/includes/class-wp-media-list-table.php | Constructor. |
| [WP\_Comments\_List\_Table::\_\_construct()](../wp_comments_list_table/__construct) wp-admin/includes/class-wp-comments-list-table.php | Constructor. |
| [WP\_Terms\_List\_Table::\_\_construct()](../wp_terms_list_table/__construct) wp-admin/includes/class-wp-terms-list-table.php | Constructor. |
| [WP\_Posts\_List\_Table::\_\_construct()](../wp_posts_list_table/__construct) wp-admin/includes/class-wp-posts-list-table.php | Constructor. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::get_pagination_arg( string $key ): int WP\_List\_Table::get\_pagination\_arg( string $key ): int
=========================================================
Access the pagination args.
`$key` string Required Pagination argument to retrieve. Common values include `'total_items'`, `'total_pages'`, `'per_page'`, or `'infinite_scroll'`. int Number of items that correspond to the given pagination argument.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function get_pagination_arg( $key ) {
if ( 'page' === $key ) {
return $this->get_pagenum();
}
if ( isset( $this->_pagination_args[ $key ] ) ) {
return $this->_pagination_args[ $key ];
}
return 0;
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::get\_pagenum()](get_pagenum) wp-admin/includes/class-wp-list-table.php | Gets the current page number. |
| Used By | Description |
| --- | --- |
| [wp\_ajax\_search\_install\_plugins()](../../functions/wp_ajax_search_install_plugins) wp-admin/includes/ajax-actions.php | Ajax handler for searching plugins to install. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::ajax_response() WP\_List\_Table::ajax\_response()
=================================
Handles an incoming ajax request (called from admin-ajax.php)
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function ajax_response() {
$this->prepare_items();
ob_start();
if ( ! empty( $_REQUEST['no_placeholder'] ) ) {
$this->display_rows();
} else {
$this->display_rows_or_placeholder();
}
$rows = ob_get_clean();
$response = array( 'rows' => $rows );
if ( isset( $this->_pagination_args['total_items'] ) ) {
$response['total_items_i18n'] = sprintf(
/* translators: Number of items. */
_n( '%s item', '%s items', $this->_pagination_args['total_items'] ),
number_format_i18n( $this->_pagination_args['total_items'] )
);
}
if ( isset( $this->_pagination_args['total_pages'] ) ) {
$response['total_pages'] = $this->_pagination_args['total_pages'];
$response['total_pages_i18n'] = number_format_i18n( $this->_pagination_args['total_pages'] );
}
die( wp_json_encode( $response ) );
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::display\_rows()](display_rows) wp-admin/includes/class-wp-list-table.php | Generates the table rows. |
| [WP\_List\_Table::display\_rows\_or\_placeholder()](display_rows_or_placeholder) wp-admin/includes/class-wp-list-table.php | Generates the tbody element for the list table. |
| [WP\_List\_Table::prepare\_items()](prepare_items) wp-admin/includes/class-wp-list-table.php | Prepares the list of items for displaying. |
| [\_n()](../../functions/_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| Used By | Description |
| --- | --- |
| [wp\_ajax\_fetch\_list()](../../functions/wp_ajax_fetch_list) wp-admin/includes/ajax-actions.php | Ajax handler for fetching a list table. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::bulk_actions( string $which = '' ) WP\_List\_Table::bulk\_actions( string $which = '' )
====================================================
Displays the bulk actions dropdown.
`$which` string Optional The location of the bulk actions: `'top'` or `'bottom'`.
This is designated as optional for backward compatibility. Default: `''`
When called, this renders out the bulk-actions drop-down. To use this, you will still need to manually wrap your list table (including search box) in a form.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function bulk_actions( $which = '' ) {
if ( is_null( $this->_actions ) ) {
$this->_actions = $this->get_bulk_actions();
/**
* Filters the items in the bulk actions menu of the list table.
*
* The dynamic portion of the hook name, `$this->screen->id`, refers
* to the ID of the current screen.
*
* @since 3.1.0
* @since 5.6.0 A bulk action can now contain an array of options in order to create an optgroup.
*
* @param array $actions An array of the available bulk actions.
*/
$this->_actions = apply_filters( "bulk_actions-{$this->screen->id}", $this->_actions ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
$two = '';
} else {
$two = '2';
}
if ( empty( $this->_actions ) ) {
return;
}
echo '<label for="bulk-action-selector-' . esc_attr( $which ) . '" class="screen-reader-text">' . __( 'Select bulk action' ) . '</label>';
echo '<select name="action' . $two . '" id="bulk-action-selector-' . esc_attr( $which ) . "\">\n";
echo '<option value="-1">' . __( 'Bulk actions' ) . "</option>\n";
foreach ( $this->_actions as $key => $value ) {
if ( is_array( $value ) ) {
echo "\t" . '<optgroup label="' . esc_attr( $key ) . '">' . "\n";
foreach ( $value as $name => $title ) {
$class = ( 'edit' === $name ) ? ' class="hide-if-no-js"' : '';
echo "\t\t" . '<option value="' . esc_attr( $name ) . '"' . $class . '>' . $title . "</option>\n";
}
echo "\t" . "</optgroup>\n";
} else {
$class = ( 'edit' === $key ) ? ' class="hide-if-no-js"' : '';
echo "\t" . '<option value="' . esc_attr( $key ) . '"' . $class . '>' . $value . "</option>\n";
}
}
echo "</select>\n";
submit_button( __( 'Apply' ), 'action', '', false, array( 'id' => "doaction$two" ) );
echo "\n";
}
```
[apply\_filters( "bulk\_actions-{$this->screen->id}", array $actions )](../../hooks/bulk_actions-this-screen-id)
Filters the items in the bulk actions menu of the list table.
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::get\_bulk\_actions()](get_bulk_actions) wp-admin/includes/class-wp-list-table.php | Retrieves the list of bulk actions available for this table. |
| [submit\_button()](../../functions/submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $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. |
| Used By | Description |
| --- | --- |
| [WP\_Plugins\_List\_Table::bulk\_actions()](../wp_plugins_list_table/bulk_actions) wp-admin/includes/class-wp-plugins-list-table.php | |
| [WP\_List\_Table::display\_tablenav()](display_tablenav) wp-admin/includes/class-wp-list-table.php | Generates the table navigation above or below the table |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::get_primary_column_name(): string WP\_List\_Table::get\_primary\_column\_name(): string
=====================================================
Gets the name of the primary column.
string The name of the primary column.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function get_primary_column_name() {
$columns = get_column_headers( $this->screen );
$default = $this->get_default_primary_column_name();
// If the primary column doesn't exist,
// fall back to the first non-checkbox column.
if ( ! isset( $columns[ $default ] ) ) {
$default = self::get_default_primary_column_name();
}
/**
* Filters the name of the primary column for the current list table.
*
* @since 4.3.0
*
* @param string $default Column name default for the specific list table, e.g. 'name'.
* @param string $context Screen ID for specific list table, e.g. 'plugins'.
*/
$column = apply_filters( 'list_table_primary_column', $default, $this->screen->id );
if ( empty( $column ) || ! isset( $columns[ $column ] ) ) {
$column = $default;
}
return $column;
}
```
[apply\_filters( 'list\_table\_primary\_column', string $default, string $context )](../../hooks/list_table_primary_column)
Filters the name of the primary column for the current list table.
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::get\_default\_primary\_column\_name()](get_default_primary_column_name) wp-admin/includes/class-wp-list-table.php | Gets the name of the default primary column. |
| [get\_column\_headers()](../../functions/get_column_headers) wp-admin/includes/screen.php | Get the column headers for a screen |
| [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\_List\_Table::get\_primary\_column()](get_primary_column) wp-admin/includes/class-wp-list-table.php | Public wrapper for [WP\_List\_Table::get\_default\_primary\_column\_name()](get_default_primary_column_name). |
| [WP\_List\_Table::get\_column\_info()](get_column_info) wp-admin/includes/class-wp-list-table.php | Gets a list of all, hidden, and sortable columns, with filter applied. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_List_Table::single_row_columns( object|array $item ) WP\_List\_Table::single\_row\_columns( object|array $item )
===========================================================
Generates the columns for a single row of the table.
`$item` object|array Required The current item. This renders out all the columns for a single item row. It is important to understand that this method assumes the existence of some custom column methods (eg column\_mycolumn()) and/or a **column\_default()** method. Neither of these are provided by the base class and should be defined in your extended class. Generally, you don’t need to call this explicitly as it is handled automatically on display().
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function single_row_columns( $item ) {
list( $columns, $hidden, $sortable, $primary ) = $this->get_column_info();
foreach ( $columns as $column_name => $column_display_name ) {
$classes = "$column_name column-$column_name";
if ( $primary === $column_name ) {
$classes .= ' has-row-actions column-primary';
}
if ( in_array( $column_name, $hidden, true ) ) {
$classes .= ' hidden';
}
// Comments column uses HTML in the display name with screen reader text.
// Strip tags to get closer to a user-friendly string.
$data = 'data-colname="' . esc_attr( wp_strip_all_tags( $column_display_name ) ) . '"';
$attributes = "class='$classes' $data";
if ( 'cb' === $column_name ) {
echo '<th scope="row" class="check-column">';
echo $this->column_cb( $item );
echo '</th>';
} elseif ( method_exists( $this, '_column_' . $column_name ) ) {
echo call_user_func(
array( $this, '_column_' . $column_name ),
$item,
$classes,
$data,
$primary
);
} elseif ( method_exists( $this, 'column_' . $column_name ) ) {
echo "<td $attributes>";
echo call_user_func( array( $this, 'column_' . $column_name ), $item );
echo $this->handle_row_actions( $item, $column_name, $primary );
echo '</td>';
} else {
echo "<td $attributes>";
echo $this->column_default( $item, $column_name );
echo $this->handle_row_actions( $item, $column_name, $primary );
echo '</td>';
}
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::handle\_row\_actions()](handle_row_actions) wp-admin/includes/class-wp-list-table.php | Generates and display row actions links for the list table. |
| [WP\_List\_Table::column\_cb()](column_cb) wp-admin/includes/class-wp-list-table.php | |
| [WP\_List\_Table::column\_default()](column_default) wp-admin/includes/class-wp-list-table.php | |
| [WP\_List\_Table::get\_column\_info()](get_column_info) wp-admin/includes/class-wp-list-table.php | Gets a list of all, hidden, and sortable columns, with filter applied. |
| [wp\_strip\_all\_tags()](../../functions/wp_strip_all_tags) wp-includes/formatting.php | Properly strips all HTML tags including script and style |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::single\_row()](single_row) wp-admin/includes/class-wp-list-table.php | Generates content for a single row of the table. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
| programming_docs |
wordpress WP_List_Table::print_column_headers( bool $with_id = true ) WP\_List\_Table::print\_column\_headers( bool $with\_id = true )
================================================================
Prints column headers, accounting for hidden and sortable columns.
`$with_id` bool Optional Whether to set the ID attribute or not Default: `true`
This method renders out the column headers. Generally, you don’t need to call this directly as it’s handled for you in the display() method.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function print_column_headers( $with_id = true ) {
list( $columns, $hidden, $sortable, $primary ) = $this->get_column_info();
$current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
$current_url = remove_query_arg( 'paged', $current_url );
if ( isset( $_GET['orderby'] ) ) {
$current_orderby = $_GET['orderby'];
} else {
$current_orderby = '';
}
if ( isset( $_GET['order'] ) && 'desc' === $_GET['order'] ) {
$current_order = 'desc';
} else {
$current_order = 'asc';
}
if ( ! empty( $columns['cb'] ) ) {
static $cb_counter = 1;
$columns['cb'] = '<label class="screen-reader-text" for="cb-select-all-' . $cb_counter . '">' . __( 'Select All' ) . '</label>'
. '<input id="cb-select-all-' . $cb_counter . '" type="checkbox" />';
$cb_counter++;
}
foreach ( $columns as $column_key => $column_display_name ) {
$class = array( 'manage-column', "column-$column_key" );
if ( in_array( $column_key, $hidden, true ) ) {
$class[] = 'hidden';
}
if ( 'cb' === $column_key ) {
$class[] = 'check-column';
} elseif ( in_array( $column_key, array( 'posts', 'comments', 'links' ), true ) ) {
$class[] = 'num';
}
if ( $column_key === $primary ) {
$class[] = 'column-primary';
}
if ( isset( $sortable[ $column_key ] ) ) {
list( $orderby, $desc_first ) = $sortable[ $column_key ];
if ( $current_orderby === $orderby ) {
$order = 'asc' === $current_order ? 'desc' : 'asc';
$class[] = 'sorted';
$class[] = $current_order;
} else {
$order = strtolower( $desc_first );
if ( ! in_array( $order, array( 'desc', 'asc' ), true ) ) {
$order = $desc_first ? 'desc' : 'asc';
}
$class[] = 'sortable';
$class[] = 'desc' === $order ? 'asc' : 'desc';
}
$column_display_name = sprintf(
'<a href="%s"><span>%s</span><span class="sorting-indicator"></span></a>',
esc_url( add_query_arg( compact( 'orderby', 'order' ), $current_url ) ),
$column_display_name
);
}
$tag = ( 'cb' === $column_key ) ? 'td' : 'th';
$scope = ( 'th' === $tag ) ? 'scope="col"' : '';
$id = $with_id ? "id='$column_key'" : '';
if ( ! empty( $class ) ) {
$class = "class='" . implode( ' ', $class ) . "'";
}
echo "<$tag $scope $id $class>$column_display_name</$tag>";
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::get\_column\_info()](get_column_info) wp-admin/includes/class-wp-list-table.php | Gets a list of all, hidden, and sortable columns, with filter applied. |
| [remove\_query\_arg()](../../functions/remove_query_arg) wp-includes/functions.php | Removes an item or items from a query string. |
| [set\_url\_scheme()](../../functions/set_url_scheme) wp-includes/link-template.php | Sets the scheme for a URL. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [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\_List\_Table::display()](display) wp-admin/includes/class-wp-list-table.php | Displays the table. |
| [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::view_switcher( string $current_mode ) WP\_List\_Table::view\_switcher( string $current\_mode )
========================================================
Displays a view switcher.
`$current_mode` string Required Call this to render post-type view switcher buttons (List View and Excerpt View)
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function view_switcher( $current_mode ) {
?>
<input type="hidden" name="mode" value="<?php echo esc_attr( $current_mode ); ?>" />
<div class="view-switch">
<?php
foreach ( $this->modes as $mode => $title ) {
$classes = array( 'view-' . $mode );
$aria_current = '';
if ( $current_mode === $mode ) {
$classes[] = 'current';
$aria_current = ' aria-current="page"';
}
printf(
"<a href='%s' class='%s' id='view-switch-$mode'$aria_current><span class='screen-reader-text'>%s</span></a>\n",
esc_url( remove_query_arg( 'attachment-filter', add_query_arg( 'mode', $mode ) ) ),
implode( ' ', $classes ),
$title
);
}
?>
</div>
<?php
}
```
| Uses | Description |
| --- | --- |
| [remove\_query\_arg()](../../functions/remove_query_arg) wp-includes/functions.php | Removes an item or items from a query string. |
| [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. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::column_default( object|array $item, string $column_name ) WP\_List\_Table::column\_default( object|array $item, string $column\_name )
============================================================================
`$item` object|array Required `$column_name` string Required This is method that is used to render a column when no other specific method exists for that column. When WP\_List\_Tables attempts to render your columns (within single\_row\_columns()), it first checks for a column-specific method. If none exists, it defaults to *this* method instead. This method accepts two arguments, a single **$item** array and the **$column\_name** (as a slug).
**NOTICE**: As of [WordPress 3.5.1](https://wordpress.org/support/wordpress-version/version-3-5-1/ "Version 3.5.1"), in core $item is passed an Object, not an array. File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function column_default( $item, $column_name ) {}
```
| Used By | Description |
| --- | --- |
| [WP\_List\_Table::single\_row\_columns()](single_row_columns) wp-admin/includes/class-wp-list-table.php | Generates the columns for a single row of the table. |
wordpress WP_List_Table::get_views_links( array $link_data = array() ): array WP\_List\_Table::get\_views\_links( array $link\_data = array() ): array
========================================================================
Generates views links.
`$link_data` array Optional An array of link data.
* `url`stringThe link URL.
* `label`stringThe link label.
* `current`boolOptional. Whether this is the currently selected view.
Default: `array()`
array An array of link markup. Keys match the `$link_data` input array.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function get_views_links( $link_data = array() ) {
if ( ! is_array( $link_data ) ) {
_doing_it_wrong(
__METHOD__,
sprintf(
/* translators: %s: The $link_data argument. */
__( 'The %s argument must be an array.' ),
'<code>$link_data</code>'
),
'6.1.0'
);
return array( '' );
}
$views_links = array();
foreach ( $link_data as $view => $link ) {
if ( empty( $link['url'] ) || ! is_string( $link['url'] ) || '' === trim( $link['url'] ) ) {
_doing_it_wrong(
__METHOD__,
sprintf(
/* translators: %1$s: The argument name. %2$s: The view name. */
__( 'The %1$s argument must be a non-empty string for %2$s.' ),
'<code>url</code>',
'<code>' . esc_html( $view ) . '</code>'
),
'6.1.0'
);
continue;
}
if ( empty( $link['label'] ) || ! is_string( $link['label'] ) || '' === trim( $link['label'] ) ) {
_doing_it_wrong(
__METHOD__,
sprintf(
/* translators: %1$s: The argument name. %2$s: The view name. */
__( 'The %1$s argument must be a non-empty string for %2$s.' ),
'<code>label</code>',
'<code>' . esc_html( $view ) . '</code>'
),
'6.1.0'
);
continue;
}
$views_links[ $view ] = sprintf(
'<a href="%s"%s>%s</a>',
esc_url( $link['url'] ),
isset( $link['current'] ) && true === $link['current'] ? ' class="current" aria-current="page"' : '',
$link['label']
);
}
return $views_links;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [\_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_List_Table::get_column_info(): array WP\_List\_Table::get\_column\_info(): array
===========================================
Gets a list of all, hidden, and sortable columns, with filter applied.
array
This is used by WordPress to build and fetch the \_column\_headers property. Generally, this should not be used by developers. Instead, assign the \_column\_headers property directly from your prepare\_items() method.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
protected function get_column_info() {
// $_column_headers is already set / cached.
if (
isset( $this->_column_headers ) &&
is_array( $this->_column_headers )
) {
/*
* Backward compatibility for `$_column_headers` format prior to WordPress 4.3.
*
* In WordPress 4.3 the primary column name was added as a fourth item in the
* column headers property. This ensures the primary column name is included
* in plugins setting the property directly in the three item format.
*/
if ( 4 === count( $this->_column_headers ) ) {
return $this->_column_headers;
}
$column_headers = array( array(), array(), array(), $this->get_primary_column_name() );
foreach ( $this->_column_headers as $key => $value ) {
$column_headers[ $key ] = $value;
}
$this->_column_headers = $column_headers;
return $this->_column_headers;
}
$columns = get_column_headers( $this->screen );
$hidden = get_hidden_columns( $this->screen );
$sortable_columns = $this->get_sortable_columns();
/**
* Filters the list table sortable columns for a specific screen.
*
* The dynamic portion of the hook name, `$this->screen->id`, refers
* to the ID of the current screen.
*
* @since 3.1.0
*
* @param array $sortable_columns An array of sortable columns.
*/
$_sortable = apply_filters( "manage_{$this->screen->id}_sortable_columns", $sortable_columns );
$sortable = array();
foreach ( $_sortable as $id => $data ) {
if ( empty( $data ) ) {
continue;
}
$data = (array) $data;
if ( ! isset( $data[1] ) ) {
$data[1] = false;
}
$sortable[ $id ] = $data;
}
$primary = $this->get_primary_column_name();
$this->_column_headers = array( $columns, $hidden, $sortable, $primary );
return $this->_column_headers;
}
```
[apply\_filters( "manage\_{$this->screen->id}\_sortable\_columns", array $sortable\_columns )](../../hooks/manage_this-screen-id_sortable_columns)
Filters the list table sortable columns for a specific screen.
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::get\_primary\_column\_name()](get_primary_column_name) wp-admin/includes/class-wp-list-table.php | Gets the name of the primary column. |
| [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\_List\_Table::get\_sortable\_columns()](get_sortable_columns) wp-admin/includes/class-wp-list-table.php | Gets a list of sortable columns. |
| [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\_List\_Table::single\_row\_columns()](single_row_columns) wp-admin/includes/class-wp-list-table.php | Generates the columns for a single row of the table. |
| [WP\_List\_Table::get\_column\_count()](get_column_count) wp-admin/includes/class-wp-list-table.php | Returns the number of visible columns. |
| [WP\_List\_Table::print\_column\_headers()](print_column_headers) wp-admin/includes/class-wp-list-table.php | Prints column headers, accounting for hidden and sortable columns. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_List_Table::views() WP\_List\_Table::views()
========================
Displays the list of views available on this table.
It renders out the <ul> element that contains the view names.
File: `wp-admin/includes/class-wp-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table.php/)
```
public function views() {
$views = $this->get_views();
/**
* Filters the list of available list table views.
*
* The dynamic portion of the hook name, `$this->screen->id`, refers
* to the ID of the current screen.
*
* @since 3.1.0
*
* @param string[] $views An array of available list table views.
*/
$views = apply_filters( "views_{$this->screen->id}", $views );
if ( empty( $views ) ) {
return;
}
$this->screen->render_screen_reader_content( 'heading_views' );
echo "<ul class='subsubsub'>\n";
foreach ( $views as $class => $view ) {
$views[ $class ] = "\t<li class='$class'>$view";
}
echo implode( " |</li>\n", $views ) . "</li>\n";
echo '</ul>';
}
```
[apply\_filters( "views\_{$this->screen->id}", string[] $views )](../../hooks/views_this-screen-id)
Filters the list of available list table views.
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::get\_views()](get_views) wp-admin/includes/class-wp-list-table.php | Gets the list of views available on this table. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Customize_Widgets::count_captured_options(): int WP\_Customize\_Widgets::count\_captured\_options(): int
=======================================================
Retrieves the number of captured widget option updates.
int Number of updated options.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
protected function count_captured_options() {
return count( $this->_captured_options );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::call\_widget\_update()](call_widget_update) wp-includes/class-wp-customize-widgets.php | Finds and invokes the widget update and control callbacks. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::filter_option_sidebars_widgets_for_theme_switch( array $sidebars_widgets ): array WP\_Customize\_Widgets::filter\_option\_sidebars\_widgets\_for\_theme\_switch( array $sidebars\_widgets ): array
================================================================================================================
Filters sidebars\_widgets option for theme switch.
When switching themes, the [retrieve\_widgets()](../../functions/retrieve_widgets) function is run when the Customizer initializes, and then the new sidebars\_widgets here get supplied as the default value for the sidebars\_widgets option.
* [WP\_Customize\_Widgets::handle\_theme\_switch()](../wp_customize_widgets/handle_theme_switch)
`$sidebars_widgets` array Required array
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function filter_option_sidebars_widgets_for_theme_switch( $sidebars_widgets ) {
$sidebars_widgets = $GLOBALS['sidebars_widgets'];
$sidebars_widgets['array_version'] = 3;
return $sidebars_widgets;
}
```
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::stop_capturing_option_updates() WP\_Customize\_Widgets::stop\_capturing\_option\_updates()
==========================================================
Undoes any changes to the options since options capture began.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
protected function stop_capturing_option_updates() {
if ( ! $this->_is_capturing_option_updates ) {
return;
}
remove_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10 );
foreach ( array_keys( $this->_captured_options ) as $option_name ) {
remove_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
}
$this->_captured_options = array();
$this->_is_capturing_option_updates = false;
}
```
| Uses | Description |
| --- | --- |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::call\_widget\_update()](call_widget_update) wp-includes/class-wp-customize-widgets.php | Finds and invokes the widget update and control callbacks. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::tally_sidebars_via_dynamic_sidebar_calls( bool $has_widgets, string $sidebar_id ): bool WP\_Customize\_Widgets::tally\_sidebars\_via\_dynamic\_sidebar\_calls( bool $has\_widgets, string $sidebar\_id ): bool
======================================================================================================================
Tallies the sidebars rendered via [dynamic\_sidebar()](../../functions/dynamic_sidebar) .
Keep track of the times that [dynamic\_sidebar()](../../functions/dynamic_sidebar) is called in the template, and assume this means the sidebar would be rendered on the template if there were widgets populating it.
`$has_widgets` bool Required Whether the current sidebar has widgets. `$sidebar_id` string Required Sidebar ID. bool Whether the current sidebar has widgets.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function tally_sidebars_via_dynamic_sidebar_calls( $has_widgets, $sidebar_id ) {
if ( is_registered_sidebar( $sidebar_id ) ) {
$this->rendered_sidebars[ $sidebar_id ] = true;
}
/*
* We may need to force this to true, and also force-true the value
* for 'is_active_sidebar' if we want to ensure there is an area to
* drop widgets into, if the sidebar is empty.
*/
return $has_widgets;
}
```
| Uses | Description |
| --- | --- |
| [is\_registered\_sidebar()](../../functions/is_registered_sidebar) wp-includes/widgets.php | Checks if a sidebar is registered. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Widgets::refresh_nonces( array $nonces ): array WP\_Customize\_Widgets::refresh\_nonces( array $nonces ): array
===============================================================
Refreshes the nonce for widget updates.
`$nonces` array Required Array of nonces. array Array of nonces.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function refresh_nonces( $nonces ) {
$nonces['update-widget'] = wp_create_nonce( 'update-widget' );
return $nonces;
}
```
| 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. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Customize_Widgets::start_dynamic_sidebar( int|string $index ) WP\_Customize\_Widgets::start\_dynamic\_sidebar( int|string $index )
====================================================================
Begins keeping track of the current sidebar being rendered.
Insert marker before widgets are rendered in a dynamic sidebar.
`$index` int|string Required Index, name, or ID of the dynamic sidebar. File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function start_dynamic_sidebar( $index ) {
array_unshift( $this->current_dynamic_sidebar_id_stack, $index );
if ( ! isset( $this->sidebar_instance_count[ $index ] ) ) {
$this->sidebar_instance_count[ $index ] = 0;
}
$this->sidebar_instance_count[ $index ] += 1;
if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
printf( "\n<!--dynamic_sidebar_before:%s:%d-->\n", esc_html( $index ), (int) $this->sidebar_instance_count[ $index ] );
}
}
```
| Uses | Description |
| --- | --- |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Widgets::tally_rendered_widgets( array $widget ) WP\_Customize\_Widgets::tally\_rendered\_widgets( array $widget )
=================================================================
Tracks the widgets that were rendered.
`$widget` array Required Rendered widget to tally. File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function tally_rendered_widgets( $widget ) {
$this->rendered_widgets[ $widget['id'] ] = true;
}
```
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::is_widget_selective_refreshable( string $id_base ): bool WP\_Customize\_Widgets::is\_widget\_selective\_refreshable( string $id\_base ): bool
====================================================================================
Determines if a widget supports selective refresh.
`$id_base` string Required Widget ID Base. bool Whether the widget can be selective refreshed.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function is_widget_selective_refreshable( $id_base ) {
$selective_refreshable_widgets = $this->get_selective_refreshable_widgets();
return ! empty( $selective_refreshable_widgets[ $id_base ] );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Widgets::get\_selective\_refreshable\_widgets()](get_selective_refreshable_widgets) wp-includes/class-wp-customize-widgets.php | List whether each registered widget can be use selective refresh. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::get\_setting\_args()](get_setting_args) wp-includes/class-wp-customize-widgets.php | Retrieves common arguments to supply when constructing a Customizer setting. |
| [WP\_Customize\_Widgets::get\_available\_widgets()](get_available_widgets) wp-includes/class-wp-customize-widgets.php | Builds up an index of all available widgets for use in Backbone models. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Widgets::setup_widget_addition_previews() WP\_Customize\_Widgets::setup\_widget\_addition\_previews()
===========================================================
This method has been deprecated. Deprecated in favor of the [‘customize\_dynamic\_setting\_args’](../../hooks/customize_dynamic_setting_args) filter instead.
{@internal Missing Summary}
See the [‘customize\_dynamic\_setting\_args’](../../hooks/customize_dynamic_setting_args) filter.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function setup_widget_addition_previews() {
_deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
}
```
| 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.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Deprecated in favor of the ['customize\_dynamic\_setting\_args'](../../hooks/customize_dynamic_setting_args) filter. |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::sanitize_widget_instance( array $value, string $id_base = null ): array|void WP\_Customize\_Widgets::sanitize\_widget\_instance( array $value, string $id\_base = null ): array|void
=======================================================================================================
Sanitizes a widget instance.
Unserialize the JS-instance for storing in the options. It’s important that this filter only get applied to an instance *once*.
`$value` array Required Widget instance to sanitize. `$id_base` string Optional Base of the ID of the widget being sanitized. Default: `null`
array|void Sanitized widget instance.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function sanitize_widget_instance( $value, $id_base = null ) {
global $wp_widget_factory;
if ( array() === $value ) {
return $value;
}
if ( isset( $value['raw_instance'] ) && $id_base && wp_use_widgets_block_editor() ) {
$widget_object = $wp_widget_factory->get_widget_object( $id_base );
if ( ! empty( $widget_object->widget_options['show_instance_in_rest'] ) ) {
if ( 'block' === $id_base && ! current_user_can( 'unfiltered_html' ) ) {
/*
* The content of the 'block' widget is not filtered on the fly while editing.
* Filter the content here to prevent vulnerabilities.
*/
$value['raw_instance']['content'] = wp_kses_post( $value['raw_instance']['content'] );
}
return $value['raw_instance'];
}
}
if (
empty( $value['is_widget_customizer_js_value'] ) ||
empty( $value['instance_hash_key'] ) ||
empty( $value['encoded_serialized_instance'] )
) {
return;
}
$decoded = base64_decode( $value['encoded_serialized_instance'], true );
if ( false === $decoded ) {
return;
}
if ( ! hash_equals( $this->get_instance_hash_key( $decoded ), $value['instance_hash_key'] ) ) {
return;
}
$instance = unserialize( $decoded );
if ( false === $instance ) {
return;
}
return $instance;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Factory::get\_widget\_object()](../wp_widget_factory/get_widget_object) wp-includes/class-wp-widget-factory.php | Returns the registered [WP\_Widget](../wp_widget) object for the given widget type. |
| [wp\_use\_widgets\_block\_editor()](../../functions/wp_use_widgets_block_editor) wp-includes/widgets.php | Whether or not to use the block editor to manage widgets. Defaults to true unless a theme has removed support for widgets-block-editor or a plugin has filtered the return value of this function. |
| [wp\_kses\_post()](../../functions/wp_kses_post) wp-includes/kses.php | Sanitizes content for allowed HTML tags for post content. |
| [WP\_Customize\_Widgets::get\_instance\_hash\_key()](get_instance_hash_key) wp-includes/class-wp-customize-widgets.php | Retrieves MAC for a serialized widget instance string. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::call\_widget\_update()](call_widget_update) wp-includes/class-wp-customize-widgets.php | Finds and invokes the widget update and control callbacks. |
| [WP\_Customize\_Widgets::get\_setting\_args()](get_setting_args) wp-includes/class-wp-customize-widgets.php | Retrieves common arguments to supply when constructing a Customizer setting. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Added the `$id_base` parameter. |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::customize_dynamic_partial_args( array|false $partial_args, string $partial_id ): array WP\_Customize\_Widgets::customize\_dynamic\_partial\_args( array|false $partial\_args, string $partial\_id ): array
===================================================================================================================
Filters arguments for dynamic widget partials.
`$partial_args` array|false Required Partial arguments. `$partial_id` string Required Partial ID. array (Maybe) modified partial arguments.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
return $partial_args;
}
if ( preg_match( '/^widget\[(?P<widget_id>.+)\]$/', $partial_id, $matches ) ) {
if ( false === $partial_args ) {
$partial_args = array();
}
$partial_args = array_merge(
$partial_args,
array(
'type' => 'widget',
'render_callback' => array( $this, 'render_widget_partial' ),
'container_inclusive' => true,
'settings' => array( $this->get_setting_id( $matches['widget_id'] ) ),
'capability' => 'edit_theme_options',
)
);
}
return $partial_args;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Widgets::get\_setting\_id()](get_setting_id) wp-includes/class-wp-customize-widgets.php | Converts a widget\_id into its corresponding Customizer setting ID (option name). |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Widgets::_sort_name_callback( array $widget_a, array $widget_b ): int WP\_Customize\_Widgets::\_sort\_name\_callback( array $widget\_a, array $widget\_b ): int
=========================================================================================
Naturally orders available widgets by name.
`$widget_a` array Required The first widget to compare. `$widget_b` array Required The second widget to compare. int Reorder position for the current widget comparison.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
protected function _sort_name_callback( $widget_a, $widget_b ) {
return strnatcasecmp( $widget_a['name'], $widget_b['name'] );
}
```
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::sanitize_sidebar_widgets_js_instance( array $widget_ids ): array WP\_Customize\_Widgets::sanitize\_sidebar\_widgets\_js\_instance( array $widget\_ids ): array
=============================================================================================
Strips out widget IDs for widgets which are no longer registered.
One example where this might happen is when a plugin orphans a widget in a sidebar upon deactivation.
`$widget_ids` array Required List of widget IDs. array Parsed list of widget IDs.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function sanitize_sidebar_widgets_js_instance( $widget_ids ) {
global $wp_registered_widgets;
$widget_ids = array_values( array_intersect( $widget_ids, array_keys( $wp_registered_widgets ) ) );
return $widget_ids;
}
```
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::get_widget_control( array $args ): string WP\_Customize\_Widgets::get\_widget\_control( array $args ): string
===================================================================
Retrieves the widget control markup.
`$args` array Required Widget control arguments. string Widget control form HTML markup.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function get_widget_control( $args ) {
$args[0]['before_form'] = '<div class="form">';
$args[0]['after_form'] = '</div><!-- .form -->';
$args[0]['before_widget_content'] = '<div class="widget-content">';
$args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
ob_start();
wp_widget_control( ...$args );
$control_tpl = ob_get_clean();
return $control_tpl;
}
```
| Uses | Description |
| --- | --- |
| [wp\_widget\_control()](../../functions/wp_widget_control) wp-admin/includes/widgets.php | Meta widget used to display the control form for a widget. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::get\_widget\_control\_parts()](get_widget_control_parts) wp-includes/class-wp-customize-widgets.php | Retrieves the widget control markup parts. |
| [WP\_Customize\_Widgets::get\_available\_widgets()](get_available_widgets) wp-includes/class-wp-customize-widgets.php | Builds up an index of all available widgets for use in Backbone models. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::get_post_value( string $name, mixed $default_value = null ): mixed WP\_Customize\_Widgets::get\_post\_value( string $name, mixed $default\_value = null ): mixed
=============================================================================================
Retrieves an unslashed post value or return a default.
`$name` string Required Post value. `$default_value` mixed Optional Default post value. Default: `null`
mixed Unslashed post value or default value.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
protected function get_post_value( $name, $default_value = null ) {
if ( ! isset( $_POST[ $name ] ) ) {
return $default_value;
}
return wp_unslash( $_POST[ $name ] );
}
```
| Uses | Description |
| --- | --- |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::call\_widget\_update()](call_widget_update) wp-includes/class-wp-customize-widgets.php | Finds and invokes the widget update and control callbacks. |
| [WP\_Customize\_Widgets::wp\_ajax\_update\_widget()](wp_ajax_update_widget) wp-includes/class-wp-customize-widgets.php | Updates widget settings asynchronously. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::print_footer_scripts() WP\_Customize\_Widgets::print\_footer\_scripts()
================================================
Calls admin\_print\_footer\_scripts and admin\_print\_scripts hooks to allow custom scripts from plugins.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function print_footer_scripts() {
/** This action is documented in wp-admin/admin-footer.php */
do_action( 'admin_print_footer_scripts-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
/** This action is documented in wp-admin/admin-footer.php */
do_action( 'admin_print_footer_scripts' );
/** This action is documented in wp-admin/admin-footer.php */
do_action( 'admin_footer-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
}
```
[do\_action( 'admin\_print\_footer\_scripts' )](../../hooks/admin_print_footer_scripts)
Prints any scripts and data queued for the footer.
| 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.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::filter_customize_dynamic_setting_args( false|array $args, string $setting_id ): array|false WP\_Customize\_Widgets::filter\_customize\_dynamic\_setting\_args( false|array $args, string $setting\_id ): array|false
========================================================================================================================
Determines the arguments for a dynamically-created setting.
`$args` false|array Required The arguments to the [WP\_Customize\_Setting](../wp_customize_setting) constructor. `$setting_id` string Required ID for dynamic setting, usually coming from `$_POST['customized']`. array|false Setting arguments, false otherwise.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function filter_customize_dynamic_setting_args( $args, $setting_id ) {
if ( $this->get_setting_type( $setting_id ) ) {
$args = $this->get_setting_args( $setting_id );
}
return $args;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Widgets::get\_setting\_type()](get_setting_type) wp-includes/class-wp-customize-widgets.php | Retrieves the widget setting type given a setting ID. |
| [WP\_Customize\_Widgets::get\_setting\_args()](get_setting_args) wp-includes/class-wp-customize-widgets.php | Retrieves common arguments to supply when constructing a Customizer setting. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Widgets::get_captured_options(): array WP\_Customize\_Widgets::get\_captured\_options(): array
=======================================================
Retrieves captured widget option updates.
array Array of captured options.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
protected function get_captured_options() {
return $this->_captured_options;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::call\_widget\_update()](call_widget_update) wp-includes/class-wp-customize-widgets.php | Finds and invokes the widget update and control callbacks. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::print_preview_css() WP\_Customize\_Widgets::print\_preview\_css()
=============================================
Inserts default style for highlighted widget at early point so theme stylesheet can override.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function print_preview_css() {
?>
<style>
.widget-customizer-highlighted-widget {
outline: none;
-webkit-box-shadow: 0 0 2px rgba(30, 140, 190, 0.8);
box-shadow: 0 0 2px rgba(30, 140, 190, 0.8);
position: relative;
z-index: 1;
}
</style>
<?php
}
```
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::filter_dynamic_sidebar_params( array $params ): array WP\_Customize\_Widgets::filter\_dynamic\_sidebar\_params( array $params ): array
================================================================================
Inject selective refresh data attributes into widget container elements.
* [WP\_Customize\_Nav\_Menus::filter\_wp\_nav\_menu\_args()](../wp_customize_nav_menus/filter_wp_nav_menu_args)
`$params` array Required Dynamic sidebar params.
* `args`arraySidebar args.
* `widget_args`arrayWidget args.
array Params.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function filter_dynamic_sidebar_params( $params ) {
$sidebar_args = array_merge(
array(
'before_widget' => '',
'after_widget' => '',
),
$params[0]
);
// Skip widgets not in a registered sidebar or ones which lack a proper wrapper element to attach the data-* attributes to.
$matches = array();
$is_valid = (
isset( $sidebar_args['id'] )
&&
is_registered_sidebar( $sidebar_args['id'] )
&&
( isset( $this->current_dynamic_sidebar_id_stack[0] ) && $this->current_dynamic_sidebar_id_stack[0] === $sidebar_args['id'] )
&&
preg_match( '#^<(?P<tag_name>\w+)#', $sidebar_args['before_widget'], $matches )
);
if ( ! $is_valid ) {
return $params;
}
$this->before_widget_tags_seen[ $matches['tag_name'] ] = true;
$context = array(
'sidebar_id' => $sidebar_args['id'],
);
if ( isset( $this->context_sidebar_instance_number ) ) {
$context['sidebar_instance_number'] = $this->context_sidebar_instance_number;
} elseif ( isset( $sidebar_args['id'] ) && isset( $this->sidebar_instance_count[ $sidebar_args['id'] ] ) ) {
$context['sidebar_instance_number'] = $this->sidebar_instance_count[ $sidebar_args['id'] ];
}
$attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'widget[' . $sidebar_args['widget_id'] . ']' ) );
$attributes .= ' data-customize-partial-type="widget"';
$attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $context ) ) );
$attributes .= sprintf( ' data-customize-widget-id="%s"', esc_attr( $sidebar_args['widget_id'] ) );
$sidebar_args['before_widget'] = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $sidebar_args['before_widget'] );
$params[0] = $sidebar_args;
return $params;
}
```
| Uses | Description |
| --- | --- |
| [is\_registered\_sidebar()](../../functions/is_registered_sidebar) wp-includes/widgets.php | Checks if a sidebar is registered. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Widgets::capture_filter_pre_update_option( mixed $new_value, string $option_name, mixed $old_value ): mixed WP\_Customize\_Widgets::capture\_filter\_pre\_update\_option( mixed $new\_value, string $option\_name, mixed $old\_value ): mixed
=================================================================================================================================
Pre-filters captured option values before updating.
`$new_value` mixed Required The new option value. `$option_name` string Required Name of the option. `$old_value` mixed Required The old option value. mixed Filtered option value.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function capture_filter_pre_update_option( $new_value, $option_name, $old_value ) {
if ( $this->is_option_capture_ignored( $option_name ) ) {
return $new_value;
}
if ( ! isset( $this->_captured_options[ $option_name ] ) ) {
add_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
}
$this->_captured_options[ $option_name ] = $new_value;
return $old_value;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Widgets::is\_option\_capture\_ignored()](is_option_capture_ignored) wp-includes/class-wp-customize-widgets.php | Determines whether the captured option update should be ignored. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::get_setting_type( string $setting_id ): string|void WP\_Customize\_Widgets::get\_setting\_type( string $setting\_id ): string|void
==============================================================================
Retrieves the widget setting type given a setting ID.
`$setting_id` string Required Setting ID. string|void Setting type.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
protected function get_setting_type( $setting_id ) {
static $cache = array();
if ( isset( $cache[ $setting_id ] ) ) {
return $cache[ $setting_id ];
}
foreach ( $this->setting_id_patterns as $type => $pattern ) {
if ( preg_match( $pattern, $setting_id ) ) {
$cache[ $setting_id ] = $type;
return $type;
}
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::register\_settings()](register_settings) wp-includes/class-wp-customize-widgets.php | Inspects the incoming customized data for any widget settings, and dynamically adds them up-front so widgets will be initialized properly. |
| [WP\_Customize\_Widgets::filter\_customize\_dynamic\_setting\_args()](filter_customize_dynamic_setting_args) wp-includes/class-wp-customize-widgets.php | Determines the arguments for a dynamically-created setting. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Customize_Widgets::render_widget_partial( WP_Customize_Partial $partial, array $context ): string|false WP\_Customize\_Widgets::render\_widget\_partial( WP\_Customize\_Partial $partial, array $context ): string|false
================================================================================================================
Renders a specific widget using the supplied sidebar arguments.
* [dynamic\_sidebar()](../../functions/dynamic_sidebar)
`$partial` [WP\_Customize\_Partial](../wp_customize_partial) Required Partial. `$context` array Required Sidebar args supplied as container context.
* `sidebar_id`stringID for sidebar for widget to render into.
* `sidebar_instance_number`intDisambiguating instance number.
string|false
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function render_widget_partial( $partial, $context ) {
$id_data = $partial->id_data();
$widget_id = array_shift( $id_data['keys'] );
if ( ! is_array( $context )
|| empty( $context['sidebar_id'] )
|| ! is_registered_sidebar( $context['sidebar_id'] )
) {
return false;
}
$this->rendering_sidebar_id = $context['sidebar_id'];
if ( isset( $context['sidebar_instance_number'] ) ) {
$this->context_sidebar_instance_number = (int) $context['sidebar_instance_number'];
}
// Filter sidebars_widgets so that only the queried widget is in the sidebar.
$this->rendering_widget_id = $widget_id;
$filter_callback = array( $this, 'filter_sidebars_widgets_for_rendering_widget' );
add_filter( 'sidebars_widgets', $filter_callback, 1000 );
// Render the widget.
ob_start();
$this->rendering_sidebar_id = $context['sidebar_id'];
dynamic_sidebar( $this->rendering_sidebar_id );
$container = ob_get_clean();
// Reset variables for next partial render.
remove_filter( 'sidebars_widgets', $filter_callback, 1000 );
$this->context_sidebar_instance_number = null;
$this->rendering_sidebar_id = null;
$this->rendering_widget_id = null;
return $container;
}
```
| Uses | Description |
| --- | --- |
| [is\_registered\_sidebar()](../../functions/is_registered_sidebar) wp-includes/widgets.php | Checks if a sidebar is registered. |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| [dynamic\_sidebar()](../../functions/dynamic_sidebar) wp-includes/widgets.php | Display dynamic sidebar. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Widgets::is_widget_rendered( string $widget_id ): bool WP\_Customize\_Widgets::is\_widget\_rendered( string $widget\_id ): bool
========================================================================
Determine if a widget is rendered on the page.
`$widget_id` string Required Widget ID to check. bool Whether the widget is rendered.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function is_widget_rendered( $widget_id ) {
return ! empty( $this->rendered_widgets[ $widget_id ] );
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Widgets::sanitize_widget_js_instance( array $value, string $id_base = null ): array WP\_Customize\_Widgets::sanitize\_widget\_js\_instance( array $value, string $id\_base = null ): array
======================================================================================================
Converts a widget instance into JSON-representable format.
`$value` array Required Widget instance to convert to JSON. `$id_base` string Optional Base of the ID of the widget being sanitized. Default: `null`
array JSON-converted widget instance.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function sanitize_widget_js_instance( $value, $id_base = null ) {
global $wp_widget_factory;
if ( empty( $value['is_widget_customizer_js_value'] ) ) {
$serialized = serialize( $value );
$js_value = array(
'encoded_serialized_instance' => base64_encode( $serialized ),
'title' => empty( $value['title'] ) ? '' : $value['title'],
'is_widget_customizer_js_value' => true,
'instance_hash_key' => $this->get_instance_hash_key( $serialized ),
);
if ( $id_base && wp_use_widgets_block_editor() ) {
$widget_object = $wp_widget_factory->get_widget_object( $id_base );
if ( ! empty( $widget_object->widget_options['show_instance_in_rest'] ) ) {
$js_value['raw_instance'] = (object) $value;
}
}
return $js_value;
}
return $value;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Factory::get\_widget\_object()](../wp_widget_factory/get_widget_object) wp-includes/class-wp-widget-factory.php | Returns the registered [WP\_Widget](../wp_widget) object for the given widget type. |
| [wp\_use\_widgets\_block\_editor()](../../functions/wp_use_widgets_block_editor) wp-includes/widgets.php | Whether or not to use the block editor to manage widgets. Defaults to true unless a theme has removed support for widgets-block-editor or a plugin has filtered the return value of this function. |
| [WP\_Customize\_Widgets::get\_instance\_hash\_key()](get_instance_hash_key) wp-includes/class-wp-customize-widgets.php | Retrieves MAC for a serialized widget instance string. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::call\_widget\_update()](call_widget_update) wp-includes/class-wp-customize-widgets.php | Finds and invokes the widget update and control callbacks. |
| [WP\_Customize\_Widgets::wp\_ajax\_update\_widget()](wp_ajax_update_widget) wp-includes/class-wp-customize-widgets.php | Updates widget settings asynchronously. |
| [WP\_Customize\_Widgets::get\_setting\_args()](get_setting_args) wp-includes/class-wp-customize-widgets.php | Retrieves common arguments to supply when constructing a Customizer setting. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Added the `$id_base` parameter. |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::is_panel_active(): bool WP\_Customize\_Widgets::is\_panel\_active(): bool
=================================================
Determines whether the widgets panel is active, based on whether there are sidebars registered.
* WP\_Customize\_Panel::$active\_callback
bool Active.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function is_panel_active() {
global $wp_registered_sidebars;
return ! empty( $wp_registered_sidebars );
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Customize_Widgets::register_settings() WP\_Customize\_Widgets::register\_settings()
============================================
Inspects the incoming customized data for any widget settings, and dynamically adds them up-front so widgets will be initialized properly.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function register_settings() {
$widget_setting_ids = array();
$incoming_setting_ids = array_keys( $this->manager->unsanitized_post_values() );
foreach ( $incoming_setting_ids as $setting_id ) {
if ( ! is_null( $this->get_setting_type( $setting_id ) ) ) {
$widget_setting_ids[] = $setting_id;
}
}
if ( $this->manager->doing_ajax( 'update-widget' ) && isset( $_REQUEST['widget-id'] ) ) {
$widget_setting_ids[] = $this->get_setting_id( wp_unslash( $_REQUEST['widget-id'] ) );
}
$settings = $this->manager->add_dynamic_settings( array_unique( $widget_setting_ids ) );
if ( $this->manager->settings_previewed() ) {
foreach ( $settings as $setting ) {
$setting->preview();
}
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Widgets::get\_setting\_type()](get_setting_type) wp-includes/class-wp-customize-widgets.php | Retrieves the widget setting type given a setting ID. |
| [WP\_Customize\_Widgets::get\_setting\_id()](get_setting_id) wp-includes/class-wp-customize-widgets.php | Converts a widget\_id into its corresponding Customizer setting ID (option name). |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Customize_Widgets::sanitize_sidebar_widgets( string[] $widget_ids ): string[] WP\_Customize\_Widgets::sanitize\_sidebar\_widgets( string[] $widget\_ids ): string[]
=====================================================================================
Ensures sidebar widget arrays only ever contain widget IDS.
Used as the ‘sanitize\_callback’ for each $sidebars\_widgets setting.
`$widget_ids` string[] Required Array of widget IDs. string[] Array of sanitized widget IDs.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function sanitize_sidebar_widgets( $widget_ids ) {
$widget_ids = array_map( 'strval', (array) $widget_ids );
$sanitized_widget_ids = array();
foreach ( $widget_ids as $widget_id ) {
$sanitized_widget_ids[] = preg_replace( '/[^a-z0-9_\-]/', '', $widget_id );
}
return $sanitized_widget_ids;
}
```
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::override_sidebars_widgets_for_theme_switch() WP\_Customize\_Widgets::override\_sidebars\_widgets\_for\_theme\_switch()
=========================================================================
Override sidebars\_widgets for theme switch.
When switching a theme via the Customizer, supply any previously-configured sidebars\_widgets from the target theme as the initial sidebars\_widgets setting. Also store the old theme’s existing settings so that they can be passed along for storing in the sidebars\_widgets theme\_mod when the theme gets switched.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function override_sidebars_widgets_for_theme_switch() {
global $sidebars_widgets;
if ( $this->manager->doing_ajax() || $this->manager->is_theme_active() ) {
return;
}
$this->old_sidebars_widgets = wp_get_sidebars_widgets();
add_filter( 'customize_value_old_sidebars_widgets_data', array( $this, 'filter_customize_value_old_sidebars_widgets_data' ) );
$this->manager->set_post_value( 'old_sidebars_widgets_data', $this->old_sidebars_widgets ); // Override any value cached in changeset.
// retrieve_widgets() looks at the global $sidebars_widgets.
$sidebars_widgets = $this->old_sidebars_widgets;
$sidebars_widgets = retrieve_widgets( 'customize' );
add_filter( 'option_sidebars_widgets', array( $this, 'filter_option_sidebars_widgets_for_theme_switch' ), 1 );
// Reset global cache var used by wp_get_sidebars_widgets().
unset( $GLOBALS['_wp_sidebars_widgets'] );
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_sidebars\_widgets()](../../functions/wp_get_sidebars_widgets) wp-includes/widgets.php | Retrieve full list of sidebars and their widget instance IDs. |
| [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. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Widgets::customize_register() WP\_Customize\_Widgets::customize\_register()
=============================================
Registers Customizer settings and controls for all sidebars and widgets.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function customize_register() {
global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_sidebars;
$use_widgets_block_editor = wp_use_widgets_block_editor();
add_filter( 'sidebars_widgets', array( $this, 'preview_sidebars_widgets' ), 1 );
$sidebars_widgets = array_merge(
array( 'wp_inactive_widgets' => array() ),
array_fill_keys( array_keys( $wp_registered_sidebars ), array() ),
wp_get_sidebars_widgets()
);
$new_setting_ids = array();
/*
* Register a setting for all widgets, including those which are active,
* inactive, and orphaned since a widget may get suppressed from a sidebar
* via a plugin (like Widget Visibility).
*/
foreach ( array_keys( $wp_registered_widgets ) as $widget_id ) {
$setting_id = $this->get_setting_id( $widget_id );
$setting_args = $this->get_setting_args( $setting_id );
if ( ! $this->manager->get_setting( $setting_id ) ) {
$this->manager->add_setting( $setting_id, $setting_args );
}
$new_setting_ids[] = $setting_id;
}
/*
* Add a setting which will be supplied for the theme's sidebars_widgets
* theme_mod when the theme is switched.
*/
if ( ! $this->manager->is_theme_active() ) {
$setting_id = 'old_sidebars_widgets_data';
$setting_args = $this->get_setting_args(
$setting_id,
array(
'type' => 'global_variable',
'dirty' => true,
)
);
$this->manager->add_setting( $setting_id, $setting_args );
}
$this->manager->add_panel(
'widgets',
array(
'type' => 'widgets',
'title' => __( 'Widgets' ),
'description' => __( 'Widgets are independent sections of content that can be placed into widgetized areas provided by your theme (commonly called sidebars).' ),
'priority' => 110,
'active_callback' => array( $this, 'is_panel_active' ),
'auto_expand_sole_section' => true,
'theme_supports' => 'widgets',
)
);
foreach ( $sidebars_widgets as $sidebar_id => $sidebar_widget_ids ) {
if ( empty( $sidebar_widget_ids ) ) {
$sidebar_widget_ids = array();
}
$is_registered_sidebar = is_registered_sidebar( $sidebar_id );
$is_inactive_widgets = ( 'wp_inactive_widgets' === $sidebar_id );
$is_active_sidebar = ( $is_registered_sidebar && ! $is_inactive_widgets );
// Add setting for managing the sidebar's widgets.
if ( $is_registered_sidebar || $is_inactive_widgets ) {
$setting_id = sprintf( 'sidebars_widgets[%s]', $sidebar_id );
$setting_args = $this->get_setting_args( $setting_id );
if ( ! $this->manager->get_setting( $setting_id ) ) {
if ( ! $this->manager->is_theme_active() ) {
$setting_args['dirty'] = true;
}
$this->manager->add_setting( $setting_id, $setting_args );
}
$new_setting_ids[] = $setting_id;
// Add section to contain controls.
$section_id = sprintf( 'sidebar-widgets-%s', $sidebar_id );
if ( $is_active_sidebar ) {
$section_args = array(
'title' => $wp_registered_sidebars[ $sidebar_id ]['name'],
'priority' => array_search( $sidebar_id, array_keys( $wp_registered_sidebars ), true ),
'panel' => 'widgets',
'sidebar_id' => $sidebar_id,
);
if ( $use_widgets_block_editor ) {
$section_args['description'] = '';
} else {
$section_args['description'] = $wp_registered_sidebars[ $sidebar_id ]['description'];
}
/**
* Filters Customizer widget section arguments for a given sidebar.
*
* @since 3.9.0
*
* @param array $section_args Array of Customizer widget section arguments.
* @param string $section_id Customizer section ID.
* @param int|string $sidebar_id Sidebar ID.
*/
$section_args = apply_filters( 'customizer_widgets_section_args', $section_args, $section_id, $sidebar_id );
$section = new WP_Customize_Sidebar_Section( $this->manager, $section_id, $section_args );
$this->manager->add_section( $section );
if ( $use_widgets_block_editor ) {
$control = new WP_Sidebar_Block_Editor_Control(
$this->manager,
$setting_id,
array(
'section' => $section_id,
'sidebar_id' => $sidebar_id,
'label' => $section_args['title'],
'description' => $section_args['description'],
)
);
} else {
$control = new WP_Widget_Area_Customize_Control(
$this->manager,
$setting_id,
array(
'section' => $section_id,
'sidebar_id' => $sidebar_id,
'priority' => count( $sidebar_widget_ids ), // place 'Add Widget' and 'Reorder' buttons at end.
)
);
}
$this->manager->add_control( $control );
$new_setting_ids[] = $setting_id;
}
}
if ( ! $use_widgets_block_editor ) {
// Add a control for each active widget (located in a sidebar).
foreach ( $sidebar_widget_ids as $i => $widget_id ) {
// Skip widgets that may have gone away due to a plugin being deactivated.
if ( ! $is_active_sidebar || ! isset( $wp_registered_widgets[ $widget_id ] ) ) {
continue;
}
$registered_widget = $wp_registered_widgets[ $widget_id ];
$setting_id = $this->get_setting_id( $widget_id );
$id_base = $wp_registered_widget_controls[ $widget_id ]['id_base'];
$control = new WP_Widget_Form_Customize_Control(
$this->manager,
$setting_id,
array(
'label' => $registered_widget['name'],
'section' => $section_id,
'sidebar_id' => $sidebar_id,
'widget_id' => $widget_id,
'widget_id_base' => $id_base,
'priority' => $i,
'width' => $wp_registered_widget_controls[ $widget_id ]['width'],
'height' => $wp_registered_widget_controls[ $widget_id ]['height'],
'is_wide' => $this->is_wide_widget( $widget_id ),
)
);
$this->manager->add_control( $control );
}
}
}
if ( $this->manager->settings_previewed() ) {
foreach ( $new_setting_ids as $new_setting_id ) {
$this->manager->get_setting( $new_setting_id )->preview();
}
}
}
```
[apply\_filters( 'customizer\_widgets\_section\_args', array $section\_args, string $section\_id, int|string $sidebar\_id )](../../hooks/customizer_widgets_section_args)
Filters Customizer widget section arguments for a given sidebar.
| Uses | Description |
| --- | --- |
| [wp\_use\_widgets\_block\_editor()](../../functions/wp_use_widgets_block_editor) wp-includes/widgets.php | Whether or not to use the block editor to manage widgets. Defaults to true unless a theme has removed support for widgets-block-editor or a plugin has filtered the return value of this function. |
| [is\_registered\_sidebar()](../../functions/is_registered_sidebar) wp-includes/widgets.php | Checks if a sidebar is registered. |
| [wp\_get\_sidebars\_widgets()](../../functions/wp_get_sidebars_widgets) wp-includes/widgets.php | Retrieve full list of sidebars and their widget instance IDs. |
| [WP\_Customize\_Widgets::get\_setting\_args()](get_setting_args) wp-includes/class-wp-customize-widgets.php | Retrieves common arguments to supply when constructing a Customizer setting. |
| [WP\_Customize\_Widgets::get\_setting\_id()](get_setting_id) wp-includes/class-wp-customize-widgets.php | Converts a widget\_id into its corresponding Customizer setting ID (option name). |
| [WP\_Customize\_Widgets::is\_wide\_widget()](is_wide_widget) wp-includes/class-wp-customize-widgets.php | Determines whether the widget is considered “wide”. |
| [\_\_()](../../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. |
| [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\_Widgets::schedule\_customize\_register()](schedule_customize_register) wp-includes/class-wp-customize-widgets.php | Ensures widgets are available for all types of previews. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::get_widget_control_parts( array $args ): array WP\_Customize\_Widgets::get\_widget\_control\_parts( array $args ): array
=========================================================================
Retrieves the widget control markup parts.
`$args` array Required Widget control arguments. array
* `control`stringMarkup for widget control wrapping form.
* `content`stringThe contents of the widget form itself.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function get_widget_control_parts( $args ) {
$args[0]['before_widget_content'] = '<div class="widget-content">';
$args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
$control_markup = $this->get_widget_control( $args );
$content_start_pos = strpos( $control_markup, $args[0]['before_widget_content'] );
$content_end_pos = strrpos( $control_markup, $args[0]['after_widget_content'] );
$control = substr( $control_markup, 0, $content_start_pos + strlen( $args[0]['before_widget_content'] ) );
$control .= substr( $control_markup, $content_end_pos );
$content = trim(
substr(
$control_markup,
$content_start_pos + strlen( $args[0]['before_widget_content'] ),
$content_end_pos - $content_start_pos - strlen( $args[0]['before_widget_content'] )
)
);
return compact( 'control', 'content' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Widgets::get\_widget\_control()](get_widget_control) wp-includes/class-wp-customize-widgets.php | Retrieves the widget control markup. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Customize_Widgets::get_setting_id( string $widget_id ): string WP\_Customize\_Widgets::get\_setting\_id( string $widget\_id ): string
======================================================================
Converts a widget\_id into its corresponding Customizer setting ID (option name).
`$widget_id` string Required Widget ID. string Maybe-parsed widget ID.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function get_setting_id( $widget_id ) {
$parsed_widget_id = $this->parse_widget_id( $widget_id );
$setting_id = sprintf( 'widget_%s', $parsed_widget_id['id_base'] );
if ( ! is_null( $parsed_widget_id['number'] ) ) {
$setting_id .= sprintf( '[%d]', $parsed_widget_id['number'] );
}
return $setting_id;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Widgets::parse\_widget\_id()](parse_widget_id) wp-includes/class-wp-customize-widgets.php | Converts a widget ID into its id\_base and number components. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::customize\_dynamic\_partial\_args()](customize_dynamic_partial_args) wp-includes/class-wp-customize-widgets.php | Filters arguments for dynamic widget partials. |
| [WP\_Customize\_Widgets::register\_settings()](register_settings) wp-includes/class-wp-customize-widgets.php | Inspects the incoming customized data for any widget settings, and dynamically adds them up-front so widgets will be initialized properly. |
| [WP\_Customize\_Widgets::call\_widget\_update()](call_widget_update) wp-includes/class-wp-customize-widgets.php | Finds and invokes the widget update and control callbacks. |
| [WP\_Customize\_Widgets::customize\_register()](customize_register) wp-includes/class-wp-customize-widgets.php | Registers Customizer settings and controls for all sidebars and widgets. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::prepreview_added_sidebars_widgets() WP\_Customize\_Widgets::prepreview\_added\_sidebars\_widgets()
==============================================================
This method has been deprecated. Deprecated in favor of the [‘customize\_dynamic\_setting\_args’](../../hooks/customize_dynamic_setting_args) filter instead.
{@internal Missing Summary}
See the [‘customize\_dynamic\_setting\_args’](../../hooks/customize_dynamic_setting_args) filter.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function prepreview_added_sidebars_widgets() {
_deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
}
```
| 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.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Deprecated in favor of the ['customize\_dynamic\_setting\_args'](../../hooks/customize_dynamic_setting_args) filter. |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::filter_sidebars_widgets_for_rendering_widget( array $sidebars_widgets ): array WP\_Customize\_Widgets::filter\_sidebars\_widgets\_for\_rendering\_widget( array $sidebars\_widgets ): array
============================================================================================================
Filters sidebars\_widgets to ensure the currently-rendered widget is the only widget in the current sidebar.
`$sidebars_widgets` array Required Sidebars widgets. array Filtered sidebars widgets.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function filter_sidebars_widgets_for_rendering_widget( $sidebars_widgets ) {
$sidebars_widgets[ $this->rendering_sidebar_id ] = array( $this->rendering_widget_id );
return $sidebars_widgets;
}
```
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Widgets::print_scripts() WP\_Customize\_Widgets::print\_scripts()
========================================
Calls admin\_print\_scripts-widgets.php and admin\_print\_scripts hooks to allow custom scripts from plugins.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function print_scripts() {
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_print_scripts-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_print_scripts' );
}
```
[do\_action( 'admin\_print\_scripts' )](../../hooks/admin_print_scripts)
Fires when scripts are printed for all admin pages.
| 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.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::should_load_block_editor_scripts_and_styles( bool $is_block_editor_screen ): bool WP\_Customize\_Widgets::should\_load\_block\_editor\_scripts\_and\_styles( bool $is\_block\_editor\_screen ): bool
==================================================================================================================
Tells the script loader to load the scripts and styles of custom blocks if the widgets block editor is enabled.
`$is_block_editor_screen` bool Required Current decision about loading block assets. bool Filtered decision about loading block assets.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function should_load_block_editor_scripts_and_styles( $is_block_editor_screen ) {
if ( wp_use_widgets_block_editor() ) {
return true;
}
return $is_block_editor_screen;
}
```
| Uses | Description |
| --- | --- |
| [wp\_use\_widgets\_block\_editor()](../../functions/wp_use_widgets_block_editor) wp-includes/widgets.php | Whether or not to use the block editor to manage widgets. Defaults to true unless a theme has removed support for widgets-block-editor or a plugin has filtered the return value of this function. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_Customize_Widgets::parse_widget_setting_id( string $setting_id ): array|WP_Error WP\_Customize\_Widgets::parse\_widget\_setting\_id( string $setting\_id ): array|WP\_Error
==========================================================================================
Converts a widget setting ID (option path) to its id\_base and number components.
`$setting_id` string Required Widget setting ID. array|[WP\_Error](../wp_error) Array containing a widget's id\_base and number components, or a [WP\_Error](../wp_error) object.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function parse_widget_setting_id( $setting_id ) {
if ( ! preg_match( '/^(widget_(.+?))(?:\[(\d+)\])?$/', $setting_id, $matches ) ) {
return new WP_Error( 'widget_setting_invalid_id' );
}
$id_base = $matches[2];
$number = isset( $matches[3] ) ? (int) $matches[3] : null;
return compact( 'id_base', 'number' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::start_capturing_option_updates() WP\_Customize\_Widgets::start\_capturing\_option\_updates()
===========================================================
Begins keeping track of changes to widget options, caching new values.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
protected function start_capturing_option_updates() {
if ( $this->_is_capturing_option_updates ) {
return;
}
$this->_is_capturing_option_updates = true;
add_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10, 3 );
}
```
| Uses | Description |
| --- | --- |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::call\_widget\_update()](call_widget_update) wp-includes/class-wp-customize-widgets.php | Finds and invokes the widget update and control callbacks. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Widgets::capture_filter_pre_get_option( mixed $value ): mixed WP\_Customize\_Widgets::capture\_filter\_pre\_get\_option( mixed $value ): mixed
================================================================================
Pre-filters captured option values before retrieving.
`$value` mixed Required Value to return instead of the option value. mixed Filtered option value.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function capture_filter_pre_get_option( $value ) {
$option_name = preg_replace( '/^pre_option_/', '', current_filter() );
if ( isset( $this->_captured_options[ $option_name ] ) ) {
$value = $this->_captured_options[ $option_name ];
/** This filter is documented in wp-includes/option.php */
$value = apply_filters( 'option_' . $option_name, $value, $option_name );
}
return $value;
}
```
| Uses | Description |
| --- | --- |
| [current\_filter()](../../functions/current_filter) wp-includes/plugin.php | Retrieves the name of the current filter hook. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::call_widget_update( string $widget_id ): array|WP_Error WP\_Customize\_Widgets::call\_widget\_update( string $widget\_id ): array|WP\_Error
===================================================================================
Finds and invokes the widget update and control callbacks.
Requires that `$_POST` be populated with the instance data.
`$widget_id` string Required Widget ID. array|[WP\_Error](../wp_error) Array containing the updated widget information.
A [WP\_Error](../wp_error) object, otherwise.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function call_widget_update( $widget_id ) {
global $wp_registered_widget_updates, $wp_registered_widget_controls;
$setting_id = $this->get_setting_id( $widget_id );
/*
* Make sure that other setting changes have previewed since this widget
* may depend on them (e.g. Menus being present for Navigation Menu widget).
*/
if ( ! did_action( 'customize_preview_init' ) ) {
foreach ( $this->manager->settings() as $setting ) {
if ( $setting->id !== $setting_id ) {
$setting->preview();
}
}
}
$this->start_capturing_option_updates();
$parsed_id = $this->parse_widget_id( $widget_id );
$option_name = 'widget_' . $parsed_id['id_base'];
/*
* If a previously-sanitized instance is provided, populate the input vars
* with its values so that the widget update callback will read this instance
*/
$added_input_vars = array();
if ( ! empty( $_POST['sanitized_widget_setting'] ) ) {
$sanitized_widget_setting = json_decode( $this->get_post_value( 'sanitized_widget_setting' ), true );
if ( false === $sanitized_widget_setting ) {
$this->stop_capturing_option_updates();
return new WP_Error( 'widget_setting_malformed' );
}
$instance = $this->sanitize_widget_instance( $sanitized_widget_setting, $parsed_id['id_base'] );
if ( is_null( $instance ) ) {
$this->stop_capturing_option_updates();
return new WP_Error( 'widget_setting_unsanitized' );
}
if ( ! is_null( $parsed_id['number'] ) ) {
$value = array();
$value[ $parsed_id['number'] ] = $instance;
$key = 'widget-' . $parsed_id['id_base'];
$_REQUEST[ $key ] = wp_slash( $value );
$_POST[ $key ] = $_REQUEST[ $key ];
$added_input_vars[] = $key;
} else {
foreach ( $instance as $key => $value ) {
$_REQUEST[ $key ] = wp_slash( $value );
$_POST[ $key ] = $_REQUEST[ $key ];
$added_input_vars[] = $key;
}
}
}
// Invoke the widget update callback.
foreach ( (array) $wp_registered_widget_updates as $name => $control ) {
if ( $name === $parsed_id['id_base'] && is_callable( $control['callback'] ) ) {
ob_start();
call_user_func_array( $control['callback'], $control['params'] );
ob_end_clean();
break;
}
}
// Clean up any input vars that were manually added.
foreach ( $added_input_vars as $key ) {
unset( $_POST[ $key ] );
unset( $_REQUEST[ $key ] );
}
// Make sure the expected option was updated.
if ( 0 !== $this->count_captured_options() ) {
if ( $this->count_captured_options() > 1 ) {
$this->stop_capturing_option_updates();
return new WP_Error( 'widget_setting_too_many_options' );
}
$updated_option_name = key( $this->get_captured_options() );
if ( $updated_option_name !== $option_name ) {
$this->stop_capturing_option_updates();
return new WP_Error( 'widget_setting_unexpected_option' );
}
}
// Obtain the widget instance.
$option = $this->get_captured_option( $option_name );
if ( null !== $parsed_id['number'] ) {
$instance = $option[ $parsed_id['number'] ];
} else {
$instance = $option;
}
/*
* Override the incoming $_POST['customized'] for a newly-created widget's
* setting with the new $instance so that the preview filter currently
* in place from WP_Customize_Setting::preview() will use this value
* instead of the default widget instance value (an empty array).
*/
$this->manager->set_post_value( $setting_id, $this->sanitize_widget_js_instance( $instance, $parsed_id['id_base'] ) );
// Obtain the widget control with the updated instance in place.
ob_start();
$form = $wp_registered_widget_controls[ $widget_id ];
if ( $form ) {
call_user_func_array( $form['callback'], $form['params'] );
}
$form = ob_get_clean();
$this->stop_capturing_option_updates();
return compact( 'instance', 'form' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Widgets::get\_captured\_option()](get_captured_option) wp-includes/class-wp-customize-widgets.php | Retrieves the option that was captured from being saved. |
| [did\_action()](../../functions/did_action) wp-includes/plugin.php | Retrieves the number of times an action has been fired during the current request. |
| [WP\_Customize\_Widgets::start\_capturing\_option\_updates()](start_capturing_option_updates) wp-includes/class-wp-customize-widgets.php | Begins keeping track of changes to widget options, caching new values. |
| [WP\_Customize\_Widgets::stop\_capturing\_option\_updates()](stop_capturing_option_updates) wp-includes/class-wp-customize-widgets.php | Undoes any changes to the options since options capture began. |
| [WP\_Customize\_Widgets::sanitize\_widget\_instance()](sanitize_widget_instance) wp-includes/class-wp-customize-widgets.php | Sanitizes a widget instance. |
| [WP\_Customize\_Widgets::count\_captured\_options()](count_captured_options) wp-includes/class-wp-customize-widgets.php | Retrieves the number of captured widget option updates. |
| [WP\_Customize\_Widgets::get\_captured\_options()](get_captured_options) wp-includes/class-wp-customize-widgets.php | Retrieves captured widget option updates. |
| [WP\_Customize\_Widgets::sanitize\_widget\_js\_instance()](sanitize_widget_js_instance) wp-includes/class-wp-customize-widgets.php | Converts a widget instance into JSON-representable format. |
| [WP\_Customize\_Widgets::get\_setting\_id()](get_setting_id) wp-includes/class-wp-customize-widgets.php | Converts a widget\_id into its corresponding Customizer setting ID (option name). |
| [WP\_Customize\_Widgets::parse\_widget\_id()](parse_widget_id) wp-includes/class-wp-customize-widgets.php | Converts a widget ID into its id\_base and number components. |
| [WP\_Customize\_Widgets::get\_post\_value()](get_post_value) wp-includes/class-wp-customize-widgets.php | Retrieves an unslashed post value or return a default. |
| [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\_Customize\_Widgets::wp\_ajax\_update\_widget()](wp_ajax_update_widget) wp-includes/class-wp-customize-widgets.php | Updates widget settings asynchronously. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::export_preview_data() WP\_Customize\_Widgets::export\_preview\_data()
===============================================
Communicates the sidebars that appeared on the page at the very end of the page, and at the very end of the wp\_footer,
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function export_preview_data() {
global $wp_registered_sidebars, $wp_registered_widgets;
$switched_locale = switch_to_locale( get_user_locale() );
$l10n = array(
'widgetTooltip' => __( 'Shift-click to edit this widget.' ),
);
if ( $switched_locale ) {
restore_previous_locale();
}
$rendered_sidebars = array_filter( $this->rendered_sidebars );
$rendered_widgets = array_filter( $this->rendered_widgets );
// Prepare Customizer settings to pass to JavaScript.
$settings = array(
'renderedSidebars' => array_fill_keys( array_keys( $rendered_sidebars ), true ),
'renderedWidgets' => array_fill_keys( array_keys( $rendered_widgets ), true ),
'registeredSidebars' => array_values( $wp_registered_sidebars ),
'registeredWidgets' => $wp_registered_widgets,
'l10n' => $l10n,
'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
);
foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
unset( $registered_widget['callback'] ); // May not be JSON-serializeable.
}
?>
<script type="text/javascript">
var _wpWidgetCustomizerPreviewSettings = <?php echo wp_json_encode( $settings ); ?>;
</script>
<?php
}
```
| 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\_Widgets::get\_selective\_refreshable\_widgets()](get_selective_refreshable_widgets) wp-includes/class-wp-customize-widgets.php | List whether each registered widget can be use selective refresh. |
| [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 |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::get_setting_args( string $id, array $overrides = array() ): array WP\_Customize\_Widgets::get\_setting\_args( string $id, array $overrides = array() ): array
===========================================================================================
Retrieves common arguments to supply when constructing a Customizer setting.
`$id` string Required Widget setting ID. `$overrides` array Optional Array of setting overrides. Default: `array()`
array Possibly modified setting arguments.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function get_setting_args( $id, $overrides = array() ) {
$args = array(
'type' => 'option',
'capability' => 'edit_theme_options',
'default' => array(),
);
if ( preg_match( $this->setting_id_patterns['sidebar_widgets'], $id, $matches ) ) {
$args['sanitize_callback'] = array( $this, 'sanitize_sidebar_widgets' );
$args['sanitize_js_callback'] = array( $this, 'sanitize_sidebar_widgets_js_instance' );
$args['transport'] = current_theme_supports( 'customize-selective-refresh-widgets' ) ? 'postMessage' : 'refresh';
} elseif ( preg_match( $this->setting_id_patterns['widget_instance'], $id, $matches ) ) {
$id_base = $matches['id_base'];
$args['sanitize_callback'] = function( $value ) use ( $id_base ) {
return $this->sanitize_widget_instance( $value, $id_base );
};
$args['sanitize_js_callback'] = function( $value ) use ( $id_base ) {
return $this->sanitize_widget_js_instance( $value, $id_base );
};
$args['transport'] = $this->is_widget_selective_refreshable( $matches['id_base'] ) ? 'postMessage' : 'refresh';
}
$args = array_merge( $args, $overrides );
/**
* Filters the common arguments supplied when constructing a Customizer setting.
*
* @since 3.9.0
*
* @see WP_Customize_Setting
*
* @param array $args Array of Customizer setting arguments.
* @param string $id Widget setting ID.
*/
return apply_filters( 'widget_customizer_setting_args', $args, $id );
}
```
[apply\_filters( 'widget\_customizer\_setting\_args', array $args, string $id )](../../hooks/widget_customizer_setting_args)
Filters the common arguments supplied when constructing a Customizer setting.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Widgets::is\_widget\_selective\_refreshable()](is_widget_selective_refreshable) wp-includes/class-wp-customize-widgets.php | Determines if a widget supports selective refresh. |
| [WP\_Customize\_Widgets::sanitize\_widget\_instance()](sanitize_widget_instance) wp-includes/class-wp-customize-widgets.php | Sanitizes a widget instance. |
| [WP\_Customize\_Widgets::sanitize\_widget\_js\_instance()](sanitize_widget_js_instance) wp-includes/class-wp-customize-widgets.php | Converts a widget instance into JSON-representable format. |
| [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. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::filter\_customize\_dynamic\_setting\_args()](filter_customize_dynamic_setting_args) wp-includes/class-wp-customize-widgets.php | Determines the arguments for a dynamically-created setting. |
| [WP\_Customize\_Widgets::customize\_register()](customize_register) wp-includes/class-wp-customize-widgets.php | Registers Customizer settings and controls for all sidebars and widgets. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::customize_preview_init() WP\_Customize\_Widgets::customize\_preview\_init()
==================================================
Adds hooks for the Customizer preview.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function customize_preview_init() {
add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue' ) );
add_action( 'wp_print_styles', array( $this, 'print_preview_css' ), 1 );
add_action( 'wp_footer', array( $this, 'export_preview_data' ), 20 );
}
```
| Uses | Description |
| --- | --- |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::selective_refresh_init() WP\_Customize\_Widgets::selective\_refresh\_init()
==================================================
Adds hooks for selective refresh.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function selective_refresh_init() {
if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
return;
}
add_filter( 'dynamic_sidebar_params', array( $this, 'filter_dynamic_sidebar_params' ) );
add_filter( 'wp_kses_allowed_html', array( $this, 'filter_wp_kses_allowed_data_attributes' ) );
add_action( 'dynamic_sidebar_before', array( $this, 'start_dynamic_sidebar' ) );
add_action( 'dynamic_sidebar_after', array( $this, 'end_dynamic_sidebar' ) );
}
```
| Uses | Description |
| --- | --- |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [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. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Widgets::preview_sidebars_widgets( array $sidebars_widgets ): array WP\_Customize\_Widgets::preview\_sidebars\_widgets( array $sidebars\_widgets ): array
=====================================================================================
When previewing, ensures the proper previewing widgets are used.
Because [wp\_get\_sidebars\_widgets()](../../functions/wp_get_sidebars_widgets) gets called early at [‘init’](../../functions/%e2%80%98init%e2%80%99) (via [wp\_convert\_widget\_settings()](../../functions/wp_convert_widget_settings) ) and can set global variable `$_wp_sidebars_widgets` to the value of `get_option( 'sidebars_widgets' )` before the Customizer preview filter is added, it has to be reset after the filter has been added.
`$sidebars_widgets` array Required List of widgets for the current sidebar. array
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function preview_sidebars_widgets( $sidebars_widgets ) {
$sidebars_widgets = get_option( 'sidebars_widgets', array() );
unset( $sidebars_widgets['array_version'] );
return $sidebars_widgets;
}
```
| Uses | Description |
| --- | --- |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::customize_controls_init() WP\_Customize\_Widgets::customize\_controls\_init()
===================================================
Ensures all widgets get loaded into the Customizer.
Note: these actions are also fired in [wp\_ajax\_update\_widget()](../../functions/wp_ajax_update_widget) .
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function customize_controls_init() {
/** This action is documented in wp-admin/includes/ajax-actions.php */
do_action( 'load-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
/** This action is documented in wp-admin/includes/ajax-actions.php */
do_action( 'widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
/** This action is documented in wp-admin/widgets.php */
do_action( 'sidebar_admin_setup' );
}
```
[do\_action( 'load-widgets.php' )](../../hooks/load-widgets-php)
Fires early when editing the widgets displayed in sidebars.
[do\_action( 'sidebar\_admin\_setup' )](../../hooks/sidebar_admin_setup)
Fires early before the Widgets administration screen loads, after scripts are enqueued.
[do\_action( 'widgets.php' )](../../hooks/widgets-php)
Fires early when editing the widgets displayed in sidebars.
| 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.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Widgets::wp_ajax_update_widget() WP\_Customize\_Widgets::wp\_ajax\_update\_widget()
==================================================
Updates widget settings asynchronously.
Allows the Customizer to update a widget using its form, but return the new instance info via Ajax instead of saving it to the options table.
Most code here copied from [wp\_ajax\_save\_widget()](../../functions/wp_ajax_save_widget) .
* [wp\_ajax\_save\_widget()](../../functions/wp_ajax_save_widget)
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function wp_ajax_update_widget() {
if ( ! is_user_logged_in() ) {
wp_die( 0 );
}
check_ajax_referer( 'update-widget', 'nonce' );
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_die( -1 );
}
if ( empty( $_POST['widget-id'] ) ) {
wp_send_json_error( 'missing_widget-id' );
}
/** This action is documented in wp-admin/includes/ajax-actions.php */
do_action( 'load-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
/** This action is documented in wp-admin/includes/ajax-actions.php */
do_action( 'widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
/** This action is documented in wp-admin/widgets.php */
do_action( 'sidebar_admin_setup' );
$widget_id = $this->get_post_value( 'widget-id' );
$parsed_id = $this->parse_widget_id( $widget_id );
$id_base = $parsed_id['id_base'];
$is_updating_widget_template = (
isset( $_POST[ 'widget-' . $id_base ] )
&&
is_array( $_POST[ 'widget-' . $id_base ] )
&&
preg_match( '/__i__|%i%/', key( $_POST[ 'widget-' . $id_base ] ) )
);
if ( $is_updating_widget_template ) {
wp_send_json_error( 'template_widget_not_updatable' );
}
$updated_widget = $this->call_widget_update( $widget_id ); // => {instance,form}
if ( is_wp_error( $updated_widget ) ) {
wp_send_json_error( $updated_widget->get_error_code() );
}
$form = $updated_widget['form'];
$instance = $this->sanitize_widget_js_instance( $updated_widget['instance'], $id_base );
wp_send_json_success( compact( 'form', 'instance' ) );
}
```
[do\_action( 'load-widgets.php' )](../../hooks/load-widgets-php)
Fires early when editing the widgets displayed in sidebars.
[do\_action( 'sidebar\_admin\_setup' )](../../hooks/sidebar_admin_setup)
Fires early before the Widgets administration screen loads, after scripts are enqueued.
[do\_action( 'widgets.php' )](../../hooks/widgets-php)
Fires early when editing the widgets displayed in sidebars.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Widgets::sanitize\_widget\_js\_instance()](sanitize_widget_js_instance) wp-includes/class-wp-customize-widgets.php | Converts a widget instance into JSON-representable format. |
| [WP\_Customize\_Widgets::call\_widget\_update()](call_widget_update) wp-includes/class-wp-customize-widgets.php | Finds and invokes the widget update and control callbacks. |
| [WP\_Customize\_Widgets::get\_post\_value()](get_post_value) wp-includes/class-wp-customize-widgets.php | Retrieves an unslashed post value or return a default. |
| [WP\_Customize\_Widgets::parse\_widget\_id()](parse_widget_id) wp-includes/class-wp-customize-widgets.php | Converts a widget ID into its id\_base and number components. |
| [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. |
| [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. |
| [wp\_send\_json\_success()](../../functions/wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| [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. |
| [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_Customize_Widgets::customize_preview_enqueue() WP\_Customize\_Widgets::customize\_preview\_enqueue()
=====================================================
Enqueues scripts for the Customizer preview.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function customize_preview_enqueue() {
wp_enqueue_script( 'customize-preview-widgets' );
}
```
| Uses | Description |
| --- | --- |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::end_dynamic_sidebar( int|string $index ) WP\_Customize\_Widgets::end\_dynamic\_sidebar( int|string $index )
==================================================================
Finishes keeping track of the current sidebar being rendered.
Inserts a marker after widgets are rendered in a dynamic sidebar.
`$index` int|string Required Index, name, or ID of the dynamic sidebar. File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function end_dynamic_sidebar( $index ) {
array_shift( $this->current_dynamic_sidebar_id_stack );
if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
printf( "\n<!--dynamic_sidebar_after:%s:%d-->\n", esc_html( $index ), (int) $this->sidebar_instance_count[ $index ] );
}
}
```
| Uses | Description |
| --- | --- |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Widgets::remove_prepreview_filters() WP\_Customize\_Widgets::remove\_prepreview\_filters()
=====================================================
This method has been deprecated. Deprecated in favor of the [‘customize\_dynamic\_setting\_args’](../../hooks/customize_dynamic_setting_args) filter instead.
{@internal Missing Summary}
See the [‘customize\_dynamic\_setting\_args’](../../hooks/customize_dynamic_setting_args) filter.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function remove_prepreview_filters() {
_deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
}
```
| 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.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Deprecated in favor of the ['customize\_dynamic\_setting\_args'](../../hooks/customize_dynamic_setting_args) filter. |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::get_selective_refreshable_widgets(): array WP\_Customize\_Widgets::get\_selective\_refreshable\_widgets(): array
=====================================================================
List whether each registered widget can be use selective refresh.
If the theme does not support the customize-selective-refresh-widgets feature, then this will always return an empty array.
array Mapping of id\_base to support. If theme doesn't support selective refresh, an empty array is returned.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function get_selective_refreshable_widgets() {
global $wp_widget_factory;
if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
return array();
}
if ( ! isset( $this->selective_refreshable_widgets ) ) {
$this->selective_refreshable_widgets = array();
foreach ( $wp_widget_factory->widgets as $wp_widget ) {
$this->selective_refreshable_widgets[ $wp_widget->id_base ] = ! empty( $wp_widget->widget_options['customize_selective_refresh'] );
}
}
return $this->selective_refreshable_widgets;
}
```
| Uses | Description |
| --- | --- |
| [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\_Widgets::is\_widget\_selective\_refreshable()](is_widget_selective_refreshable) wp-includes/class-wp-customize-widgets.php | Determines if a widget supports selective refresh. |
| [WP\_Customize\_Widgets::export\_preview\_data()](export_preview_data) wp-includes/class-wp-customize-widgets.php | Communicates the sidebars that appeared on the page at the very end of the page, and at the very end of the wp\_footer, |
| [WP\_Customize\_Widgets::enqueue\_scripts()](enqueue_scripts) wp-includes/class-wp-customize-widgets.php | Enqueues scripts and styles for Customizer panel and export data to JavaScript. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Widgets::get_instance_hash_key( string $serialized_instance ): string WP\_Customize\_Widgets::get\_instance\_hash\_key( string $serialized\_instance ): string
========================================================================================
Retrieves MAC for a serialized widget instance string.
Allows values posted back from JS to be rejected if any tampering of the data has occurred.
`$serialized_instance` string Required Widget instance. string MAC for serialized widget instance.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
protected function get_instance_hash_key( $serialized_instance ) {
return wp_hash( $serialized_instance );
}
```
| Uses | Description |
| --- | --- |
| [wp\_hash()](../../functions/wp_hash) wp-includes/pluggable.php | Gets hash of given string. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::sanitize\_widget\_instance()](sanitize_widget_instance) wp-includes/class-wp-customize-widgets.php | Sanitizes a widget instance. |
| [WP\_Customize\_Widgets::sanitize\_widget\_js\_instance()](sanitize_widget_js_instance) wp-includes/class-wp-customize-widgets.php | Converts a widget instance into JSON-representable format. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::__construct( WP_Customize_Manager $manager ) WP\_Customize\_Widgets::\_\_construct( WP\_Customize\_Manager $manager )
========================================================================
Initial loader.
`$manager` [WP\_Customize\_Manager](../wp_customize_manager) Required Customizer bootstrap instance. File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function __construct( $manager ) {
$this->manager = $manager;
// See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L420-L449
add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
add_action( 'widgets_init', array( $this, 'register_settings' ), 95 );
add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
// Skip remaining hooks when the user can't manage widgets anyway.
if ( ! current_user_can( 'edit_theme_options' ) ) {
return;
}
add_action( 'wp_loaded', array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
add_action( 'customize_controls_init', array( $this, 'customize_controls_init' ) );
add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'customize_controls_print_styles', array( $this, 'print_styles' ) );
add_action( 'customize_controls_print_scripts', array( $this, 'print_scripts' ) );
add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_footer_scripts' ) );
add_action( 'customize_controls_print_footer_scripts', array( $this, 'output_widget_control_templates' ) );
add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
add_filter( 'customize_refresh_nonces', array( $this, 'refresh_nonces' ) );
add_filter( 'should_load_block_editor_scripts_and_styles', array( $this, 'should_load_block_editor_scripts_and_styles' ) );
add_action( 'dynamic_sidebar', array( $this, 'tally_rendered_widgets' ) );
add_filter( 'is_active_sidebar', array( $this, 'tally_sidebars_via_is_active_sidebar_calls' ), 10, 2 );
add_filter( 'dynamic_sidebar_has_widgets', array( $this, 'tally_sidebars_via_dynamic_sidebar_calls' ), 10, 2 );
// Selective Refresh.
add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
add_action( 'customize_preview_init', array( $this, 'selective_refresh_init' ) );
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [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\_Customize\_Manager::\_\_construct()](../wp_customize_manager/__construct) wp-includes/class-wp-customize-manager.php | Constructor. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::enqueue_scripts() WP\_Customize\_Widgets::enqueue\_scripts()
==========================================
Enqueues scripts and styles for Customizer panel and export data to JavaScript.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function enqueue_scripts() {
global $wp_scripts, $wp_registered_sidebars, $wp_registered_widgets;
wp_enqueue_style( 'customize-widgets' );
wp_enqueue_script( 'customize-widgets' );
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_enqueue_scripts', 'widgets.php' );
/*
* Export available widgets with control_tpl removed from model
* since plugins need templates to be in the DOM.
*/
$available_widgets = array();
foreach ( $this->get_available_widgets() as $available_widget ) {
unset( $available_widget['control_tpl'] );
$available_widgets[] = $available_widget;
}
$widget_reorder_nav_tpl = sprintf(
'<div class="widget-reorder-nav"><span class="move-widget" tabindex="0">%1$s</span><span class="move-widget-down" tabindex="0">%2$s</span><span class="move-widget-up" tabindex="0">%3$s</span></div>',
__( 'Move to another area…' ),
__( 'Move down' ),
__( 'Move up' )
);
$move_widget_area_tpl = str_replace(
array( '{description}', '{btn}' ),
array(
__( 'Select an area to move this widget into:' ),
_x( 'Move', 'Move widget' ),
),
'<div class="move-widget-area">
<p class="description">{description}</p>
<ul class="widget-area-select">
<% _.each( sidebars, function ( sidebar ){ %>
<li class="" data-id="<%- sidebar.id %>" title="<%- sidebar.description %>" tabindex="0"><%- sidebar.name %></li>
<% }); %>
</ul>
<div class="move-widget-actions">
<button class="move-widget-btn button" type="button">{btn}</button>
</div>
</div>'
);
/*
* Gather all strings in PHP that may be needed by JS on the client.
* Once JS i18n is implemented (in #20491), this can be removed.
*/
$some_non_rendered_areas_messages = array();
$some_non_rendered_areas_messages[1] = html_entity_decode(
__( 'Your theme has 1 other widget area, but this particular page does not display it.' ),
ENT_QUOTES,
get_bloginfo( 'charset' )
);
$registered_sidebar_count = count( $wp_registered_sidebars );
for ( $non_rendered_count = 2; $non_rendered_count < $registered_sidebar_count; $non_rendered_count++ ) {
$some_non_rendered_areas_messages[ $non_rendered_count ] = html_entity_decode(
sprintf(
/* translators: %s: The number of other widget areas registered but not rendered. */
_n(
'Your theme has %s other widget area, but this particular page does not display it.',
'Your theme has %s other widget areas, but this particular page does not display them.',
$non_rendered_count
),
number_format_i18n( $non_rendered_count )
),
ENT_QUOTES,
get_bloginfo( 'charset' )
);
}
if ( 1 === $registered_sidebar_count ) {
$no_areas_shown_message = html_entity_decode(
sprintf(
__( 'Your theme has 1 widget area, but this particular page does not display it.' )
),
ENT_QUOTES,
get_bloginfo( 'charset' )
);
} else {
$no_areas_shown_message = html_entity_decode(
sprintf(
/* translators: %s: The total number of widget areas registered. */
_n(
'Your theme has %s widget area, but this particular page does not display it.',
'Your theme has %s widget areas, but this particular page does not display them.',
$registered_sidebar_count
),
number_format_i18n( $registered_sidebar_count )
),
ENT_QUOTES,
get_bloginfo( 'charset' )
);
}
$settings = array(
'registeredSidebars' => array_values( $wp_registered_sidebars ),
'registeredWidgets' => $wp_registered_widgets,
'availableWidgets' => $available_widgets, // @todo Merge this with registered_widgets.
'l10n' => array(
'saveBtnLabel' => __( 'Apply' ),
'saveBtnTooltip' => __( 'Save and preview changes before publishing them.' ),
'removeBtnLabel' => __( 'Remove' ),
'removeBtnTooltip' => __( 'Keep widget settings and move it to the inactive widgets' ),
'error' => __( 'An error has occurred. Please reload the page and try again.' ),
'widgetMovedUp' => __( 'Widget moved up' ),
'widgetMovedDown' => __( 'Widget moved down' ),
'navigatePreview' => __( 'You can navigate to other pages on your site while using the Customizer to view and edit the widgets displayed on those pages.' ),
'someAreasShown' => $some_non_rendered_areas_messages,
'noAreasShown' => $no_areas_shown_message,
'reorderModeOn' => __( 'Reorder mode enabled' ),
'reorderModeOff' => __( 'Reorder mode closed' ),
'reorderLabelOn' => esc_attr__( 'Reorder widgets' ),
/* translators: %d: The number of widgets found. */
'widgetsFound' => __( 'Number of widgets found: %d' ),
'noWidgetsFound' => __( 'No widgets found.' ),
),
'tpl' => array(
'widgetReorderNav' => $widget_reorder_nav_tpl,
'moveWidgetArea' => $move_widget_area_tpl,
),
'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
);
foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
unset( $registered_widget['callback'] ); // May not be JSON-serializeable.
}
$wp_scripts->add_data(
'customize-widgets',
'data',
sprintf( 'var _wpCustomizeWidgetsSettings = %s;', wp_json_encode( $settings ) )
);
/*
* TODO: Update 'wp-customize-widgets' to not rely so much on things in
* 'customize-widgets'. This will let us skip most of the above and not
* enqueue 'customize-widgets' which saves bytes.
*/
if ( wp_use_widgets_block_editor() ) {
$block_editor_context = new WP_Block_Editor_Context(
array(
'name' => 'core/customize-widgets',
)
);
$editor_settings = get_block_editor_settings(
get_legacy_widget_block_editor_settings(),
$block_editor_context
);
wp_add_inline_script(
'wp-customize-widgets',
sprintf(
'wp.domReady( function() {
wp.customizeWidgets.initialize( "widgets-customizer", %s );
} );',
wp_json_encode( $editor_settings )
)
);
// Preload server-registered block schemas.
wp_add_inline_script(
'wp-blocks',
'wp.blocks.unstable__bootstrapServerSideBlockDefinitions(' . wp_json_encode( get_block_editor_server_block_settings() ) . ');'
);
wp_add_inline_script(
'wp-blocks',
sprintf( 'wp.blocks.setCategories( %s );', wp_json_encode( get_block_categories( $block_editor_context ) ) ),
'after'
);
wp_enqueue_script( 'wp-customize-widgets' );
wp_enqueue_style( 'wp-customize-widgets' );
/** This action is documented in edit-form-blocks.php */
do_action( 'enqueue_block_editor_assets' );
}
}
```
[do\_action( 'admin\_enqueue\_scripts', string $hook\_suffix )](../../hooks/admin_enqueue_scripts)
Enqueue scripts for all admin pages.
[do\_action( 'enqueue\_block\_editor\_assets' )](../../hooks/enqueue_block_editor_assets)
Fires after block assets have been enqueued for the editing interface.
| Uses | Description |
| --- | --- |
| [WP\_Block\_Editor\_Context::\_\_construct()](../wp_block_editor_context/__construct) wp-includes/class-wp-block-editor-context.php | Constructor. |
| [get\_block\_editor\_settings()](../../functions/get_block_editor_settings) wp-includes/block-editor.php | Returns the contextualized block editor settings for a selected editor context. |
| [wp\_enqueue\_style()](../../functions/wp_enqueue_style) wp-includes/functions.wp-styles.php | Enqueue a CSS stylesheet. |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [esc\_attr\_\_()](../../functions/esc_attr__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in an attribute. |
| [\_n()](../../functions/_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [WP\_Customize\_Widgets::get\_available\_widgets()](get_available_widgets) wp-includes/class-wp-customize-widgets.php | Builds up an index of all available widgets for use in Backbone models. |
| [WP\_Customize\_Widgets::get\_selective\_refreshable\_widgets()](get_selective_refreshable_widgets) wp-includes/class-wp-customize-widgets.php | List whether each registered widget can be use selective refresh. |
| [wp\_add\_inline\_script()](../../functions/wp_add_inline_script) wp-includes/functions.wp-scripts.php | Adds extra code to a registered script. |
| [get\_block\_categories()](../../functions/get_block_categories) wp-includes/block-editor.php | Returns all the categories for block types that will be shown in the block editor. |
| [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. |
| [wp\_use\_widgets\_block\_editor()](../../functions/wp_use_widgets_block_editor) wp-includes/widgets.php | Whether or not to use the block editor to manage widgets. Defaults to true unless a theme has removed support for widgets-block-editor or a plugin has filtered the return value of this function. |
| [get\_legacy\_widget\_block\_editor\_settings()](../../functions/get_legacy_widget_block_editor_settings) wp-includes/block-editor.php | Returns the block editor settings needed to use the Legacy Widget block which is not registered by default. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Widgets::output_widget_control_templates() WP\_Customize\_Widgets::output\_widget\_control\_templates()
============================================================
Renders the widget form control templates into the DOM.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function output_widget_control_templates() {
?>
<div id="widgets-left"><!-- compatibility with JS which looks for widget templates here -->
<div id="available-widgets">
<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">
<?php
/* translators: ▸ is the unicode right-pointing triangle. %s: Section title in the Customizer. */
printf( __( 'Customizing ▸ %s' ), esc_html( $this->manager->get_panel( 'widgets' )->title ) );
?>
</span>
<?php _e( 'Add a Widget' ); ?>
</h3>
</div>
<div id="available-widgets-filter">
<label class="screen-reader-text" for="widgets-search"><?php _e( 'Search Widgets' ); ?></label>
<input type="text" id="widgets-search" placeholder="<?php esc_attr_e( 'Search widgets…' ); ?>" aria-describedby="widgets-search-desc" />
<div class="search-icon" aria-hidden="true"></div>
<button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
<p class="screen-reader-text" id="widgets-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
</div>
<div id="available-widgets-list">
<?php foreach ( $this->get_available_widgets() as $available_widget ) : ?>
<div id="widget-tpl-<?php echo esc_attr( $available_widget['id'] ); ?>" data-widget-id="<?php echo esc_attr( $available_widget['id'] ); ?>" class="widget-tpl <?php echo esc_attr( $available_widget['id'] ); ?>" tabindex="0">
<?php echo $available_widget['control_tpl']; ?>
</div>
<?php endforeach; ?>
<p class="no-widgets-found-message"><?php _e( 'No widgets found.' ); ?></p>
</div><!-- #available-widgets-list -->
</div><!-- #available-widgets -->
</div><!-- #widgets-left -->
<?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. |
| [WP\_Customize\_Widgets::get\_available\_widgets()](get_available_widgets) wp-includes/class-wp-customize-widgets.php | Builds up an index of all available widgets for use in Backbone models. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](../../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. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::is_sidebar_rendered( string $sidebar_id ): bool WP\_Customize\_Widgets::is\_sidebar\_rendered( string $sidebar\_id ): bool
==========================================================================
Determines if a sidebar is rendered on the page.
`$sidebar_id` string Required Sidebar ID to check. bool Whether the sidebar is rendered.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function is_sidebar_rendered( $sidebar_id ) {
return ! empty( $this->rendered_sidebars[ $sidebar_id ] );
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Widgets::get_available_widgets(): array WP\_Customize\_Widgets::get\_available\_widgets(): array
========================================================
Builds up an index of all available widgets for use in Backbone models.
* [wp\_list\_widgets()](../../functions/wp_list_widgets)
array List of available widgets.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function get_available_widgets() {
static $available_widgets = array();
if ( ! empty( $available_widgets ) ) {
return $available_widgets;
}
global $wp_registered_widgets, $wp_registered_widget_controls;
require_once ABSPATH . 'wp-admin/includes/widgets.php'; // For next_widget_id_number().
$sort = $wp_registered_widgets;
usort( $sort, array( $this, '_sort_name_callback' ) );
$done = array();
foreach ( $sort as $widget ) {
if ( in_array( $widget['callback'], $done, true ) ) { // We already showed this multi-widget.
continue;
}
$sidebar = is_active_widget( $widget['callback'], $widget['id'], false, false );
$done[] = $widget['callback'];
if ( ! isset( $widget['params'][0] ) ) {
$widget['params'][0] = array();
}
$available_widget = $widget;
unset( $available_widget['callback'] ); // Not serializable to JSON.
$args = array(
'widget_id' => $widget['id'],
'widget_name' => $widget['name'],
'_display' => 'template',
);
$is_disabled = false;
$is_multi_widget = ( isset( $wp_registered_widget_controls[ $widget['id'] ]['id_base'] ) && isset( $widget['params'][0]['number'] ) );
if ( $is_multi_widget ) {
$id_base = $wp_registered_widget_controls[ $widget['id'] ]['id_base'];
$args['_temp_id'] = "$id_base-__i__";
$args['_multi_num'] = next_widget_id_number( $id_base );
$args['_add'] = 'multi';
} else {
$args['_add'] = 'single';
if ( $sidebar && 'wp_inactive_widgets' !== $sidebar ) {
$is_disabled = true;
}
$id_base = $widget['id'];
}
$list_widget_controls_args = wp_list_widget_controls_dynamic_sidebar(
array(
0 => $args,
1 => $widget['params'][0],
)
);
$control_tpl = $this->get_widget_control( $list_widget_controls_args );
// The properties here are mapped to the Backbone Widget model.
$available_widget = array_merge(
$available_widget,
array(
'temp_id' => isset( $args['_temp_id'] ) ? $args['_temp_id'] : null,
'is_multi' => $is_multi_widget,
'control_tpl' => $control_tpl,
'multi_number' => ( 'multi' === $args['_add'] ) ? $args['_multi_num'] : false,
'is_disabled' => $is_disabled,
'id_base' => $id_base,
'transport' => $this->is_widget_selective_refreshable( $id_base ) ? 'postMessage' : 'refresh',
'width' => $wp_registered_widget_controls[ $widget['id'] ]['width'],
'height' => $wp_registered_widget_controls[ $widget['id'] ]['height'],
'is_wide' => $this->is_wide_widget( $widget['id'] ),
)
);
$available_widgets[] = $available_widget;
}
return $available_widgets;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Widgets::is\_widget\_selective\_refreshable()](is_widget_selective_refreshable) wp-includes/class-wp-customize-widgets.php | Determines if a widget supports selective refresh. |
| [next\_widget\_id\_number()](../../functions/next_widget_id_number) wp-admin/includes/widgets.php | |
| [wp\_list\_widget\_controls\_dynamic\_sidebar()](../../functions/wp_list_widget_controls_dynamic_sidebar) wp-admin/includes/widgets.php | Retrieves the widget control arguments. |
| [is\_active\_widget()](../../functions/is_active_widget) wp-includes/widgets.php | Determines whether a given widget is displayed on the front end. |
| [WP\_Customize\_Widgets::get\_widget\_control()](get_widget_control) wp-includes/class-wp-customize-widgets.php | Retrieves the widget control markup. |
| [WP\_Customize\_Widgets::is\_wide\_widget()](is_wide_widget) wp-includes/class-wp-customize-widgets.php | Determines whether the widget is considered “wide”. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::enqueue\_scripts()](enqueue_scripts) wp-includes/class-wp-customize-widgets.php | Enqueues scripts and styles for Customizer panel and export data to JavaScript. |
| [WP\_Customize\_Widgets::output\_widget\_control\_templates()](output_widget_control_templates) wp-includes/class-wp-customize-widgets.php | Renders the widget form control templates into the DOM. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::is_wide_widget( string $widget_id ): bool WP\_Customize\_Widgets::is\_wide\_widget( string $widget\_id ): bool
====================================================================
Determines whether the widget is considered “wide”.
Core widgets which may have controls wider than 250, but can still be shown in the narrow Customizer panel. The RSS and Text widgets in Core, for example, have widths of 400 and yet they still render fine in the Customizer panel.
This method will return all Core widgets as being not wide, but this can be overridden with the [‘is\_wide\_widget\_in\_customizer’](../../hooks/is_wide_widget_in_customizer) filter.
`$widget_id` string Required Widget ID. bool Whether or not the widget is a "wide" widget.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function is_wide_widget( $widget_id ) {
global $wp_registered_widget_controls;
$parsed_widget_id = $this->parse_widget_id( $widget_id );
$width = $wp_registered_widget_controls[ $widget_id ]['width'];
$is_core = in_array( $parsed_widget_id['id_base'], $this->core_widget_id_bases, true );
$is_wide = ( $width > 250 && ! $is_core );
/**
* Filters whether the given widget is considered "wide".
*
* @since 3.9.0
*
* @param bool $is_wide Whether the widget is wide, Default false.
* @param string $widget_id Widget ID.
*/
return apply_filters( 'is_wide_widget_in_customizer', $is_wide, $widget_id );
}
```
[apply\_filters( 'is\_wide\_widget\_in\_customizer', bool $is\_wide, string $widget\_id )](../../hooks/is_wide_widget_in_customizer)
Filters whether the given widget is considered “wide”.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Widgets::parse\_widget\_id()](parse_widget_id) wp-includes/class-wp-customize-widgets.php | Converts a widget ID into its id\_base and number components. |
| [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\_Widgets::get\_available\_widgets()](get_available_widgets) wp-includes/class-wp-customize-widgets.php | Builds up an index of all available widgets for use in Backbone models. |
| [WP\_Customize\_Widgets::customize\_register()](customize_register) wp-includes/class-wp-customize-widgets.php | Registers Customizer settings and controls for all sidebars and widgets. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::filter_wp_kses_allowed_data_attributes( array $allowed_html ): array WP\_Customize\_Widgets::filter\_wp\_kses\_allowed\_data\_attributes( array $allowed\_html ): array
==================================================================================================
Ensures the HTML data-\* attributes for selective refresh are allowed by kses.
This is needed in case the `$before_widget` is run through [wp\_kses()](../../functions/wp_kses) when printed.
`$allowed_html` array Required Allowed HTML. array (Maybe) modified allowed HTML.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function filter_wp_kses_allowed_data_attributes( $allowed_html ) {
foreach ( array_keys( $this->before_widget_tags_seen ) as $tag_name ) {
if ( ! isset( $allowed_html[ $tag_name ] ) ) {
$allowed_html[ $tag_name ] = array();
}
$allowed_html[ $tag_name ] = array_merge(
$allowed_html[ $tag_name ],
array_fill_keys(
array(
'data-customize-partial-id',
'data-customize-partial-type',
'data-customize-partial-placement-context',
'data-customize-partial-widget-id',
'data-customize-partial-options',
),
true
)
);
}
return $allowed_html;
}
```
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Widgets::prepreview_added_widget_instance() WP\_Customize\_Widgets::prepreview\_added\_widget\_instance()
=============================================================
This method has been deprecated. Deprecated in favor of the [‘customize\_dynamic\_setting\_args’](../../hooks/customize_dynamic_setting_args) filter instead.
{@internal Missing Summary}
See the [‘customize\_dynamic\_setting\_args’](../../hooks/customize_dynamic_setting_args) filter.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function prepreview_added_widget_instance() {
_deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
}
```
| 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.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Deprecated in favor of the ['customize\_dynamic\_setting\_args'](../../hooks/customize_dynamic_setting_args) filter. |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::filter_customize_value_old_sidebars_widgets_data( array $old_sidebars_widgets ): array WP\_Customize\_Widgets::filter\_customize\_value\_old\_sidebars\_widgets\_data( array $old\_sidebars\_widgets ): array
======================================================================================================================
Filters old\_sidebars\_widgets\_data Customizer setting.
When switching themes, filter the Customizer setting old\_sidebars\_widgets\_data to supply initial $sidebars\_widgets before they were overridden by [retrieve\_widgets()](../../functions/retrieve_widgets) .
The value for old\_sidebars\_widgets\_data gets set in the old theme’s sidebars\_widgets theme\_mod.
* [WP\_Customize\_Widgets::handle\_theme\_switch()](../wp_customize_widgets/handle_theme_switch)
`$old_sidebars_widgets` array Required array
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function filter_customize_value_old_sidebars_widgets_data( $old_sidebars_widgets ) {
return $this->old_sidebars_widgets;
}
```
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::print_styles() WP\_Customize\_Widgets::print\_styles()
=======================================
Calls admin\_print\_styles-widgets.php and admin\_print\_styles hooks to allow custom styles from plugins.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function print_styles() {
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_print_styles-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_print_styles' );
}
```
[do\_action( 'admin\_print\_styles' )](../../hooks/admin_print_styles)
Fires when styles are printed for all admin pages.
| 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.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::get_captured_option( string $option_name, mixed $default_value = false ): mixed WP\_Customize\_Widgets::get\_captured\_option( string $option\_name, mixed $default\_value = false ): mixed
===========================================================================================================
Retrieves the option that was captured from being saved.
`$option_name` string Required Option name. `$default_value` mixed Optional Default value to return if the option does not exist. Default: `false`
mixed Value set for the option.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
protected function get_captured_option( $option_name, $default_value = false ) {
if ( array_key_exists( $option_name, $this->_captured_options ) ) {
$value = $this->_captured_options[ $option_name ];
} else {
$value = $default_value;
}
return $value;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::call\_widget\_update()](call_widget_update) wp-includes/class-wp-customize-widgets.php | Finds and invokes the widget update and control callbacks. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Customize_Widgets::tally_sidebars_via_is_active_sidebar_calls( bool $is_active, string $sidebar_id ): bool WP\_Customize\_Widgets::tally\_sidebars\_via\_is\_active\_sidebar\_calls( bool $is\_active, string $sidebar\_id ): bool
=======================================================================================================================
Tallies the sidebars rendered via [is\_active\_sidebar()](../../functions/is_active_sidebar) .
Keep track of the times that [is\_active\_sidebar()](../../functions/is_active_sidebar) is called in the template, and assume that this means that the sidebar would be rendered on the template if there were widgets populating it.
`$is_active` bool Required Whether the sidebar is active. `$sidebar_id` string Required Sidebar ID. bool Whether the sidebar is active.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function tally_sidebars_via_is_active_sidebar_calls( $is_active, $sidebar_id ) {
if ( is_registered_sidebar( $sidebar_id ) ) {
$this->rendered_sidebars[ $sidebar_id ] = true;
}
/*
* We may need to force this to true, and also force-true the value
* for 'dynamic_sidebar_has_widgets' if we want to ensure that there
* is an area to drop widgets into, if the sidebar is empty.
*/
return $is_active;
}
```
| Uses | Description |
| --- | --- |
| [is\_registered\_sidebar()](../../functions/is_registered_sidebar) wp-includes/widgets.php | Checks if a sidebar is registered. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Widgets::parse_widget_id( string $widget_id ): array WP\_Customize\_Widgets::parse\_widget\_id( string $widget\_id ): array
======================================================================
Converts a widget ID into its id\_base and number components.
`$widget_id` string Required Widget ID. array Array containing a widget's id\_base and number components.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function parse_widget_id( $widget_id ) {
$parsed = array(
'number' => null,
'id_base' => null,
);
if ( preg_match( '/^(.+)-(\d+)$/', $widget_id, $matches ) ) {
$parsed['id_base'] = $matches[1];
$parsed['number'] = (int) $matches[2];
} else {
// Likely an old single widget.
$parsed['id_base'] = $widget_id;
}
return $parsed;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::call\_widget\_update()](call_widget_update) wp-includes/class-wp-customize-widgets.php | Finds and invokes the widget update and control callbacks. |
| [WP\_Customize\_Widgets::wp\_ajax\_update\_widget()](wp_ajax_update_widget) wp-includes/class-wp-customize-widgets.php | Updates widget settings asynchronously. |
| [WP\_Customize\_Widgets::get\_setting\_id()](get_setting_id) wp-includes/class-wp-customize-widgets.php | Converts a widget\_id into its corresponding Customizer setting ID (option name). |
| [WP\_Customize\_Widgets::is\_wide\_widget()](is_wide_widget) wp-includes/class-wp-customize-widgets.php | Determines whether the widget is considered “wide”. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::is_option_capture_ignored( string $option_name ): bool WP\_Customize\_Widgets::is\_option\_capture\_ignored( string $option\_name ): bool
==================================================================================
Determines whether the captured option update should be ignored.
`$option_name` string Required Option name. bool Whether the option capture is ignored.
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
protected function is_option_capture_ignored( $option_name ) {
return ( 0 === strpos( $option_name, '_transient_' ) );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Widgets::capture\_filter\_pre\_update\_option()](capture_filter_pre_update_option) wp-includes/class-wp-customize-widgets.php | Pre-filters captured option values before updating. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress WP_Customize_Widgets::schedule_customize_register() WP\_Customize\_Widgets::schedule\_customize\_register()
=======================================================
Ensures widgets are available for all types of previews.
When in preview, hook to [‘customize\_register’](../../hooks/customize_register) for settings after WordPress is loaded so that all filters have been initialized (e.g. Widget Visibility).
File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/)
```
public function schedule_customize_register() {
if ( is_admin() ) {
$this->customize_register();
} else {
add_action( 'wp', array( $this, 'customize_register' ) );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Widgets::customize\_register()](customize_register) wp-includes/class-wp-customize-widgets.php | Registers Customizer settings and controls for all sidebars and widgets. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getTaxonomy( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getTaxonomy( array $args ): array|IXR\_Error
====================================================================
Retrieve a taxonomy.
* [get\_taxonomy()](../../functions/get_taxonomy)
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`stringTaxonomy name.
* `4`arrayOptional. Array of taxonomy fields to limit to in the return.
Accepts `'labels'`, `'cap'`, `'menu'`, and `'object_type'`.
Default empty array.
array|[IXR\_Error](../ixr_error) An array of taxonomy data on success, [IXR\_Error](../ixr_error) instance otherwise.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getTaxonomy( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$taxonomy = $args[3];
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/**
* Filters the taxonomy query fields used by the given XML-RPC method.
*
* @since 3.4.0
*
* @param array $fields An array of taxonomy fields to retrieve.
* @param string $method The method name.
*/
$fields = apply_filters( 'xmlrpc_default_taxonomy_fields', array( 'labels', 'cap', 'object_type' ), 'wp.getTaxonomy' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getTaxonomy', $args, $this );
if ( ! taxonomy_exists( $taxonomy ) ) {
return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
}
$taxonomy = get_taxonomy( $taxonomy );
if ( ! current_user_can( $taxonomy->cap->assign_terms ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign terms in this taxonomy.' ) );
}
return $this->_prepare_taxonomy( $taxonomy, $fields );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[apply\_filters( 'xmlrpc\_default\_taxonomy\_fields', array $fields, string $method )](../../hooks/xmlrpc_default_taxonomy_fields)
Filters the taxonomy query fields used by the given XML-RPC method.
| Uses | Description |
| --- | --- |
| [taxonomy\_exists()](../../functions/taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [wp\_xmlrpc\_server::\_prepare\_taxonomy()](_prepare_taxonomy) wp-includes/class-wp-xmlrpc-server.php | Prepares taxonomy data for return in an XML-RPC object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wp_xmlrpc_server::set_is_enabled() wp\_xmlrpc\_server::set\_is\_enabled()
======================================
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.
Set wp\_xmlrpc\_server::$is\_enabled property.
Determine whether the xmlrpc server is enabled on this WordPress install and set the is\_enabled property accordingly.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
private function set_is_enabled() {
/*
* Respect old get_option() filters left for back-compat when the 'enable_xmlrpc'
* option was deprecated in 3.5.0. Use the {@see 'xmlrpc_enabled'} hook instead.
*/
$is_enabled = apply_filters( 'pre_option_enable_xmlrpc', false );
if ( false === $is_enabled ) {
$is_enabled = apply_filters( 'option_enable_xmlrpc', true );
}
/**
* Filters whether XML-RPC methods requiring authentication are enabled.
*
* Contrary to the way it's named, this filter does not control whether XML-RPC is *fully*
* enabled, rather, it only controls whether XML-RPC methods requiring authentication - such
* as for publishing purposes - are enabled.
*
* Further, the filter does not control whether pingbacks or other custom endpoints that don't
* require authentication are enabled. This behavior is expected, and due to how parity was matched
* with the `enable_xmlrpc` UI option the filter replaced when it was introduced in 3.5.
*
* To disable XML-RPC methods that require authentication, use:
*
* add_filter( 'xmlrpc_enabled', '__return_false' );
*
* For more granular control over all XML-RPC methods and requests, see the {@see 'xmlrpc_methods'}
* and {@see 'xmlrpc_element_limit'} hooks.
*
* @since 3.5.0
*
* @param bool $is_enabled Whether XML-RPC is enabled. Default true.
*/
$this->is_enabled = apply_filters( 'xmlrpc_enabled', $is_enabled );
}
```
[apply\_filters( 'xmlrpc\_enabled', bool $is\_enabled )](../../hooks/xmlrpc_enabled)
Filters whether XML-RPC methods requiring authentication are enabled.
| 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\_xmlrpc\_server::\_\_construct()](__construct) wp-includes/class-wp-xmlrpc-server.php | Registers all of the XMLRPC methods that XMLRPC server understands. |
| Version | Description |
| --- | --- |
| [5.7.3](https://developer.wordpress.org/reference/since/5.7.3/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getPost( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getPost( array $args ): array|IXR\_Error
================================================================
Retrieve a post.
* [get\_post()](../../functions/get_post)
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intPost ID.
* `4`arrayOptional. The subset of post type fields to return.
array|[IXR\_Error](../ixr_error) Array contains (based on $fields parameter):
* `'post_id'`
* `'post_title'`
* `'post_date'`
* `'post_date_gmt'`
* `'post_modified'`
* `'post_modified_gmt'`
* `'post_status'`
* `'post_type'`
* `'post_name'`
* `'post_author'`
* `'post_password'`
* `'post_excerpt'`
* `'post_content'`
* `'link'`
* `'comment_status'`
* `'ping_status'`
* `'sticky'`
* `'custom_fields'`
* `'terms'`
* `'categories'`
* `'tags'`
* `'enclosure'`
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getPost( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post_id = (int) $args[3];
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/**
* Filters the list of post query fields used by the given XML-RPC method.
*
* @since 3.4.0
*
* @param array $fields Array of post fields. Default array contains 'post', 'terms', and 'custom_fields'.
* @param string $method Method name.
*/
$fields = apply_filters( 'xmlrpc_default_post_fields', array( 'post', 'terms', 'custom_fields' ), 'wp.getPost' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPost', $args, $this );
$post = get_post( $post_id, ARRAY_A );
if ( empty( $post['ID'] ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
return $this->_prepare_post( $post, $fields );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[apply\_filters( 'xmlrpc\_default\_post\_fields', array $fields, string $method )](../../hooks/xmlrpc_default_post_fields)
Filters the list of post query fields used by the given XML-RPC method.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [wp\_xmlrpc\_server::\_prepare\_post()](_prepare_post) wp-includes/class-wp-xmlrpc-server.php | Prepares post data for return in an XML-RPC object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_deleteComment( array $args ): bool|IXR_Error wp\_xmlrpc\_server::wp\_deleteComment( array $args ): bool|IXR\_Error
=====================================================================
Delete a comment.
By default, the comment will be moved to the Trash instead of deleted.
See [wp\_delete\_comment()](../../functions/wp_delete_comment) for more information on this behavior.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intComment ID.
bool|[IXR\_Error](../ixr_error) See [wp\_delete\_comment()](../../functions/wp_delete_comment) .
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_deleteComment( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$comment_ID = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! get_comment( $comment_ID ) ) {
return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
}
if ( ! current_user_can( 'edit_comment', $comment_ID ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to delete this comment.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.deleteComment', $args, $this );
$status = wp_delete_comment( $comment_ID );
if ( $status ) {
/**
* Fires after a comment has been successfully deleted via XML-RPC.
*
* @since 3.4.0
*
* @param int $comment_ID ID of the deleted comment.
* @param array $args An array of arguments to delete the comment.
*/
do_action( 'xmlrpc_call_success_wp_deleteComment', $comment_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
}
return $status;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[do\_action( 'xmlrpc\_call\_success\_wp\_deleteComment', int $comment\_ID, array $args )](../../hooks/xmlrpc_call_success_wp_deletecomment)
Fires after a comment has been successfully deleted via XML-RPC.
| Uses | Description |
| --- | --- |
| [wp\_delete\_comment()](../../functions/wp_delete_comment) wp-includes/comment.php | Trashes or deletes a comment. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [get\_comment()](../../functions/get_comment) wp-includes/comment.php | Retrieves comment data given a comment ID or comment object. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_editTerm( array $args ): true|IXR_Error wp\_xmlrpc\_server::wp\_editTerm( array $args ): true|IXR\_Error
================================================================
Edit a term.
* [wp\_update\_term()](../../functions/wp_update_term)
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intTerm ID.
* `4`arrayContent struct for editing a term. The struct must contain the term `'taxonomy'`. Optional accepted values include `'name'`, `'parent'`, `'description'`, and `'slug'`.
true|[IXR\_Error](../ixr_error) True on success, [IXR\_Error](../ixr_error) instance on failure.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_editTerm( $args ) {
if ( ! $this->minimum_args( $args, 5 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$term_id = (int) $args[3];
$content_struct = $args[4];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.editTerm', $args, $this );
if ( ! taxonomy_exists( $content_struct['taxonomy'] ) ) {
return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
}
$taxonomy = get_taxonomy( $content_struct['taxonomy'] );
$taxonomy = (array) $taxonomy;
// Hold the data of the term.
$term_data = array();
$term = get_term( $term_id, $content_struct['taxonomy'] );
if ( is_wp_error( $term ) ) {
return new IXR_Error( 500, $term->get_error_message() );
}
if ( ! $term ) {
return new IXR_Error( 404, __( 'Invalid term ID.' ) );
}
if ( ! current_user_can( 'edit_term', $term_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this term.' ) );
}
if ( isset( $content_struct['name'] ) ) {
$term_data['name'] = trim( $content_struct['name'] );
if ( empty( $term_data['name'] ) ) {
return new IXR_Error( 403, __( 'The term name cannot be empty.' ) );
}
}
if ( ! empty( $content_struct['parent'] ) ) {
if ( ! $taxonomy['hierarchical'] ) {
return new IXR_Error( 403, __( 'Cannot set parent term, taxonomy is not hierarchical.' ) );
}
$parent_term_id = (int) $content_struct['parent'];
$parent_term = get_term( $parent_term_id, $taxonomy['name'] );
if ( is_wp_error( $parent_term ) ) {
return new IXR_Error( 500, $parent_term->get_error_message() );
}
if ( ! $parent_term ) {
return new IXR_Error( 403, __( 'Parent term does not exist.' ) );
}
$term_data['parent'] = $content_struct['parent'];
}
if ( isset( $content_struct['description'] ) ) {
$term_data['description'] = $content_struct['description'];
}
if ( isset( $content_struct['slug'] ) ) {
$term_data['slug'] = $content_struct['slug'];
}
$term = wp_update_term( $term_id, $taxonomy['name'], $term_data );
if ( is_wp_error( $term ) ) {
return new IXR_Error( 500, $term->get_error_message() );
}
if ( ! $term ) {
return new IXR_Error( 500, __( 'Sorry, editing the term failed.' ) );
}
// Update term meta.
if ( isset( $content_struct['custom_fields'] ) ) {
$this->set_term_custom_fields( $term_id, $content_struct['custom_fields'] );
}
return true;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::set\_term\_custom\_fields()](set_term_custom_fields) wp-includes/class-wp-xmlrpc-server.php | Set custom fields for a term. |
| [wp\_update\_term()](../../functions/wp_update_term) wp-includes/taxonomy.php | Updates term based on arguments provided. |
| [taxonomy\_exists()](../../functions/taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::blogger_getUserInfo( array $args ): array|IXR_Error wp\_xmlrpc\_server::blogger\_getUserInfo( array $args ): array|IXR\_Error
=========================================================================
Retrieve user’s data.
Gives your client some info about you, so you don’t have to.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function blogger_getUserInfo( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to access user data on this site.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.getUserInfo', $args, $this );
$struct = array(
'nickname' => $user->nickname,
'userid' => $user->ID,
'url' => $user->user_url,
'lastname' => $user->last_name,
'firstname' => $user->first_name,
);
return $struct;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getComment( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getComment( array $args ): array|IXR\_Error
===================================================================
Retrieve comment.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intComment ID.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getComment( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$comment_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getComment', $args, $this );
$comment = get_comment( $comment_id );
if ( ! $comment ) {
return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
}
if ( ! current_user_can( 'edit_comment', $comment_id ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to moderate or edit this comment.' ) );
}
return $this->_prepare_comment( $comment );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_prepare\_comment()](_prepare_comment) wp-includes/class-wp-xmlrpc-server.php | Prepares comment data for return in an XML-RPC object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [get\_comment()](../../functions/get_comment) wp-includes/comment.php | Retrieves comment data given a comment ID or comment object. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wp_xmlrpc_server::_prepare_comment( WP_Comment $comment ): array wp\_xmlrpc\_server::\_prepare\_comment( WP\_Comment $comment ): array
=====================================================================
Prepares comment data for return in an XML-RPC object.
`$comment` [WP\_Comment](../wp_comment) Required The unprepared comment data. array The prepared comment data.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function _prepare_comment( $comment ) {
// Format page date.
$comment_date_gmt = $this->_convert_date_gmt( $comment->comment_date_gmt, $comment->comment_date );
if ( '0' == $comment->comment_approved ) {
$comment_status = 'hold';
} elseif ( 'spam' === $comment->comment_approved ) {
$comment_status = 'spam';
} elseif ( '1' == $comment->comment_approved ) {
$comment_status = 'approve';
} else {
$comment_status = $comment->comment_approved;
}
$_comment = array(
'date_created_gmt' => $comment_date_gmt,
'user_id' => $comment->user_id,
'comment_id' => $comment->comment_ID,
'parent' => $comment->comment_parent,
'status' => $comment_status,
'content' => $comment->comment_content,
'link' => get_comment_link( $comment ),
'post_id' => $comment->comment_post_ID,
'post_title' => get_the_title( $comment->comment_post_ID ),
'author' => $comment->comment_author,
'author_url' => $comment->comment_author_url,
'author_email' => $comment->comment_author_email,
'author_ip' => $comment->comment_author_IP,
'type' => $comment->comment_type,
);
/**
* Filters XML-RPC-prepared data for the given comment.
*
* @since 3.4.0
*
* @param array $_comment An array of prepared comment data.
* @param WP_Comment $comment Comment object.
*/
return apply_filters( 'xmlrpc_prepare_comment', $_comment, $comment );
}
```
[apply\_filters( 'xmlrpc\_prepare\_comment', array $\_comment, WP\_Comment $comment )](../../hooks/xmlrpc_prepare_comment)
Filters XML-RPC-prepared data for the given comment.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_convert\_date\_gmt()](_convert_date_gmt) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress GMT date string to an [IXR\_Date](../ixr_date) object. |
| [get\_the\_title()](../../functions/get_the_title) wp-includes/post-template.php | Retrieves the post title. |
| [get\_comment\_link()](../../functions/get_comment_link) wp-includes/comment-template.php | Retrieves the link to a given comment. |
| [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\_xmlrpc\_server::wp\_getComments()](wp_getcomments) wp-includes/class-wp-xmlrpc-server.php | Retrieve comments. |
| [wp\_xmlrpc\_server::wp\_getComment()](wp_getcomment) wp-includes/class-wp-xmlrpc-server.php | Retrieve comment. |
wordpress wp_xmlrpc_server::wp_getPageTemplates( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getPageTemplates( array $args ): array|IXR\_Error
=========================================================================
Retrieve page templates.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getPageTemplates( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_pages' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
}
$templates = get_page_templates();
$templates['Default'] = 'default';
return $templates;
}
```
| Uses | Description |
| --- | --- |
| [get\_page\_templates()](../../functions/get_page_templates) wp-admin/includes/theme.php | Gets the page templates available in this theme. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getPage( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getPage( array $args ): array|IXR\_Error
================================================================
Retrieve page.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`intPage ID.
* `2`stringUsername.
* `3`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getPage( $args ) {
$this->escape( $args );
$page_id = (int) $args[1];
$username = $args[2];
$password = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
$page = get_post( $page_id );
if ( ! $page ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_page', $page_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this page.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPage', $args, $this );
// If we found the page then format the data.
if ( $page->ID && ( 'page' === $page->post_type ) ) {
return $this->_prepare_page( $page );
} else {
// If the page doesn't exist, indicate that.
return new IXR_Error( 404, __( 'Sorry, no such page.' ) );
}
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_prepare\_page()](_prepare_page) wp-includes/class-wp-xmlrpc-server.php | Prepares page data for return in an XML-RPC object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_newComment( array $args ): int|IXR_Error wp\_xmlrpc\_server::wp\_newComment( array $args ): int|IXR\_Error
=================================================================
Create new comment.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`string|intPost ID or URL.
* `4`arrayContent structure.
int|[IXR\_Error](../ixr_error) See [wp\_new\_comment()](../../functions/wp_new_comment) .
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_newComment( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post = $args[3];
$content_struct = $args[4];
/**
* Filters whether to allow anonymous comments over XML-RPC.
*
* @since 2.7.0
*
* @param bool $allow Whether to allow anonymous commenting via XML-RPC.
* Default false.
*/
$allow_anon = apply_filters( 'xmlrpc_allow_anonymous_comments', false );
$user = $this->login( $username, $password );
if ( ! $user ) {
$logged_in = false;
if ( $allow_anon && get_option( 'comment_registration' ) ) {
return new IXR_Error( 403, __( 'Sorry, you must be logged in to comment.' ) );
} elseif ( ! $allow_anon ) {
return $this->error;
}
} else {
$logged_in = true;
}
if ( is_numeric( $post ) ) {
$post_id = absint( $post );
} else {
$post_id = url_to_postid( $post );
}
if ( ! $post_id ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! get_post( $post_id ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! comments_open( $post_id ) ) {
return new IXR_Error( 403, __( 'Sorry, comments are closed for this item.' ) );
}
if (
'publish' === get_post_status( $post_id ) &&
! current_user_can( 'edit_post', $post_id ) &&
post_password_required( $post_id )
) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to comment on this post.' ) );
}
if (
'private' === get_post_status( $post_id ) &&
! current_user_can( 'read_post', $post_id )
) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to comment on this post.' ) );
}
$comment = array(
'comment_post_ID' => $post_id,
'comment_content' => trim( $content_struct['content'] ),
);
if ( $logged_in ) {
$display_name = $user->display_name;
$user_email = $user->user_email;
$user_url = $user->user_url;
$comment['comment_author'] = $this->escape( $display_name );
$comment['comment_author_email'] = $this->escape( $user_email );
$comment['comment_author_url'] = $this->escape( $user_url );
$comment['user_id'] = $user->ID;
} else {
$comment['comment_author'] = '';
if ( isset( $content_struct['author'] ) ) {
$comment['comment_author'] = $content_struct['author'];
}
$comment['comment_author_email'] = '';
if ( isset( $content_struct['author_email'] ) ) {
$comment['comment_author_email'] = $content_struct['author_email'];
}
$comment['comment_author_url'] = '';
if ( isset( $content_struct['author_url'] ) ) {
$comment['comment_author_url'] = $content_struct['author_url'];
}
$comment['user_id'] = 0;
if ( get_option( 'require_name_email' ) ) {
if ( strlen( $comment['comment_author_email'] ) < 6 || '' === $comment['comment_author'] ) {
return new IXR_Error( 403, __( 'Comment author name and email are required.' ) );
} elseif ( ! is_email( $comment['comment_author_email'] ) ) {
return new IXR_Error( 403, __( 'A valid email address is required.' ) );
}
}
}
$comment['comment_parent'] = isset( $content_struct['comment_parent'] ) ? absint( $content_struct['comment_parent'] ) : 0;
/** This filter is documented in wp-includes/comment.php */
$allow_empty = apply_filters( 'allow_empty_comment', false, $comment );
if ( ! $allow_empty && '' === $comment['comment_content'] ) {
return new IXR_Error( 403, __( 'Comment is required.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.newComment', $args, $this );
$comment_ID = wp_new_comment( $comment, true );
if ( is_wp_error( $comment_ID ) ) {
return new IXR_Error( 403, $comment_ID->get_error_message() );
}
if ( ! $comment_ID ) {
return new IXR_Error( 403, __( 'Something went wrong.' ) );
}
/**
* Fires after a new comment has been successfully created via XML-RPC.
*
* @since 3.4.0
*
* @param int $comment_ID ID of the new comment.
* @param array $args An array of new comment arguments.
*/
do_action( 'xmlrpc_call_success_wp_newComment', $comment_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return $comment_ID;
}
```
[apply\_filters( 'allow\_empty\_comment', bool $allow\_empty\_comment, array $commentdata )](../../hooks/allow_empty_comment)
Filters whether an empty comment should be allowed.
[apply\_filters( 'xmlrpc\_allow\_anonymous\_comments', bool $allow )](../../hooks/xmlrpc_allow_anonymous_comments)
Filters whether to allow anonymous comments over XML-RPC.
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[do\_action( 'xmlrpc\_call\_success\_wp\_newComment', int $comment\_ID, array $args )](../../hooks/xmlrpc_call_success_wp_newcomment)
Fires after a new comment has been successfully created via XML-RPC.
| Uses | Description |
| --- | --- |
| [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\_post\_status()](../../functions/get_post_status) wp-includes/post.php | Retrieves the post status based on the post ID. |
| [wp\_new\_comment()](../../functions/wp_new_comment) wp-includes/comment.php | Adds a new comment to the database. |
| [is\_email()](../../functions/is_email) wp-includes/formatting.php | Verifies that an email is valid. |
| [comments\_open()](../../functions/comments_open) wp-includes/comment-template.php | Determines whether the current post is open for comments. |
| [url\_to\_postid()](../../functions/url_to_postid) wp-includes/rewrite.php | Examines a URL and try to determine the post ID it represents. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [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. |
| [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. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [\_\_()](../../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 |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::initialise_blog_option_info() wp\_xmlrpc\_server::initialise\_blog\_option\_info()
====================================================
Set up blog options property.
Passes property through [‘xmlrpc\_blog\_options’](../../hooks/xmlrpc_blog_options) filter.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function initialise_blog_option_info() {
$this->blog_options = array(
// Read-only options.
'software_name' => array(
'desc' => __( 'Software Name' ),
'readonly' => true,
'value' => 'WordPress',
),
'software_version' => array(
'desc' => __( 'Software Version' ),
'readonly' => true,
'value' => get_bloginfo( 'version' ),
),
'blog_url' => array(
'desc' => __( 'WordPress Address (URL)' ),
'readonly' => true,
'option' => 'siteurl',
),
'home_url' => array(
'desc' => __( 'Site Address (URL)' ),
'readonly' => true,
'option' => 'home',
),
'login_url' => array(
'desc' => __( 'Login Address (URL)' ),
'readonly' => true,
'value' => wp_login_url(),
),
'admin_url' => array(
'desc' => __( 'The URL to the admin area' ),
'readonly' => true,
'value' => get_admin_url(),
),
'image_default_link_type' => array(
'desc' => __( 'Image default link type' ),
'readonly' => true,
'option' => 'image_default_link_type',
),
'image_default_size' => array(
'desc' => __( 'Image default size' ),
'readonly' => true,
'option' => 'image_default_size',
),
'image_default_align' => array(
'desc' => __( 'Image default align' ),
'readonly' => true,
'option' => 'image_default_align',
),
'template' => array(
'desc' => __( 'Template' ),
'readonly' => true,
'option' => 'template',
),
'stylesheet' => array(
'desc' => __( 'Stylesheet' ),
'readonly' => true,
'option' => 'stylesheet',
),
'post_thumbnail' => array(
'desc' => __( 'Post Thumbnail' ),
'readonly' => true,
'value' => current_theme_supports( 'post-thumbnails' ),
),
// Updatable options.
'time_zone' => array(
'desc' => __( 'Time Zone' ),
'readonly' => false,
'option' => 'gmt_offset',
),
'blog_title' => array(
'desc' => __( 'Site Title' ),
'readonly' => false,
'option' => 'blogname',
),
'blog_tagline' => array(
'desc' => __( 'Site Tagline' ),
'readonly' => false,
'option' => 'blogdescription',
),
'date_format' => array(
'desc' => __( 'Date Format' ),
'readonly' => false,
'option' => 'date_format',
),
'time_format' => array(
'desc' => __( 'Time Format' ),
'readonly' => false,
'option' => 'time_format',
),
'users_can_register' => array(
'desc' => __( 'Allow new users to sign up' ),
'readonly' => false,
'option' => 'users_can_register',
),
'thumbnail_size_w' => array(
'desc' => __( 'Thumbnail Width' ),
'readonly' => false,
'option' => 'thumbnail_size_w',
),
'thumbnail_size_h' => array(
'desc' => __( 'Thumbnail Height' ),
'readonly' => false,
'option' => 'thumbnail_size_h',
),
'thumbnail_crop' => array(
'desc' => __( 'Crop thumbnail to exact dimensions' ),
'readonly' => false,
'option' => 'thumbnail_crop',
),
'medium_size_w' => array(
'desc' => __( 'Medium size image width' ),
'readonly' => false,
'option' => 'medium_size_w',
),
'medium_size_h' => array(
'desc' => __( 'Medium size image height' ),
'readonly' => false,
'option' => 'medium_size_h',
),
'medium_large_size_w' => array(
'desc' => __( 'Medium-Large size image width' ),
'readonly' => false,
'option' => 'medium_large_size_w',
),
'medium_large_size_h' => array(
'desc' => __( 'Medium-Large size image height' ),
'readonly' => false,
'option' => 'medium_large_size_h',
),
'large_size_w' => array(
'desc' => __( 'Large size image width' ),
'readonly' => false,
'option' => 'large_size_w',
),
'large_size_h' => array(
'desc' => __( 'Large size image height' ),
'readonly' => false,
'option' => 'large_size_h',
),
'default_comment_status' => array(
'desc' => __( 'Allow people to submit comments on new posts.' ),
'readonly' => false,
'option' => 'default_comment_status',
),
'default_ping_status' => array(
'desc' => __( 'Allow link notifications from other blogs (pingbacks and trackbacks) on new posts.' ),
'readonly' => false,
'option' => 'default_ping_status',
),
);
/**
* Filters the XML-RPC blog options property.
*
* @since 2.6.0
*
* @param array $blog_options An array of XML-RPC blog options.
*/
$this->blog_options = apply_filters( 'xmlrpc_blog_options', $this->blog_options );
}
```
[apply\_filters( 'xmlrpc\_blog\_options', array $blog\_options )](../../hooks/xmlrpc_blog_options)
Filters the XML-RPC blog options property.
| Uses | Description |
| --- | --- |
| [wp\_login\_url()](../../functions/wp_login_url) wp-includes/general-template.php | Retrieves the login URL. |
| [get\_admin\_url()](../../functions/get_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for a given site. |
| [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. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| [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\_xmlrpc\_server::\_\_construct()](__construct) wp-includes/class-wp-xmlrpc-server.php | Registers all of the XMLRPC methods that XMLRPC server understands. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress wp_xmlrpc_server::mw_editPost( array $args ): true|IXR_Error wp\_xmlrpc\_server::mw\_editPost( array $args ): true|IXR\_Error
================================================================
Edit a post.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intPost ID.
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayContent structure.
* `4`intOptional. Publish flag. 0 for draft, 1 for publish. Default 0.
true|[IXR\_Error](../ixr_error) True on success.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mw_editPost( $args ) {
$this->escape( $args );
$post_ID = (int) $args[0];
$username = $args[1];
$password = $args[2];
$content_struct = $args[3];
$publish = isset( $args[4] ) ? $args[4] : 0;
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'metaWeblog.editPost', $args, $this );
$postdata = get_post( $post_ID, ARRAY_A );
/*
* If there is no post data for the give post ID, stop now and return an error.
* Otherwise a new post will be created (which was the old behavior).
*/
if ( ! $postdata || empty( $postdata['ID'] ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
// Use wp.editPost to edit post types other than post and page.
if ( ! in_array( $postdata['post_type'], array( 'post', 'page' ), true ) ) {
return new IXR_Error( 401, __( 'Invalid post type.' ) );
}
// Thwart attempt to change the post type.
if ( ! empty( $content_struct['post_type'] ) && ( $content_struct['post_type'] != $postdata['post_type'] ) ) {
return new IXR_Error( 401, __( 'The post type may not be changed.' ) );
}
// Check for a valid post format if one was given.
if ( isset( $content_struct['wp_post_format'] ) ) {
$content_struct['wp_post_format'] = sanitize_key( $content_struct['wp_post_format'] );
if ( ! array_key_exists( $content_struct['wp_post_format'], get_post_format_strings() ) ) {
return new IXR_Error( 404, __( 'Invalid post format.' ) );
}
}
$this->escape( $postdata );
$ID = $postdata['ID'];
$post_content = $postdata['post_content'];
$post_title = $postdata['post_title'];
$post_excerpt = $postdata['post_excerpt'];
$post_password = $postdata['post_password'];
$post_parent = $postdata['post_parent'];
$post_type = $postdata['post_type'];
$menu_order = $postdata['menu_order'];
$ping_status = $postdata['ping_status'];
$comment_status = $postdata['comment_status'];
// Let WordPress manage slug if none was provided.
$post_name = $postdata['post_name'];
if ( isset( $content_struct['wp_slug'] ) ) {
$post_name = $content_struct['wp_slug'];
}
// Only use a password if one was given.
if ( isset( $content_struct['wp_password'] ) ) {
$post_password = $content_struct['wp_password'];
}
// Only set a post parent if one was given.
if ( isset( $content_struct['wp_page_parent_id'] ) ) {
$post_parent = $content_struct['wp_page_parent_id'];
}
// Only set the 'menu_order' if it was given.
if ( isset( $content_struct['wp_page_order'] ) ) {
$menu_order = $content_struct['wp_page_order'];
}
$page_template = '';
if ( ! empty( $content_struct['wp_page_template'] ) && 'page' === $post_type ) {
$page_template = $content_struct['wp_page_template'];
}
$post_author = $postdata['post_author'];
// If an author id was provided then use it instead.
if ( isset( $content_struct['wp_author_id'] ) ) {
// Check permissions if attempting to switch author to or from another user.
if ( $user->ID != $content_struct['wp_author_id'] || $user->ID != $post_author ) {
switch ( $post_type ) {
case 'post':
if ( ! current_user_can( 'edit_others_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to change the post author as this user.' ) );
}
break;
case 'page':
if ( ! current_user_can( 'edit_others_pages' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to change the page author as this user.' ) );
}
break;
default:
return new IXR_Error( 401, __( 'Invalid post type.' ) );
}
$post_author = $content_struct['wp_author_id'];
}
}
if ( isset( $content_struct['mt_allow_comments'] ) ) {
if ( ! is_numeric( $content_struct['mt_allow_comments'] ) ) {
switch ( $content_struct['mt_allow_comments'] ) {
case 'closed':
$comment_status = 'closed';
break;
case 'open':
$comment_status = 'open';
break;
default:
$comment_status = get_default_comment_status( $post_type );
break;
}
} else {
switch ( (int) $content_struct['mt_allow_comments'] ) {
case 0:
case 2:
$comment_status = 'closed';
break;
case 1:
$comment_status = 'open';
break;
default:
$comment_status = get_default_comment_status( $post_type );
break;
}
}
}
if ( isset( $content_struct['mt_allow_pings'] ) ) {
if ( ! is_numeric( $content_struct['mt_allow_pings'] ) ) {
switch ( $content_struct['mt_allow_pings'] ) {
case 'closed':
$ping_status = 'closed';
break;
case 'open':
$ping_status = 'open';
break;
default:
$ping_status = get_default_comment_status( $post_type, 'pingback' );
break;
}
} else {
switch ( (int) $content_struct['mt_allow_pings'] ) {
case 0:
$ping_status = 'closed';
break;
case 1:
$ping_status = 'open';
break;
default:
$ping_status = get_default_comment_status( $post_type, 'pingback' );
break;
}
}
}
if ( isset( $content_struct['title'] ) ) {
$post_title = $content_struct['title'];
}
if ( isset( $content_struct['description'] ) ) {
$post_content = $content_struct['description'];
}
$post_category = array();
if ( isset( $content_struct['categories'] ) ) {
$catnames = $content_struct['categories'];
if ( is_array( $catnames ) ) {
foreach ( $catnames as $cat ) {
$post_category[] = get_cat_ID( $cat );
}
}
}
if ( isset( $content_struct['mt_excerpt'] ) ) {
$post_excerpt = $content_struct['mt_excerpt'];
}
$post_more = isset( $content_struct['mt_text_more'] ) ? $content_struct['mt_text_more'] : '';
$post_status = $publish ? 'publish' : 'draft';
if ( isset( $content_struct[ "{$post_type}_status" ] ) ) {
switch ( $content_struct[ "{$post_type}_status" ] ) {
case 'draft':
case 'pending':
case 'private':
case 'publish':
$post_status = $content_struct[ "{$post_type}_status" ];
break;
default:
$post_status = $publish ? 'publish' : 'draft';
break;
}
}
$tags_input = isset( $content_struct['mt_keywords'] ) ? $content_struct['mt_keywords'] : array();
if ( 'publish' === $post_status || 'private' === $post_status ) {
if ( 'page' === $post_type && ! current_user_can( 'publish_pages' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this page.' ) );
} elseif ( ! current_user_can( 'publish_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this post.' ) );
}
}
if ( $post_more ) {
$post_content = $post_content . '<!--more-->' . $post_more;
}
$to_ping = '';
if ( isset( $content_struct['mt_tb_ping_urls'] ) ) {
$to_ping = $content_struct['mt_tb_ping_urls'];
if ( is_array( $to_ping ) ) {
$to_ping = implode( ' ', $to_ping );
}
}
// Do some timestamp voodoo.
if ( ! empty( $content_struct['date_created_gmt'] ) ) {
// We know this is supposed to be GMT, so we're going to slap that Z on there by force.
$dateCreated = rtrim( $content_struct['date_created_gmt']->getIso(), 'Z' ) . 'Z';
} elseif ( ! empty( $content_struct['dateCreated'] ) ) {
$dateCreated = $content_struct['dateCreated']->getIso();
}
// Default to not flagging the post date to be edited unless it's intentional.
$edit_date = false;
if ( ! empty( $dateCreated ) ) {
$post_date = iso8601_to_datetime( $dateCreated );
$post_date_gmt = iso8601_to_datetime( $dateCreated, 'gmt' );
// Flag the post date to be edited.
$edit_date = true;
} else {
$post_date = $postdata['post_date'];
$post_date_gmt = $postdata['post_date_gmt'];
}
// We've got all the data -- post it.
$newpost = compact( 'ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'edit_date', 'post_date', 'post_date_gmt', 'to_ping', 'post_name', 'post_password', 'post_parent', 'menu_order', 'post_author', 'tags_input', 'page_template' );
$result = wp_update_post( $newpost, true );
if ( is_wp_error( $result ) ) {
return new IXR_Error( 500, $result->get_error_message() );
}
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, the post could not be updated.' ) );
}
// Only posts can be sticky.
if ( 'post' === $post_type && isset( $content_struct['sticky'] ) ) {
$data = $newpost;
$data['sticky'] = $content_struct['sticky'];
$data['post_type'] = 'post';
$error = $this->_toggle_sticky( $data, true );
if ( $error ) {
return $error;
}
}
if ( isset( $content_struct['custom_fields'] ) ) {
$this->set_custom_fields( $post_ID, $content_struct['custom_fields'] );
}
if ( isset( $content_struct['wp_post_thumbnail'] ) ) {
// Empty value deletes, non-empty value adds/updates.
if ( empty( $content_struct['wp_post_thumbnail'] ) ) {
delete_post_thumbnail( $post_ID );
} else {
if ( set_post_thumbnail( $post_ID, $content_struct['wp_post_thumbnail'] ) === false ) {
return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
}
}
unset( $content_struct['wp_post_thumbnail'] );
}
// Handle enclosures.
$thisEnclosure = isset( $content_struct['enclosure'] ) ? $content_struct['enclosure'] : null;
$this->add_enclosure_if_new( $post_ID, $thisEnclosure );
$this->attach_uploads( $ID, $post_content );
// Handle post formats if assigned, validation is handled earlier in this function.
if ( isset( $content_struct['wp_post_format'] ) ) {
set_post_format( $post_ID, $content_struct['wp_post_format'] );
}
/**
* Fires after a post has been successfully updated via the XML-RPC MovableType API.
*
* @since 3.4.0
*
* @param int $post_ID ID of the updated post.
* @param array $args An array of arguments to update the post.
*/
do_action( 'xmlrpc_call_success_mw_editPost', $post_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return true;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[do\_action( 'xmlrpc\_call\_success\_mw\_editPost', int $post\_ID, array $args )](../../hooks/xmlrpc_call_success_mw_editpost)
Fires after a post has been successfully updated via the XML-RPC MovableType API.
| Uses | Description |
| --- | --- |
| [set\_post\_thumbnail()](../../functions/set_post_thumbnail) wp-includes/post.php | Sets the post thumbnail (featured image) for the given post. |
| [set\_post\_format()](../../functions/set_post_format) wp-includes/post-formats.php | Assign a format to a post |
| [get\_default\_comment\_status()](../../functions/get_default_comment_status) wp-includes/comment.php | Gets the default comment status for a post type. |
| [wp\_xmlrpc\_server::set\_custom\_fields()](set_custom_fields) wp-includes/class-wp-xmlrpc-server.php | Set custom fields for post. |
| [iso8601\_to\_datetime()](../../functions/iso8601_to_datetime) wp-includes/formatting.php | Given an ISO 8601 (Ymd\TH:i:sO) date, returns a MySQL DateTime (Y-m-d H:i:s) format used by post\_date[\_gmt]. |
| [get\_cat\_ID()](../../functions/get_cat_id) wp-includes/category.php | Retrieves the ID of a category from its name. |
| [wp\_xmlrpc\_server::attach\_uploads()](attach_uploads) wp-includes/class-wp-xmlrpc-server.php | Attach upload to a post. |
| [delete\_post\_thumbnail()](../../functions/delete_post_thumbnail) wp-includes/post.php | Removes the thumbnail (featured image) from the given post. |
| [wp\_xmlrpc\_server::\_toggle\_sticky()](_toggle_sticky) wp-includes/class-wp-xmlrpc-server.php | Encapsulate the logic for sticking a post and determining if the user has permission to do so |
| [wp\_update\_post()](../../functions/wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [wp\_xmlrpc\_server::add\_enclosure\_if\_new()](add_enclosure_if_new) wp-includes/class-wp-xmlrpc-server.php | Adds an enclosure to a post if it’s new. |
| [get\_post\_format\_strings()](../../functions/get_post_format_strings) wp-includes/post-formats.php | Returns an array of post format slugs to their translated and pretty display versions |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [sanitize\_key()](../../functions/sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [\_\_()](../../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. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::wp\_editPage()](wp_editpage) wp-includes/class-wp-xmlrpc-server.php | Edit page. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::wp_getPageStatusList( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getPageStatusList( array $args ): array|IXR\_Error
==========================================================================
Retrieve page statuses.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getPageStatusList( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_pages' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPageStatusList', $args, $this );
return get_page_statuses();
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [get\_page\_statuses()](../../functions/get_page_statuses) wp-includes/post.php | Retrieves all of the WordPress support page statuses. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_newPage( array $args ): int|IXR_Error wp\_xmlrpc\_server::wp\_newPage( array $args ): int|IXR\_Error
==============================================================
Create new page.
* [wp\_xmlrpc\_server::mw\_newPost()](mw_newpost)
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayContent struct.
int|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_newPage( $args ) {
// Items not escaped here will be escaped in wp_newPost().
$username = $this->escape( $args[1] );
$password = $this->escape( $args[2] );
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.newPage', $args, $this );
// Mark this as content for a page.
$args[3]['post_type'] = 'page';
// Let mw_newPost() do all of the heavy lifting.
return $this->mw_newPost( $args );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::mw\_newPost()](mw_newpost) wp-includes/class-wp-xmlrpc-server.php | Create a new post. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getTags( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getTags( array $args ): array|IXR\_Error
================================================================
Get list of all tags
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getTags( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view tags.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getKeywords', $args, $this );
$tags = array();
$all_tags = get_tags();
if ( $all_tags ) {
foreach ( (array) $all_tags as $tag ) {
$struct = array();
$struct['tag_id'] = $tag->term_id;
$struct['name'] = $tag->name;
$struct['count'] = $tag->count;
$struct['slug'] = $tag->slug;
$struct['html_url'] = esc_html( get_tag_link( $tag->term_id ) );
$struct['rss_url'] = esc_html( get_tag_feed_link( $tag->term_id ) );
$tags[] = $struct;
}
}
return $tags;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [get\_tag\_link()](../../functions/get_tag_link) wp-includes/category-template.php | Retrieves the link to the tag. |
| [get\_tags()](../../functions/get_tags) wp-includes/category.php | Retrieves all post tags. |
| [get\_tag\_feed\_link()](../../functions/get_tag_feed_link) wp-includes/link-template.php | Retrieves the permalink for a tag feed. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wp_xmlrpc_server::serve_request() wp\_xmlrpc\_server::serve\_request()
====================================
Serves the XML-RPC request.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function serve_request() {
$this->IXR_Server( $this->methods );
}
```
| Version | Description |
| --- | --- |
| [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getAuthors( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getAuthors( array $args ): array|IXR\_Error
===================================================================
Retrieve authors list.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getAuthors( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getAuthors', $args, $this );
$authors = array();
foreach ( get_users( array( 'fields' => array( 'ID', 'user_login', 'display_name' ) ) ) as $user ) {
$authors[] = array(
'user_id' => $user->ID,
'user_login' => $user->user_login,
'display_name' => $user->display_name,
);
}
return $authors;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [get\_users()](../../functions/get_users) wp-includes/user.php | Retrieves list of users matching criteria. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_deletePost( array $args ): true|IXR_Error wp\_xmlrpc\_server::wp\_deletePost( array $args ): true|IXR\_Error
==================================================================
Delete a post for any registered post type.
* [wp\_delete\_post()](../../functions/wp_delete_post)
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intPost ID.
true|[IXR\_Error](../ixr_error) True on success, [IXR\_Error](../ixr_error) instance on failure.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_deletePost( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.deletePost', $args, $this );
$post = get_post( $post_id, ARRAY_A );
if ( empty( $post['ID'] ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'delete_post', $post_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this post.' ) );
}
$result = wp_delete_post( $post_id );
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, the post could not be deleted.' ) );
}
return true;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wp_xmlrpc_server::mt_getRecentPostTitles( array $args ): array|IXR_Error wp\_xmlrpc\_server::mt\_getRecentPostTitles( array $args ): array|IXR\_Error
============================================================================
Retrieve the post titles of recent posts.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intOptional. Number of posts.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mt_getRecentPostTitles( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
if ( isset( $args[3] ) ) {
$query = array( 'numberposts' => absint( $args[3] ) );
} else {
$query = array();
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.getRecentPostTitles', $args, $this );
$posts_list = wp_get_recent_posts( $query );
if ( ! $posts_list ) {
$this->error = new IXR_Error( 500, __( 'Either there are no posts, or something went wrong.' ) );
return $this->error;
}
$recent_posts = array();
foreach ( $posts_list as $entry ) {
if ( ! current_user_can( 'edit_post', $entry['ID'] ) ) {
continue;
}
$post_date = $this->_convert_date( $entry['post_date'] );
$post_date_gmt = $this->_convert_date_gmt( $entry['post_date_gmt'], $entry['post_date'] );
$recent_posts[] = array(
'dateCreated' => $post_date,
'userid' => $entry['post_author'],
'postid' => (string) $entry['ID'],
'title' => $entry['post_title'],
'post_status' => $entry['post_status'],
'date_created_gmt' => $post_date_gmt,
);
}
return $recent_posts;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_convert\_date()](_convert_date) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress date string to an [IXR\_Date](../ixr_date) object. |
| [wp\_get\_recent\_posts()](../../functions/wp_get_recent_posts) wp-includes/post.php | Retrieves a number of recent posts. |
| [wp\_xmlrpc\_server::\_convert\_date\_gmt()](_convert_date_gmt) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress GMT date string to an [IXR\_Date](../ixr_date) object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getRevisions( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getRevisions( array $args ): array|IXR\_Error
=====================================================================
Retrieve revisions for a specific post.
* [wp\_getPost()](../../functions/wp_getpost): for more on $fields
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intPost ID.
* `4`arrayOptional. Fields to fetch.
array|[IXR\_Error](../ixr_error) contains a collection of posts.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getRevisions( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post_id = (int) $args[3];
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/**
* Filters the default revision query fields used by the given XML-RPC method.
*
* @since 3.5.0
*
* @param array $field An array of revision query fields.
* @param string $method The method name.
*/
$fields = apply_filters( 'xmlrpc_default_revision_fields', array( 'post_date', 'post_date_gmt' ), 'wp.getRevisions' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getRevisions', $args, $this );
$post = get_post( $post_id );
if ( ! $post ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
}
// Check if revisions are enabled.
if ( ! wp_revisions_enabled( $post ) ) {
return new IXR_Error( 401, __( 'Sorry, revisions are disabled.' ) );
}
$revisions = wp_get_post_revisions( $post_id );
if ( ! $revisions ) {
return array();
}
$struct = array();
foreach ( $revisions as $revision ) {
if ( ! current_user_can( 'read_post', $revision->ID ) ) {
continue;
}
// Skip autosaves.
if ( wp_is_post_autosave( $revision ) ) {
continue;
}
$struct[] = $this->_prepare_post( get_object_vars( $revision ), $fields );
}
return $struct;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[apply\_filters( 'xmlrpc\_default\_revision\_fields', array $field, string $method )](../../hooks/xmlrpc_default_revision_fields)
Filters the default revision query fields used by the given XML-RPC method.
| Uses | Description |
| --- | --- |
| [wp\_revisions\_enabled()](../../functions/wp_revisions_enabled) wp-includes/revision.php | Determines whether revisions are enabled for a given post. |
| [wp\_get\_post\_revisions()](../../functions/wp_get_post_revisions) wp-includes/revision.php | Returns all revisions of specified post. |
| [wp\_is\_post\_autosave()](../../functions/wp_is_post_autosave) wp-includes/revision.php | Determines if the specified post is an autosave. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [wp\_xmlrpc\_server::\_prepare\_post()](_prepare_post) wp-includes/class-wp-xmlrpc-server.php | Prepares post data for return in an XML-RPC object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::wp_newCategory( array $args ): int|IXR_Error wp\_xmlrpc\_server::wp\_newCategory( array $args ): int|IXR\_Error
==================================================================
Create new category.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayCategory.
int|[IXR\_Error](../ixr_error) Category ID.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_newCategory( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$category = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.newCategory', $args, $this );
// Make sure the user is allowed to add a category.
if ( ! current_user_can( 'manage_categories' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to add a category.' ) );
}
// If no slug was provided, make it empty
// so that WordPress will generate one.
if ( empty( $category['slug'] ) ) {
$category['slug'] = '';
}
// If no parent_id was provided, make it empty
// so that it will be a top-level page (no parent).
if ( ! isset( $category['parent_id'] ) ) {
$category['parent_id'] = '';
}
// If no description was provided, make it empty.
if ( empty( $category['description'] ) ) {
$category['description'] = '';
}
$new_category = array(
'cat_name' => $category['name'],
'category_nicename' => $category['slug'],
'category_parent' => $category['parent_id'],
'category_description' => $category['description'],
);
$cat_id = wp_insert_category( $new_category, true );
if ( is_wp_error( $cat_id ) ) {
if ( 'term_exists' === $cat_id->get_error_code() ) {
return (int) $cat_id->get_error_data();
} else {
return new IXR_Error( 500, __( 'Sorry, the category could not be created.' ) );
}
} elseif ( ! $cat_id ) {
return new IXR_Error( 500, __( 'Sorry, the category could not be created.' ) );
}
/**
* Fires after a new category has been successfully created via XML-RPC.
*
* @since 3.4.0
*
* @param int $cat_id ID of the new category.
* @param array $args An array of new category arguments.
*/
do_action( 'xmlrpc_call_success_wp_newCategory', $cat_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return $cat_id;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[do\_action( 'xmlrpc\_call\_success\_wp\_newCategory', int $cat\_id, array $args )](../../hooks/xmlrpc_call_success_wp_newcategory)
Fires after a new category has been successfully created via XML-RPC.
| Uses | Description |
| --- | --- |
| [wp\_insert\_category()](../../functions/wp_insert_category) wp-admin/includes/taxonomy.php | Updates an existing Category or creates a new Category. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress wp_xmlrpc_server::pingback_ping( array $args ): string|IXR_Error wp\_xmlrpc\_server::pingback\_ping( array $args ): string|IXR\_Error
====================================================================
Retrieves a pingback and registers it.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* stringURL of page linked from.
* `1`stringURL of page linked to.
string|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function pingback_ping( $args ) {
global $wpdb;
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'pingback.ping', $args, $this );
$this->escape( $args );
$pagelinkedfrom = str_replace( '&', '&', $args[0] );
$pagelinkedto = str_replace( '&', '&', $args[1] );
$pagelinkedto = str_replace( '&', '&', $pagelinkedto );
/**
* Filters the pingback source URI.
*
* @since 3.6.0
*
* @param string $pagelinkedfrom URI of the page linked from.
* @param string $pagelinkedto URI of the page linked to.
*/
$pagelinkedfrom = apply_filters( 'pingback_ping_source_uri', $pagelinkedfrom, $pagelinkedto );
if ( ! $pagelinkedfrom ) {
return $this->pingback_error( 0, __( 'A valid URL was not provided.' ) );
}
// Check if the page linked to is on our site.
$pos1 = strpos( $pagelinkedto, str_replace( array( 'http://www.', 'http://', 'https://www.', 'https://' ), '', get_option( 'home' ) ) );
if ( ! $pos1 ) {
return $this->pingback_error( 0, __( 'Is there no link to us?' ) );
}
/*
* Let's find which post is linked to.
* FIXME: Does url_to_postid() cover all these cases already?
* If so, then let's use it and drop the old code.
*/
$urltest = parse_url( $pagelinkedto );
$post_ID = url_to_postid( $pagelinkedto );
if ( $post_ID ) {
// $way
} elseif ( isset( $urltest['path'] ) && preg_match( '#p/[0-9]{1,}#', $urltest['path'], $match ) ) {
// The path defines the post_ID (archives/p/XXXX).
$blah = explode( '/', $match[0] );
$post_ID = (int) $blah[1];
} elseif ( isset( $urltest['query'] ) && preg_match( '#p=[0-9]{1,}#', $urltest['query'], $match ) ) {
// The query string defines the post_ID (?p=XXXX).
$blah = explode( '=', $match[0] );
$post_ID = (int) $blah[1];
} elseif ( isset( $urltest['fragment'] ) ) {
// An #anchor is there, it's either...
if ( (int) $urltest['fragment'] ) {
// ...an integer #XXXX (simplest case),
$post_ID = (int) $urltest['fragment'];
} elseif ( preg_match( '/post-[0-9]+/', $urltest['fragment'] ) ) {
// ...a post ID in the form 'post-###',
$post_ID = preg_replace( '/[^0-9]+/', '', $urltest['fragment'] );
} elseif ( is_string( $urltest['fragment'] ) ) {
// ...or a string #title, a little more complicated.
$title = preg_replace( '/[^a-z0-9]/i', '.', $urltest['fragment'] );
$sql = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title RLIKE %s", $title );
$post_ID = $wpdb->get_var( $sql );
if ( ! $post_ID ) {
// Returning unknown error '0' is better than die()'ing.
return $this->pingback_error( 0, '' );
}
}
} else {
// TODO: Attempt to extract a post ID from the given URL.
return $this->pingback_error( 33, __( 'The specified target URL cannot be used as a target. It either does not exist, or it is not a pingback-enabled resource.' ) );
}
$post_ID = (int) $post_ID;
$post = get_post( $post_ID );
if ( ! $post ) { // Post not found.
return $this->pingback_error( 33, __( 'The specified target URL cannot be used as a target. It either does not exist, or it is not a pingback-enabled resource.' ) );
}
if ( url_to_postid( $pagelinkedfrom ) == $post_ID ) {
return $this->pingback_error( 0, __( 'The source URL and the target URL cannot both point to the same resource.' ) );
}
// Check if pings are on.
if ( ! pings_open( $post ) ) {
return $this->pingback_error( 33, __( 'The specified target URL cannot be used as a target. It either does not exist, or it is not a pingback-enabled resource.' ) );
}
// Let's check that the remote site didn't already pingback this entry.
if ( $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_author_url = %s", $post_ID, $pagelinkedfrom ) ) ) {
return $this->pingback_error( 48, __( 'The pingback has already been registered.' ) );
}
// Very stupid, but gives time to the 'from' server to publish!
sleep( 1 );
$remote_ip = preg_replace( '/[^0-9a-fA-F:., ]/', '', $_SERVER['REMOTE_ADDR'] );
/** This filter is documented in wp-includes/class-wp-http.php */
$user_agent = apply_filters( 'http_headers_useragent', 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ), $pagelinkedfrom );
// Let's check the remote site.
$http_api_args = array(
'timeout' => 10,
'redirection' => 0,
'limit_response_size' => 153600, // 150 KB
'user-agent' => "$user_agent; verifying pingback from $remote_ip",
'headers' => array(
'X-Pingback-Forwarded-For' => $remote_ip,
),
);
$request = wp_safe_remote_get( $pagelinkedfrom, $http_api_args );
$remote_source = wp_remote_retrieve_body( $request );
$remote_source_original = $remote_source;
if ( ! $remote_source ) {
return $this->pingback_error( 16, __( 'The source URL does not exist.' ) );
}
/**
* Filters the pingback remote source.
*
* @since 2.5.0
*
* @param string $remote_source Response source for the page linked from.
* @param string $pagelinkedto URL of the page linked to.
*/
$remote_source = apply_filters( 'pre_remote_source', $remote_source, $pagelinkedto );
// Work around bug in strip_tags():
$remote_source = str_replace( '<!DOC', '<DOC', $remote_source );
$remote_source = preg_replace( '/[\r\n\t ]+/', ' ', $remote_source ); // normalize spaces
$remote_source = preg_replace( '/<\/*(h1|h2|h3|h4|h5|h6|p|th|td|li|dt|dd|pre|caption|input|textarea|button|body)[^>]*>/', "\n\n", $remote_source );
preg_match( '|<title>([^<]*?)</title>|is', $remote_source, $matchtitle );
$title = isset( $matchtitle[1] ) ? $matchtitle[1] : '';
if ( empty( $title ) ) {
return $this->pingback_error( 32, __( 'A title on that page cannot be found.' ) );
}
// Remove all script and style tags including their content.
$remote_source = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $remote_source );
// Just keep the tag we need.
$remote_source = strip_tags( $remote_source, '<a>' );
$p = explode( "\n\n", $remote_source );
$preg_target = preg_quote( $pagelinkedto, '|' );
foreach ( $p as $para ) {
if ( strpos( $para, $pagelinkedto ) !== false ) { // It exists, but is it a link?
preg_match( '|<a[^>]+?' . $preg_target . '[^>]*>([^>]+?)</a>|', $para, $context );
// If the URL isn't in a link context, keep looking.
if ( empty( $context ) ) {
continue;
}
// We're going to use this fake tag to mark the context in a bit.
// The marker is needed in case the link text appears more than once in the paragraph.
$excerpt = preg_replace( '|\</?wpcontext\>|', '', $para );
// prevent really long link text
if ( strlen( $context[1] ) > 100 ) {
$context[1] = substr( $context[1], 0, 100 ) . '…';
}
$marker = '<wpcontext>' . $context[1] . '</wpcontext>'; // Set up our marker.
$excerpt = str_replace( $context[0], $marker, $excerpt ); // Swap out the link for our marker.
$excerpt = strip_tags( $excerpt, '<wpcontext>' ); // Strip all tags but our context marker.
$excerpt = trim( $excerpt );
$preg_marker = preg_quote( $marker, '|' );
$excerpt = preg_replace( "|.*?\s(.{0,100}$preg_marker.{0,100})\s.*|s", '$1', $excerpt );
$excerpt = strip_tags( $excerpt ); // YES, again, to remove the marker wrapper.
break;
}
}
if ( empty( $context ) ) { // Link to target not found.
return $this->pingback_error( 17, __( 'The source URL does not contain a link to the target URL, and so cannot be used as a source.' ) );
}
$pagelinkedfrom = str_replace( '&', '&', $pagelinkedfrom );
$context = '[…] ' . esc_html( $excerpt ) . ' […]';
$pagelinkedfrom = $this->escape( $pagelinkedfrom );
$comment_post_id = (int) $post_ID;
$comment_author = $title;
$comment_author_email = '';
$this->escape( $comment_author );
$comment_author_url = $pagelinkedfrom;
$comment_content = $context;
$this->escape( $comment_content );
$comment_type = 'pingback';
$commentdata = array(
'comment_post_ID' => $comment_post_id,
);
$commentdata += compact(
'comment_author',
'comment_author_url',
'comment_author_email',
'comment_content',
'comment_type',
'remote_source',
'remote_source_original'
);
$comment_ID = wp_new_comment( $commentdata );
if ( is_wp_error( $comment_ID ) ) {
return $this->pingback_error( 0, $comment_ID->get_error_message() );
}
/**
* Fires after a post pingback has been sent.
*
* @since 0.71
*
* @param int $comment_ID Comment ID.
*/
do_action( 'pingback_post', $comment_ID );
/* translators: 1: URL of the page linked from, 2: URL of the page linked to. */
return sprintf( __( 'Pingback from %1$s to %2$s registered. Keep the web talking! :-)' ), $pagelinkedfrom, $pagelinkedto );
}
```
[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( 'pingback\_ping\_source\_uri', string $pagelinkedfrom, string $pagelinkedto )](../../hooks/pingback_ping_source_uri)
Filters the pingback source URI.
[do\_action( 'pingback\_post', int $comment\_ID )](../../hooks/pingback_post)
Fires after a post pingback has been sent.
[apply\_filters( 'pre\_remote\_source', string $remote\_source, string $pagelinkedto )](../../hooks/pre_remote_source)
Filters the pingback remote source.
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [url\_to\_postid()](../../functions/url_to_postid) wp-includes/rewrite.php | Examines a URL and try to determine the post ID it represents. |
| [wp\_xmlrpc\_server::pingback\_error()](pingback_error) wp-includes/class-wp-xmlrpc-server.php | Sends a pingback error based on the given error code and message. |
| [wp\_new\_comment()](../../functions/wp_new_comment) wp-includes/comment.php | Adds a new comment to the database. |
| [wp\_safe\_remote\_get()](../../functions/wp_safe_remote_get) wp-includes/http.php | Retrieve the raw response from a safe HTTP request using the GET method. |
| [wp\_remote\_retrieve\_body()](../../functions/wp_remote_retrieve_body) wp-includes/http.php | Retrieve only the body from the raw response. |
| [pings\_open()](../../functions/pings_open) wp-includes/comment-template.php | Determines whether the current post is open for pings. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [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. |
| [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. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::sayHello(): string wp\_xmlrpc\_server::sayHello(): string
======================================
Test XMLRPC API by saying, “Hello!” to client.
string Hello string response.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function sayHello() {
return 'Hello!';
}
```
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_deletePage( array $args ): true|IXR_Error wp\_xmlrpc\_server::wp\_deletePage( array $args ): true|IXR\_Error
==================================================================
Delete page.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intPage ID.
true|[IXR\_Error](../ixr_error) True, if success.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_deletePage( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$page_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.deletePage', $args, $this );
// Get the current page based on the 'page_id' and
// make sure it is a page and not a post.
$actual_page = get_post( $page_id, ARRAY_A );
if ( ! $actual_page || ( 'page' !== $actual_page['post_type'] ) ) {
return new IXR_Error( 404, __( 'Sorry, no such page.' ) );
}
// Make sure the user can delete pages.
if ( ! current_user_can( 'delete_page', $page_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this page.' ) );
}
// Attempt to delete the page.
$result = wp_delete_post( $page_id );
if ( ! $result ) {
return new IXR_Error( 500, __( 'Failed to delete the page.' ) );
}
/**
* Fires after a page has been successfully deleted via XML-RPC.
*
* @since 3.4.0
*
* @param int $page_id ID of the deleted page.
* @param array $args An array of arguments to delete the page.
*/
do_action( 'xmlrpc_call_success_wp_deletePage', $page_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return true;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[do\_action( 'xmlrpc\_call\_success\_wp\_deletePage', int $page\_id, array $args )](../../hooks/xmlrpc_call_success_wp_deletepage)
Fires after a page has been successfully deleted via XML-RPC.
| Uses | Description |
| --- | --- |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::wp_getUsersBlogs( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getUsersBlogs( array $args ): array|IXR\_Error
======================================================================
Retrieve the blogs of the user.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* stringUsername.
* `1`stringPassword.
array|[IXR\_Error](../ixr_error) Array contains:
* `'isAdmin'`
* `'isPrimary'` - whether the blog is the user's primary blog
* `'url'`
* `'blogid'`
* `'blogName'`
* `'xmlrpc'` - url of xmlrpc endpoint
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getUsersBlogs( $args ) {
if ( ! $this->minimum_args( $args, 2 ) ) {
return $this->error;
}
// If this isn't on WPMU then just use blogger_getUsersBlogs().
if ( ! is_multisite() ) {
array_unshift( $args, 1 );
return $this->blogger_getUsersBlogs( $args );
}
$this->escape( $args );
$username = $args[0];
$password = $args[1];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/**
* Fires after the XML-RPC user has been authenticated but before the rest of
* the method logic begins.
*
* All built-in XML-RPC methods use the action xmlrpc_call, with a parameter
* equal to the method's name, e.g., wp.getUsersBlogs, wp.newPost, etc.
*
* @since 2.5.0
* @since 5.7.0 Added the `$args` and `$server` parameters.
*
* @param string $name The method name.
* @param array|string $args The escaped arguments passed to the method.
* @param wp_xmlrpc_server $server The XML-RPC server instance.
*/
do_action( 'xmlrpc_call', 'wp.getUsersBlogs', $args, $this );
$blogs = (array) get_blogs_of_user( $user->ID );
$struct = array();
$primary_blog_id = 0;
$active_blog = get_active_blog_for_user( $user->ID );
if ( $active_blog ) {
$primary_blog_id = (int) $active_blog->blog_id;
}
foreach ( $blogs as $blog ) {
// Don't include blogs that aren't hosted at this site.
if ( get_current_network_id() != $blog->site_id ) {
continue;
}
$blog_id = $blog->userblog_id;
switch_to_blog( $blog_id );
$is_admin = current_user_can( 'manage_options' );
$is_primary = ( (int) $blog_id === $primary_blog_id );
$struct[] = array(
'isAdmin' => $is_admin,
'isPrimary' => $is_primary,
'url' => home_url( '/' ),
'blogid' => (string) $blog_id,
'blogName' => get_option( 'blogname' ),
'xmlrpc' => site_url( 'xmlrpc.php', 'rpc' ),
);
restore_current_blog();
}
return $struct;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [get\_current\_network\_id()](../../functions/get_current_network_id) wp-includes/load.php | Retrieves the current network ID. |
| [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. |
| [get\_blogs\_of\_user()](../../functions/get_blogs_of_user) wp-includes/user.php | Gets the sites a user belongs to. |
| [get\_active\_blog\_for\_user()](../../functions/get_active_blog_for_user) wp-includes/ms-functions.php | Gets one of a user’s active blogs. |
| [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\_xmlrpc\_server::blogger\_getUsersBlogs()](blogger_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Retrieve blogs that user owns. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [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. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_multisite\_getUsersBlogs()](_multisite_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Private function for retrieving a users blogs for multisite setups |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_newPost( array $args ): int|IXR_Error wp\_xmlrpc\_server::wp\_newPost( array $args ): int|IXR\_Error
==============================================================
Create a new post for any registered post type.
`$args` array Required Method arguments. Note: top-level arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`array Content struct for adding a new post. See [wp\_insert\_post()](../../functions/wp_insert_post) for information on additional post fields
+ `post_type`stringPost type. Default `'post'`.
+ `post_status`stringPost status. Default `'draft'`
+ `post_title`stringPost title.
+ `post_author`intPost author ID.
+ `post_excerpt`stringPost excerpt.
+ `post_content`stringPost content.
+ `post_date_gmt`stringPost date in GMT.
+ `post_date`stringPost date.
+ `post_password`stringPost password (20-character limit).
+ `comment_status`stringPost comment enabled status. Accepts `'open'` or `'closed'`.
+ `ping_status`stringPost ping status. Accepts `'open'` or `'closed'`.
+ `sticky`boolWhether the post should be sticky. Automatically false if `$post_status` is `'private'`.
+ `post_thumbnail`intID of an image to use as the post thumbnail/featured image.
+ `custom_fields`arrayArray of meta key/value pairs to add to the post.
+ `terms`arrayAssociative array with taxonomy names as keys and arrays of term IDs as values.
+ `terms_names`arrayAssociative array with taxonomy names as keys and arrays of term names as values.
+ `enclosure`array Array of feed enclosure data to add to post meta.
- `url`stringURL for the feed enclosure.
- `length`intSize in bytes of the enclosure.
- `type`stringMime-type for the enclosure.
} int|[IXR\_Error](../ixr_error) Post ID on success, [IXR\_Error](../ixr_error) instance otherwise.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_newPost( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$content_struct = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
// Convert the date field back to IXR form.
if ( isset( $content_struct['post_date'] ) && ! ( $content_struct['post_date'] instanceof IXR_Date ) ) {
$content_struct['post_date'] = $this->_convert_date( $content_struct['post_date'] );
}
/*
* Ignore the existing GMT date if it is empty or a non-GMT date was supplied in $content_struct,
* since _insert_post() will ignore the non-GMT date if the GMT date is set.
*/
if ( isset( $content_struct['post_date_gmt'] ) && ! ( $content_struct['post_date_gmt'] instanceof IXR_Date ) ) {
if ( '0000-00-00 00:00:00' === $content_struct['post_date_gmt'] || isset( $content_struct['post_date'] ) ) {
unset( $content_struct['post_date_gmt'] );
} else {
$content_struct['post_date_gmt'] = $this->_convert_date( $content_struct['post_date_gmt'] );
}
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.newPost', $args, $this );
unset( $content_struct['ID'] );
return $this->_insert_post( $user, $content_struct );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_insert\_post()](_insert_post) wp-includes/class-wp-xmlrpc-server.php | Helper method for wp\_newPost() and wp\_editPost(), containing shared logic. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [wp\_xmlrpc\_server::\_convert\_date()](_convert_date) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress date string to an [IXR\_Date](../ixr_date) object. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wp_xmlrpc_server::blogger_getTemplate( array $args ): IXR_Error wp\_xmlrpc\_server::blogger\_getTemplate( array $args ): IXR\_Error
===================================================================
This method has been deprecated.
Deprecated.
`$args` array Required Unused. [IXR\_Error](../ixr_error) Error object.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function blogger_getTemplate( $args ) {
return new IXR_Error( 403, __( 'Sorry, this method is not supported.' ) );
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | This method has been deprecated. |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::addTwoNumbers( array $args ): int wp\_xmlrpc\_server::addTwoNumbers( array $args ): int
=====================================================
Test XMLRPC API by adding two numbers for client.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intA number to add.
* `1`intA second number to add.
int Sum of the two given numbers.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function addTwoNumbers( $args ) {
$number1 = $args[0];
$number2 = $args[1];
return $number1 + $number2;
}
```
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::mt_publishPost( array $args ): int|IXR_Error wp\_xmlrpc\_server::mt\_publishPost( array $args ): int|IXR\_Error
==================================================================
Sets a post’s publish status to ‘publish’.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intPost ID.
* `1`stringUsername.
* `2`stringPassword.
int|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mt_publishPost( $args ) {
$this->escape( $args );
$post_ID = (int) $args[0];
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.publishPost', $args, $this );
$postdata = get_post( $post_ID, ARRAY_A );
if ( ! $postdata ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'publish_posts' ) || ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this post.' ) );
}
$postdata['post_status'] = 'publish';
// Retain old categories.
$postdata['post_category'] = wp_get_post_categories( $post_ID );
$this->escape( $postdata );
return wp_update_post( $postdata );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_get\_post\_categories()](../../functions/wp_get_post_categories) wp-includes/post.php | Retrieves the list of categories for a post. |
| [wp\_update\_post()](../../functions/wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::_prepare_term( array|object $term ): array wp\_xmlrpc\_server::\_prepare\_term( array|object $term ): array
================================================================
Prepares term data for return in an XML-RPC object.
`$term` array|object Required The unprepared term data. array The prepared term data.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function _prepare_term( $term ) {
$_term = $term;
if ( ! is_array( $_term ) ) {
$_term = get_object_vars( $_term );
}
// For integers which may be larger than XML-RPC supports ensure we return strings.
$_term['term_id'] = (string) $_term['term_id'];
$_term['term_group'] = (string) $_term['term_group'];
$_term['term_taxonomy_id'] = (string) $_term['term_taxonomy_id'];
$_term['parent'] = (string) $_term['parent'];
// Count we are happy to return as an integer because people really shouldn't use terms that much.
$_term['count'] = (int) $_term['count'];
// Get term meta.
$_term['custom_fields'] = $this->get_term_custom_fields( $_term['term_id'] );
/**
* Filters XML-RPC-prepared data for the given term.
*
* @since 3.4.0
*
* @param array $_term An array of term data.
* @param array|object $term Term object or array.
*/
return apply_filters( 'xmlrpc_prepare_term', $_term, $term );
}
```
[apply\_filters( 'xmlrpc\_prepare\_term', array $\_term, array|object $term )](../../hooks/xmlrpc_prepare_term)
Filters XML-RPC-prepared data for the given term.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::get\_term\_custom\_fields()](get_term_custom_fields) wp-includes/class-wp-xmlrpc-server.php | Retrieve custom fields for a term. |
| [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\_xmlrpc\_server::wp\_getTerm()](wp_getterm) wp-includes/class-wp-xmlrpc-server.php | Retrieve a term. |
| [wp\_xmlrpc\_server::wp\_getTerms()](wp_getterms) wp-includes/class-wp-xmlrpc-server.php | Retrieve all terms for a taxonomy. |
| [wp\_xmlrpc\_server::\_prepare\_post()](_prepare_post) wp-includes/class-wp-xmlrpc-server.php | Prepares post data for return in an XML-RPC object. |
wordpress wp_xmlrpc_server::blogger_newPost( array $args ): int|IXR_Error wp\_xmlrpc\_server::blogger\_newPost( array $args ): int|IXR\_Error
===================================================================
Creates new post.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* stringApp key (unused).
* `1`intBlog ID (unused).
* `2`stringUsername.
* `3`stringPassword.
* `4`stringContent.
* `5`intPublish flag. 0 for draft, 1 for publish.
int|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function blogger_newPost( $args ) {
$this->escape( $args );
$username = $args[2];
$password = $args[3];
$content = $args[4];
$publish = $args[5];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.newPost', $args, $this );
$cap = ( $publish ) ? 'publish_posts' : 'edit_posts';
if ( ! current_user_can( get_post_type_object( 'post' )->cap->create_posts ) || ! current_user_can( $cap ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to post on this site.' ) );
}
$post_status = ( $publish ) ? 'publish' : 'draft';
$post_author = $user->ID;
$post_title = xmlrpc_getposttitle( $content );
$post_category = xmlrpc_getpostcategory( $content );
$post_content = xmlrpc_removepostdata( $content );
$post_date = current_time( 'mysql' );
$post_date_gmt = current_time( 'mysql', 1 );
$post_data = compact( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status' );
$post_ID = wp_insert_post( $post_data );
if ( is_wp_error( $post_ID ) ) {
return new IXR_Error( 500, $post_ID->get_error_message() );
}
if ( ! $post_ID ) {
return new IXR_Error( 500, __( 'Sorry, the post could not be created.' ) );
}
$this->attach_uploads( $post_ID, $post_content );
/**
* Fires after a new post has been successfully created via the XML-RPC Blogger API.
*
* @since 3.4.0
*
* @param int $post_ID ID of the new post.
* @param array $args An array of new post arguments.
*/
do_action( 'xmlrpc_call_success_blogger_newPost', $post_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return $post_ID;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[do\_action( 'xmlrpc\_call\_success\_blogger\_newPost', int $post\_ID, array $args )](../../hooks/xmlrpc_call_success_blogger_newpost)
Fires after a new post has been successfully created via the XML-RPC Blogger API.
| Uses | Description |
| --- | --- |
| [xmlrpc\_getposttitle()](../../functions/xmlrpc_getposttitle) wp-includes/functions.php | Retrieves post title from XMLRPC XML. |
| [xmlrpc\_getpostcategory()](../../functions/xmlrpc_getpostcategory) wp-includes/functions.php | Retrieves the post category or categories from XMLRPC XML. |
| [xmlrpc\_removepostdata()](../../functions/xmlrpc_removepostdata) wp-includes/functions.php | XMLRPC XML content without title and category elements. |
| [current\_time()](../../functions/current_time) wp-includes/functions.php | Retrieves the current time based on specified type. |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [wp\_xmlrpc\_server::attach\_uploads()](attach_uploads) wp-includes/class-wp-xmlrpc-server.php | Attach upload to a post. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::mt_getPostCategories( array $args ): array|IXR_Error wp\_xmlrpc\_server::mt\_getPostCategories( array $args ): array|IXR\_Error
==========================================================================
Retrieve post categories.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intPost ID.
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mt_getPostCategories( $args ) {
$this->escape( $args );
$post_ID = (int) $args[0];
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! get_post( $post_ID ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.getPostCategories', $args, $this );
$categories = array();
$catids = wp_get_post_categories( (int) $post_ID );
// First listed category will be the primary category.
$isPrimary = true;
foreach ( $catids as $catid ) {
$categories[] = array(
'categoryName' => get_cat_name( $catid ),
'categoryId' => (string) $catid,
'isPrimary' => $isPrimary,
);
$isPrimary = false;
}
return $categories;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [get\_cat\_name()](../../functions/get_cat_name) wp-includes/category.php | Retrieves the name of a category from its ID. |
| [wp\_get\_post\_categories()](../../functions/wp_get_post_categories) wp-includes/post.php | Retrieves the list of categories for a post. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getComments( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getComments( array $args ): array|IXR\_Error
====================================================================
Retrieve comments.
Besides the common blog\_id (unused), username, and password arguments, it takes a filter array as last argument.
Accepted ‘filter’ keys are ‘status’, ‘post\_id’, ‘offset’, and ‘number’.
The defaults are as follows:
* ‘status’ – Default is ”. Filter by status (e.g., ‘approve’, ‘hold’)
* ‘post\_id’ – Default is ”. The post where the comment is posted. Empty string shows all comments.
* ‘number’ – Default is 10. Total number of media items to retrieve.
* ‘offset’ – Default is 0. See [WP\_Query::query()](../wp_query/query) for more.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayOptional. Query arguments.
array|[IXR\_Error](../ixr_error) Contains a collection of comments. See [wp\_xmlrpc\_server::wp\_getComment()](wp_getcomment) for a description of each item contents
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getComments( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$struct = isset( $args[3] ) ? $args[3] : array();
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getComments', $args, $this );
if ( isset( $struct['status'] ) ) {
$status = $struct['status'];
} else {
$status = '';
}
if ( ! current_user_can( 'moderate_comments' ) && 'approve' !== $status ) {
return new IXR_Error( 401, __( 'Invalid comment status.' ) );
}
$post_id = '';
if ( isset( $struct['post_id'] ) ) {
$post_id = absint( $struct['post_id'] );
}
$post_type = '';
if ( isset( $struct['post_type'] ) ) {
$post_type_object = get_post_type_object( $struct['post_type'] );
if ( ! $post_type_object || ! post_type_supports( $post_type_object->name, 'comments' ) ) {
return new IXR_Error( 404, __( 'Invalid post type.' ) );
}
$post_type = $struct['post_type'];
}
$offset = 0;
if ( isset( $struct['offset'] ) ) {
$offset = absint( $struct['offset'] );
}
$number = 10;
if ( isset( $struct['number'] ) ) {
$number = absint( $struct['number'] );
}
$comments = get_comments(
array(
'status' => $status,
'post_id' => $post_id,
'offset' => $offset,
'number' => $number,
'post_type' => $post_type,
)
);
$comments_struct = array();
if ( is_array( $comments ) ) {
foreach ( $comments as $comment ) {
$comments_struct[] = $this->_prepare_comment( $comment );
}
}
return $comments_struct;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [post\_type\_supports()](../../functions/post_type_supports) wp-includes/post.php | Checks a post type’s support for a given feature. |
| [wp\_xmlrpc\_server::\_prepare\_comment()](_prepare_comment) wp-includes/class-wp-xmlrpc-server.php | Prepares comment data for return in an XML-RPC object. |
| [get\_comments()](../../functions/get_comments) wp-includes/comment.php | Retrieves a list of comments. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wp_xmlrpc_server::mt_supportedMethods(): array wp\_xmlrpc\_server::mt\_supportedMethods(): array
=================================================
Retrieve an array of methods supported by this server.
array
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mt_supportedMethods() {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.supportedMethods', array(), $this );
return array_keys( $this->methods );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| 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 |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::blogger_editPost( array $args ): true|IXR_Error wp\_xmlrpc\_server::blogger\_editPost( array $args ): true|IXR\_Error
=====================================================================
Edit a post.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`intPost ID.
* `2`stringUsername.
* `3`stringPassword.
* `4`stringContent
* `5`intPublish flag. 0 for draft, 1 for publish.
true|[IXR\_Error](../ixr_error) true when done.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function blogger_editPost( $args ) {
$this->escape( $args );
$post_ID = (int) $args[1];
$username = $args[2];
$password = $args[3];
$content = $args[4];
$publish = $args[5];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.editPost', $args, $this );
$actual_post = get_post( $post_ID, ARRAY_A );
if ( ! $actual_post || 'post' !== $actual_post['post_type'] ) {
return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
}
$this->escape( $actual_post );
if ( ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
if ( 'publish' === $actual_post['post_status'] && ! current_user_can( 'publish_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this post.' ) );
}
$postdata = array();
$postdata['ID'] = $actual_post['ID'];
$postdata['post_content'] = xmlrpc_removepostdata( $content );
$postdata['post_title'] = xmlrpc_getposttitle( $content );
$postdata['post_category'] = xmlrpc_getpostcategory( $content );
$postdata['post_status'] = $actual_post['post_status'];
$postdata['post_excerpt'] = $actual_post['post_excerpt'];
$postdata['post_status'] = $publish ? 'publish' : 'draft';
$result = wp_update_post( $postdata );
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, the post could not be updated.' ) );
}
$this->attach_uploads( $actual_post['ID'], $postdata['post_content'] );
/**
* Fires after a post has been successfully updated via the XML-RPC Blogger API.
*
* @since 3.4.0
*
* @param int $post_ID ID of the updated post.
* @param array $args An array of arguments for the post to edit.
*/
do_action( 'xmlrpc_call_success_blogger_editPost', $post_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return true;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[do\_action( 'xmlrpc\_call\_success\_blogger\_editPost', int $post\_ID, array $args )](../../hooks/xmlrpc_call_success_blogger_editpost)
Fires after a post has been successfully updated via the XML-RPC Blogger API.
| Uses | Description |
| --- | --- |
| [xmlrpc\_removepostdata()](../../functions/xmlrpc_removepostdata) wp-includes/functions.php | XMLRPC XML content without title and category elements. |
| [xmlrpc\_getposttitle()](../../functions/xmlrpc_getposttitle) wp-includes/functions.php | Retrieves post title from XMLRPC XML. |
| [xmlrpc\_getpostcategory()](../../functions/xmlrpc_getpostcategory) wp-includes/functions.php | Retrieves the post category or categories from XMLRPC XML. |
| [wp\_update\_post()](../../functions/wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [wp\_xmlrpc\_server::attach\_uploads()](attach_uploads) wp-includes/class-wp-xmlrpc-server.php | Attach upload to a post. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getUsers( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getUsers( array $args ): array|IXR\_Error
=================================================================
Retrieve users.
The optional $filter parameter modifies the query used to retrieve users.
Accepted keys are ‘number’ (default: 50), ‘offset’ (default: 0), ‘role’, ‘who’, ‘orderby’, and ‘order’.
The optional $fields parameter specifies what fields will be included in the response array.
* [wp\_getUser()](../../functions/wp_getuser): for more on $fields and return values
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayOptional. Arguments for the user query.
* `4`arrayOptional. Fields to return.
array|[IXR\_Error](../ixr_error) users data
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getUsers( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$filter = isset( $args[3] ) ? $args[3] : array();
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
$fields = apply_filters( 'xmlrpc_default_user_fields', array( 'all' ), 'wp.getUsers' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getUsers', $args, $this );
if ( ! current_user_can( 'list_users' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to list users.' ) );
}
$query = array( 'fields' => 'all_with_meta' );
$query['number'] = ( isset( $filter['number'] ) ) ? absint( $filter['number'] ) : 50;
$query['offset'] = ( isset( $filter['offset'] ) ) ? absint( $filter['offset'] ) : 0;
if ( isset( $filter['orderby'] ) ) {
$query['orderby'] = $filter['orderby'];
if ( isset( $filter['order'] ) ) {
$query['order'] = $filter['order'];
}
}
if ( isset( $filter['role'] ) ) {
if ( get_role( $filter['role'] ) === null ) {
return new IXR_Error( 403, __( 'Invalid role.' ) );
}
$query['role'] = $filter['role'];
}
if ( isset( $filter['who'] ) ) {
$query['who'] = $filter['who'];
}
$users = get_users( $query );
$_users = array();
foreach ( $users as $user_data ) {
if ( current_user_can( 'edit_user', $user_data->ID ) ) {
$_users[] = $this->_prepare_user( $user_data, $fields );
}
}
return $_users;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[apply\_filters( 'xmlrpc\_default\_user\_fields', array $fields, string $method )](../../hooks/xmlrpc_default_user_fields)
Filters the default user query fields used by the given XML-RPC method.
| Uses | Description |
| --- | --- |
| [get\_role()](../../functions/get_role) wp-includes/capabilities.php | Retrieves role object. |
| [get\_users()](../../functions/get_users) wp-includes/user.php | Retrieves list of users matching criteria. |
| [wp\_xmlrpc\_server::\_prepare\_user()](_prepare_user) wp-includes/class-wp-xmlrpc-server.php | Prepares user data for return in an XML-RPC object. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [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. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
wordpress wp_xmlrpc_server::blogger_getPost( array $args ): array|IXR_Error wp\_xmlrpc\_server::blogger\_getPost( array $args ): array|IXR\_Error
=====================================================================
Retrieve post.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`intPost ID.
* `2`stringUsername.
* `3`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function blogger_getPost( $args ) {
$this->escape( $args );
$post_ID = (int) $args[1];
$username = $args[2];
$password = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
$post_data = get_post( $post_ID, ARRAY_A );
if ( ! $post_data ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.getPost', $args, $this );
$categories = implode( ',', wp_get_post_categories( $post_ID ) );
$content = '<title>' . wp_unslash( $post_data['post_title'] ) . '</title>';
$content .= '<category>' . $categories . '</category>';
$content .= wp_unslash( $post_data['post_content'] );
$struct = array(
'userid' => $post_data['post_author'],
'dateCreated' => $this->_convert_date( $post_data['post_date'] ),
'content' => $content,
'postid' => (string) $post_data['ID'],
);
return $struct;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_get\_post\_categories()](../../functions/wp_get_post_categories) wp-includes/post.php | Retrieves the list of categories for a post. |
| [wp\_xmlrpc\_server::\_convert\_date()](_convert_date) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress date string to an [IXR\_Date](../ixr_date) object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::_convert_date( string $date ): IXR_Date wp\_xmlrpc\_server::\_convert\_date( string $date ): IXR\_Date
==============================================================
Convert a WordPress date string to an [IXR\_Date](../ixr_date) object.
`$date` string Required Date string to convert. [IXR\_Date](../ixr_date) [IXR\_Date](../ixr_date) object.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function _convert_date( $date ) {
if ( '0000-00-00 00:00:00' === $date ) {
return new IXR_Date( '00000000T00:00:00Z' );
}
return new IXR_Date( mysql2date( 'Ymd\TH:i:s', $date, false ) );
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Date::\_\_construct()](../ixr_date/__construct) wp-includes/IXR/class-IXR-date.php | PHP5 constructor. |
| [mysql2date()](../../functions/mysql2date) wp-includes/functions.php | Converts given MySQL date string into a different format. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::mw\_getPost()](mw_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve post. |
| [wp\_xmlrpc\_server::mw\_getRecentPosts()](mw_getrecentposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve list of recent posts. |
| [wp\_xmlrpc\_server::mt\_getRecentPostTitles()](mt_getrecentposttitles) wp-includes/class-wp-xmlrpc-server.php | Retrieve the post titles of recent posts. |
| [wp\_xmlrpc\_server::blogger\_getPost()](blogger_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve post. |
| [wp\_xmlrpc\_server::blogger\_getRecentPosts()](blogger_getrecentposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve list of recent posts. |
| [wp\_xmlrpc\_server::wp\_getPageList()](wp_getpagelist) wp-includes/class-wp-xmlrpc-server.php | Retrieve page list. |
| [wp\_xmlrpc\_server::\_prepare\_page()](_prepare_page) wp-includes/class-wp-xmlrpc-server.php | Prepares page data for return in an XML-RPC object. |
| [wp\_xmlrpc\_server::\_prepare\_user()](_prepare_user) wp-includes/class-wp-xmlrpc-server.php | Prepares user data for return in an XML-RPC object. |
| [wp\_xmlrpc\_server::wp\_newPost()](wp_newpost) wp-includes/class-wp-xmlrpc-server.php | Create a new post for any registered post type. |
| [wp\_xmlrpc\_server::wp\_editPost()](wp_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post for any registered post type. |
| [wp\_xmlrpc\_server::\_convert\_date\_gmt()](_convert_date_gmt) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress GMT date string to an [IXR\_Date](../ixr_date) object. |
| [wp\_xmlrpc\_server::\_prepare\_post()](_prepare_post) wp-includes/class-wp-xmlrpc-server.php | Prepares post data for return in an XML-RPC object. |
wordpress wp_xmlrpc_server::wp_getUser( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getUser( array $args ): array|IXR\_Error
================================================================
Retrieve a user.
The optional $fields parameter specifies what fields will be included in the response array. This should be a list of field names. ‘user\_id’ will always be included in the response regardless of the value of $fields.
Instead of, or in addition to, individual field names, conceptual group names can be used to specify multiple fields. The available conceptual groups are ‘basic’ and ‘all’.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intUser ID.
* `4`arrayOptional. Array of fields to return.
array|[IXR\_Error](../ixr_error) Array contains (based on $fields parameter):
* `'user_id'`
* `'username'`
* `'first_name'`
* `'last_name'`
* `'registered'`
* `'bio'`
* `'email'`
* `'nickname'`
* `'nicename'`
* `'url'`
* `'display_name'`
* `'roles'`
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getUser( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user_id = (int) $args[3];
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/**
* Filters the default user query fields used by the given XML-RPC method.
*
* @since 3.5.0
*
* @param array $fields User query fields for given method. Default 'all'.
* @param string $method The method name.
*/
$fields = apply_filters( 'xmlrpc_default_user_fields', array( 'all' ), 'wp.getUser' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getUser', $args, $this );
if ( ! current_user_can( 'edit_user', $user_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this user.' ) );
}
$user_data = get_userdata( $user_id );
if ( ! $user_data ) {
return new IXR_Error( 404, __( 'Invalid user ID.' ) );
}
return $this->_prepare_user( $user_data, $fields );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[apply\_filters( 'xmlrpc\_default\_user\_fields', array $fields, string $method )](../../hooks/xmlrpc_default_user_fields)
Filters the default user query fields used by the given XML-RPC method.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_prepare\_user()](_prepare_user) wp-includes/class-wp-xmlrpc-server.php | Prepares user data for return in an XML-RPC object. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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\_userdata()](../../functions/get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
wordpress wp_xmlrpc_server::login( string $username, string $password ): WP_User|false wp\_xmlrpc\_server::login( string $username, string $password ): WP\_User|false
===============================================================================
Log user in.
`$username` string Required User's username. `$password` string Required User's password. [WP\_User](../wp_user)|false [WP\_User](../wp_user) object if authentication passed, false otherwise
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function login( $username, $password ) {
if ( ! $this->is_enabled ) {
$this->error = new IXR_Error( 405, sprintf( __( 'XML-RPC services are disabled on this site.' ) ) );
return false;
}
if ( $this->auth_failed ) {
$user = new WP_Error( 'login_prevented' );
} else {
$user = wp_authenticate( $username, $password );
}
if ( is_wp_error( $user ) ) {
$this->error = new IXR_Error( 403, __( 'Incorrect username or password.' ) );
// Flag that authentication has failed once on this wp_xmlrpc_server instance.
$this->auth_failed = true;
/**
* Filters the XML-RPC user login error message.
*
* @since 3.5.0
*
* @param IXR_Error $error The XML-RPC error message.
* @param WP_Error $user WP_Error object.
*/
$this->error = apply_filters( 'xmlrpc_login_error', $this->error, $user );
return false;
}
wp_set_current_user( $user->ID );
return $user;
}
```
[apply\_filters( 'xmlrpc\_login\_error', IXR\_Error $error, WP\_Error $user )](../../hooks/xmlrpc_login_error)
Filters the XML-RPC user login error message.
| Uses | Description |
| --- | --- |
| [wp\_authenticate()](../../functions/wp_authenticate) wp-includes/pluggable.php | Authenticates a user, confirming the login credentials are valid. |
| [wp\_set\_current\_user()](../../functions/wp_set_current_user) wp-includes/pluggable.php | Changes the current user by ID or name. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [\_\_()](../../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\_xmlrpc\_server::mt\_getPostCategories()](mt_getpostcategories) wp-includes/class-wp-xmlrpc-server.php | Retrieve post categories. |
| [wp\_xmlrpc\_server::mt\_setPostCategories()](mt_setpostcategories) wp-includes/class-wp-xmlrpc-server.php | Sets categories for a post. |
| [wp\_xmlrpc\_server::mt\_publishPost()](mt_publishpost) wp-includes/class-wp-xmlrpc-server.php | Sets a post’s publish status to ‘publish’. |
| [wp\_xmlrpc\_server::mw\_editPost()](mw_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post. |
| [wp\_xmlrpc\_server::mw\_getPost()](mw_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve post. |
| [wp\_xmlrpc\_server::mw\_getRecentPosts()](mw_getrecentposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve list of recent posts. |
| [wp\_xmlrpc\_server::mw\_getCategories()](mw_getcategories) wp-includes/class-wp-xmlrpc-server.php | Retrieve the list of categories on a given blog. |
| [wp\_xmlrpc\_server::mw\_newMediaObject()](mw_newmediaobject) wp-includes/class-wp-xmlrpc-server.php | Uploads a file, following your settings. |
| [wp\_xmlrpc\_server::mt\_getRecentPostTitles()](mt_getrecentposttitles) wp-includes/class-wp-xmlrpc-server.php | Retrieve the post titles of recent posts. |
| [wp\_xmlrpc\_server::mt\_getCategoryList()](mt_getcategorylist) wp-includes/class-wp-xmlrpc-server.php | Retrieve list of all categories on blog. |
| [wp\_xmlrpc\_server::blogger\_getUserInfo()](blogger_getuserinfo) wp-includes/class-wp-xmlrpc-server.php | Retrieve user’s data. |
| [wp\_xmlrpc\_server::blogger\_getPost()](blogger_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve post. |
| [wp\_xmlrpc\_server::blogger\_getRecentPosts()](blogger_getrecentposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve list of recent posts. |
| [wp\_xmlrpc\_server::blogger\_newPost()](blogger_newpost) wp-includes/class-wp-xmlrpc-server.php | Creates new post. |
| [wp\_xmlrpc\_server::blogger\_editPost()](blogger_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post. |
| [wp\_xmlrpc\_server::blogger\_deletePost()](blogger_deletepost) wp-includes/class-wp-xmlrpc-server.php | Remove a post. |
| [wp\_xmlrpc\_server::mw\_newPost()](mw_newpost) wp-includes/class-wp-xmlrpc-server.php | Create a new post. |
| [wp\_xmlrpc\_server::wp\_getOptions()](wp_getoptions) wp-includes/class-wp-xmlrpc-server.php | Retrieve blog options. |
| [wp\_xmlrpc\_server::wp\_setOptions()](wp_setoptions) wp-includes/class-wp-xmlrpc-server.php | Update blog options. |
| [wp\_xmlrpc\_server::wp\_getMediaItem()](wp_getmediaitem) wp-includes/class-wp-xmlrpc-server.php | Retrieve a media item by ID |
| [wp\_xmlrpc\_server::wp\_getMediaLibrary()](wp_getmedialibrary) wp-includes/class-wp-xmlrpc-server.php | Retrieves a collection of media library items (or attachments) |
| [wp\_xmlrpc\_server::wp\_getPostFormats()](wp_getpostformats) wp-includes/class-wp-xmlrpc-server.php | Retrieves a list of post formats used by the site. |
| [wp\_xmlrpc\_server::wp\_getPostType()](wp_getposttype) wp-includes/class-wp-xmlrpc-server.php | Retrieves a post type |
| [wp\_xmlrpc\_server::wp\_getPostTypes()](wp_getposttypes) wp-includes/class-wp-xmlrpc-server.php | Retrieves a post types |
| [wp\_xmlrpc\_server::wp\_getRevisions()](wp_getrevisions) wp-includes/class-wp-xmlrpc-server.php | Retrieve revisions for a specific post. |
| [wp\_xmlrpc\_server::wp\_restoreRevision()](wp_restorerevision) wp-includes/class-wp-xmlrpc-server.php | Restore a post revision |
| [wp\_xmlrpc\_server::blogger\_getUsersBlogs()](blogger_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Retrieve blogs that user owns. |
| [wp\_xmlrpc\_server::wp\_getComments()](wp_getcomments) wp-includes/class-wp-xmlrpc-server.php | Retrieve comments. |
| [wp\_xmlrpc\_server::wp\_deleteComment()](wp_deletecomment) wp-includes/class-wp-xmlrpc-server.php | Delete a comment. |
| [wp\_xmlrpc\_server::wp\_editComment()](wp_editcomment) wp-includes/class-wp-xmlrpc-server.php | Edit comment. |
| [wp\_xmlrpc\_server::wp\_newComment()](wp_newcomment) wp-includes/class-wp-xmlrpc-server.php | Create new comment. |
| [wp\_xmlrpc\_server::wp\_getCommentStatusList()](wp_getcommentstatuslist) wp-includes/class-wp-xmlrpc-server.php | Retrieve all of the comment status. |
| [wp\_xmlrpc\_server::wp\_getCommentCount()](wp_getcommentcount) wp-includes/class-wp-xmlrpc-server.php | Retrieve comment count. |
| [wp\_xmlrpc\_server::wp\_getPostStatusList()](wp_getpoststatuslist) wp-includes/class-wp-xmlrpc-server.php | Retrieve post statuses. |
| [wp\_xmlrpc\_server::wp\_getPageStatusList()](wp_getpagestatuslist) wp-includes/class-wp-xmlrpc-server.php | Retrieve page statuses. |
| [wp\_xmlrpc\_server::wp\_getPageTemplates()](wp_getpagetemplates) wp-includes/class-wp-xmlrpc-server.php | Retrieve page templates. |
| [wp\_xmlrpc\_server::wp\_getPages()](wp_getpages) wp-includes/class-wp-xmlrpc-server.php | Retrieve Pages. |
| [wp\_xmlrpc\_server::wp\_newPage()](wp_newpage) wp-includes/class-wp-xmlrpc-server.php | Create new page. |
| [wp\_xmlrpc\_server::wp\_deletePage()](wp_deletepage) wp-includes/class-wp-xmlrpc-server.php | Delete page. |
| [wp\_xmlrpc\_server::wp\_editPage()](wp_editpage) wp-includes/class-wp-xmlrpc-server.php | Edit page. |
| [wp\_xmlrpc\_server::wp\_getPageList()](wp_getpagelist) wp-includes/class-wp-xmlrpc-server.php | Retrieve page list. |
| [wp\_xmlrpc\_server::wp\_getAuthors()](wp_getauthors) wp-includes/class-wp-xmlrpc-server.php | Retrieve authors list. |
| [wp\_xmlrpc\_server::wp\_getTags()](wp_gettags) wp-includes/class-wp-xmlrpc-server.php | Get list of all tags |
| [wp\_xmlrpc\_server::wp\_newCategory()](wp_newcategory) wp-includes/class-wp-xmlrpc-server.php | Create new category. |
| [wp\_xmlrpc\_server::wp\_deleteCategory()](wp_deletecategory) wp-includes/class-wp-xmlrpc-server.php | Remove category. |
| [wp\_xmlrpc\_server::wp\_suggestCategories()](wp_suggestcategories) wp-includes/class-wp-xmlrpc-server.php | Retrieve category list. |
| [wp\_xmlrpc\_server::wp\_getComment()](wp_getcomment) wp-includes/class-wp-xmlrpc-server.php | Retrieve comment. |
| [wp\_xmlrpc\_server::wp\_getPosts()](wp_getposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve posts. |
| [wp\_xmlrpc\_server::wp\_newTerm()](wp_newterm) wp-includes/class-wp-xmlrpc-server.php | Create a new term. |
| [wp\_xmlrpc\_server::wp\_editTerm()](wp_editterm) wp-includes/class-wp-xmlrpc-server.php | Edit a term. |
| [wp\_xmlrpc\_server::wp\_deleteTerm()](wp_deleteterm) wp-includes/class-wp-xmlrpc-server.php | Delete a term. |
| [wp\_xmlrpc\_server::wp\_getTerm()](wp_getterm) wp-includes/class-wp-xmlrpc-server.php | Retrieve a term. |
| [wp\_xmlrpc\_server::wp\_getTerms()](wp_getterms) wp-includes/class-wp-xmlrpc-server.php | Retrieve all terms for a taxonomy. |
| [wp\_xmlrpc\_server::wp\_getTaxonomy()](wp_gettaxonomy) wp-includes/class-wp-xmlrpc-server.php | Retrieve a taxonomy. |
| [wp\_xmlrpc\_server::wp\_getTaxonomies()](wp_gettaxonomies) wp-includes/class-wp-xmlrpc-server.php | Retrieve all taxonomies. |
| [wp\_xmlrpc\_server::wp\_getUser()](wp_getuser) wp-includes/class-wp-xmlrpc-server.php | Retrieve a user. |
| [wp\_xmlrpc\_server::wp\_getUsers()](wp_getusers) wp-includes/class-wp-xmlrpc-server.php | Retrieve users. |
| [wp\_xmlrpc\_server::wp\_getProfile()](wp_getprofile) wp-includes/class-wp-xmlrpc-server.php | Retrieve information about the requesting user. |
| [wp\_xmlrpc\_server::wp\_editProfile()](wp_editprofile) wp-includes/class-wp-xmlrpc-server.php | Edit user’s profile. |
| [wp\_xmlrpc\_server::wp\_getPage()](wp_getpage) wp-includes/class-wp-xmlrpc-server.php | Retrieve page. |
| [wp\_xmlrpc\_server::wp\_newPost()](wp_newpost) wp-includes/class-wp-xmlrpc-server.php | Create a new post for any registered post type. |
| [wp\_xmlrpc\_server::wp\_editPost()](wp_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post for any registered post type. |
| [wp\_xmlrpc\_server::wp\_deletePost()](wp_deletepost) wp-includes/class-wp-xmlrpc-server.php | Delete a post for any registered post type. |
| [wp\_xmlrpc\_server::wp\_getPost()](wp_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve a post. |
| [wp\_xmlrpc\_server::wp\_getUsersBlogs()](wp_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Retrieve the blogs of the user. |
| [wp\_xmlrpc\_server::login\_pass\_ok()](login_pass_ok) wp-includes/class-wp-xmlrpc-server.php | Check user’s credentials. Deprecated. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress wp_xmlrpc_server::__call( string $name, array $arguments ): array|IXR_Error|false wp\_xmlrpc\_server::\_\_call( string $name, array $arguments ): array|IXR\_Error|false
======================================================================================
Make private/protected methods readable for backward compatibility.
`$name` string Required Method to call. `$arguments` array Required Arguments to pass when calling. array|[IXR\_Error](../ixr_error)|false Return value of the callback, false otherwise.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function __call( $name, $arguments ) {
if ( '_multisite_getUsersBlogs' === $name ) {
return $this->_multisite_getUsersBlogs( ...$arguments );
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_multisite\_getUsersBlogs()](_multisite_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Private function for retrieving a users blogs for multisite setups |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress wp_xmlrpc_server::_prepare_media_item( WP_Post $media_item, string $thumbnail_size = 'thumbnail' ): array wp\_xmlrpc\_server::\_prepare\_media\_item( WP\_Post $media\_item, string $thumbnail\_size = 'thumbnail' ): array
=================================================================================================================
Prepares media item data for return in an XML-RPC object.
`$media_item` [WP\_Post](../wp_post) Required The unprepared media item data. `$thumbnail_size` string Optional The image size to use for the thumbnail URL. Default: `'thumbnail'`
array The prepared media item data.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function _prepare_media_item( $media_item, $thumbnail_size = 'thumbnail' ) {
$_media_item = array(
'attachment_id' => (string) $media_item->ID,
'date_created_gmt' => $this->_convert_date_gmt( $media_item->post_date_gmt, $media_item->post_date ),
'parent' => $media_item->post_parent,
'link' => wp_get_attachment_url( $media_item->ID ),
'title' => $media_item->post_title,
'caption' => $media_item->post_excerpt,
'description' => $media_item->post_content,
'metadata' => wp_get_attachment_metadata( $media_item->ID ),
'type' => $media_item->post_mime_type,
);
$thumbnail_src = image_downsize( $media_item->ID, $thumbnail_size );
if ( $thumbnail_src ) {
$_media_item['thumbnail'] = $thumbnail_src[0];
} else {
$_media_item['thumbnail'] = $_media_item['link'];
}
/**
* Filters XML-RPC-prepared data for the given media item.
*
* @since 3.4.0
*
* @param array $_media_item An array of media item data.
* @param WP_Post $media_item Media item object.
* @param string $thumbnail_size Image size.
*/
return apply_filters( 'xmlrpc_prepare_media_item', $_media_item, $media_item, $thumbnail_size );
}
```
[apply\_filters( 'xmlrpc\_prepare\_media\_item', array $\_media\_item, WP\_Post $media\_item, string $thumbnail\_size )](../../hooks/xmlrpc_prepare_media_item)
Filters XML-RPC-prepared data for the given media item.
| Uses | Description |
| --- | --- |
| [wp\_get\_attachment\_url()](../../functions/wp_get_attachment_url) wp-includes/post.php | Retrieves the URL for an attachment. |
| [image\_downsize()](../../functions/image_downsize) wp-includes/media.php | Scales an image to fit a particular size (such as ‘thumb’ or ‘medium’). |
| [wp\_get\_attachment\_metadata()](../../functions/wp_get_attachment_metadata) wp-includes/post.php | Retrieves attachment metadata for attachment ID. |
| [wp\_xmlrpc\_server::\_convert\_date\_gmt()](_convert_date_gmt) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress GMT date string to an [IXR\_Date](../ixr_date) object. |
| [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\_xmlrpc\_server::mw\_newMediaObject()](mw_newmediaobject) wp-includes/class-wp-xmlrpc-server.php | Uploads a file, following your settings. |
| [wp\_xmlrpc\_server::wp\_getMediaItem()](wp_getmediaitem) wp-includes/class-wp-xmlrpc-server.php | Retrieve a media item by ID |
| [wp\_xmlrpc\_server::wp\_getMediaLibrary()](wp_getmedialibrary) wp-includes/class-wp-xmlrpc-server.php | Retrieves a collection of media library items (or attachments) |
| [wp\_xmlrpc\_server::\_prepare\_post()](_prepare_post) wp-includes/class-wp-xmlrpc-server.php | Prepares post data for return in an XML-RPC object. |
| programming_docs |
wordpress wp_xmlrpc_server::wp_suggestCategories( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_suggestCategories( array $args ): array|IXR\_Error
==========================================================================
Retrieve category list.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayCategory
* `4`intMax number of results.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_suggestCategories( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$category = $args[3];
$max_results = (int) $args[4];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view categories.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.suggestCategories', $args, $this );
$category_suggestions = array();
$args = array(
'get' => 'all',
'number' => $max_results,
'name__like' => $category,
);
foreach ( (array) get_categories( $args ) as $cat ) {
$category_suggestions[] = array(
'category_id' => $cat->term_id,
'category_name' => $cat->name,
);
}
return $category_suggestions;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [get\_categories()](../../functions/get_categories) wp-includes/category.php | Retrieves a list of category objects. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getTaxonomies( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getTaxonomies( array $args ): array|IXR\_Error
======================================================================
Retrieve all taxonomies.
* [get\_taxonomies()](../../functions/get_taxonomies)
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayOptional. An array of arguments for retrieving taxonomies.
* `4`arrayOptional. The subset of taxonomy fields to return.
array|[IXR\_Error](../ixr_error) An associative array of taxonomy data with returned fields determined by `$fields`, or an [IXR\_Error](../ixr_error) instance on failure.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getTaxonomies( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$filter = isset( $args[3] ) ? $args[3] : array( 'public' => true );
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
$fields = apply_filters( 'xmlrpc_default_taxonomy_fields', array( 'labels', 'cap', 'object_type' ), 'wp.getTaxonomies' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getTaxonomies', $args, $this );
$taxonomies = get_taxonomies( $filter, 'objects' );
// Holds all the taxonomy data.
$struct = array();
foreach ( $taxonomies as $taxonomy ) {
// Capability check for post types.
if ( ! current_user_can( $taxonomy->cap->assign_terms ) ) {
continue;
}
$struct[] = $this->_prepare_taxonomy( $taxonomy, $fields );
}
return $struct;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[apply\_filters( 'xmlrpc\_default\_taxonomy\_fields', array $fields, string $method )](../../hooks/xmlrpc_default_taxonomy_fields)
Filters the taxonomy query fields used by the given XML-RPC method.
| Uses | Description |
| --- | --- |
| [get\_taxonomies()](../../functions/get_taxonomies) wp-includes/taxonomy.php | Retrieves a list of registered taxonomy names or objects. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [wp\_xmlrpc\_server::\_prepare\_taxonomy()](_prepare_taxonomy) wp-includes/class-wp-xmlrpc-server.php | Prepares taxonomy data for return in an XML-RPC object. |
| [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. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getOptions( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getOptions( array $args ): array|IXR\_Error
===================================================================
Retrieve blog options.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayOptional. Options.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getOptions( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$options = isset( $args[3] ) ? (array) $args[3] : array();
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
// If no specific options where asked for, return all of them.
if ( count( $options ) == 0 ) {
$options = array_keys( $this->blog_options );
}
return $this->_getOptions( $options );
}
```
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_getOptions()](_getoptions) wp-includes/class-wp-xmlrpc-server.php | Retrieve blog options value from list. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress wp_xmlrpc_server::_insert_post( WP_User $user, array|IXR_Error $content_struct ): IXR_Error|string wp\_xmlrpc\_server::\_insert\_post( WP\_User $user, array|IXR\_Error $content\_struct ): IXR\_Error|string
==========================================================================================================
Helper method for wp\_newPost() and wp\_editPost(), containing shared logic.
* [wp\_insert\_post()](../../functions/wp_insert_post)
`$user` [WP\_User](../wp_user) Required The post author if post\_author isn't set in $content\_struct. `$content_struct` array|[IXR\_Error](../ixr_error) Required Post data to insert. [IXR\_Error](../ixr_error)|string
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function _insert_post( $user, $content_struct ) {
$defaults = array(
'post_status' => 'draft',
'post_type' => 'post',
'post_author' => 0,
'post_password' => '',
'post_excerpt' => '',
'post_content' => '',
'post_title' => '',
'post_date' => '',
'post_date_gmt' => '',
'post_format' => null,
'post_name' => null,
'post_thumbnail' => null,
'post_parent' => 0,
'ping_status' => '',
'comment_status' => '',
'custom_fields' => null,
'terms_names' => null,
'terms' => null,
'sticky' => null,
'enclosure' => null,
'ID' => null,
);
$post_data = wp_parse_args( array_intersect_key( $content_struct, $defaults ), $defaults );
$post_type = get_post_type_object( $post_data['post_type'] );
if ( ! $post_type ) {
return new IXR_Error( 403, __( 'Invalid post type.' ) );
}
$update = ! empty( $post_data['ID'] );
if ( $update ) {
if ( ! get_post( $post_data['ID'] ) ) {
return new IXR_Error( 401, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_data['ID'] ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
if ( get_post_type( $post_data['ID'] ) !== $post_data['post_type'] ) {
return new IXR_Error( 401, __( 'The post type may not be changed.' ) );
}
} else {
if ( ! current_user_can( $post_type->cap->create_posts ) || ! current_user_can( $post_type->cap->edit_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to post on this site.' ) );
}
}
switch ( $post_data['post_status'] ) {
case 'draft':
case 'pending':
break;
case 'private':
if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to create private posts in this post type.' ) );
}
break;
case 'publish':
case 'future':
if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish posts in this post type.' ) );
}
break;
default:
if ( ! get_post_status_object( $post_data['post_status'] ) ) {
$post_data['post_status'] = 'draft';
}
break;
}
if ( ! empty( $post_data['post_password'] ) && ! current_user_can( $post_type->cap->publish_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to create password protected posts in this post type.' ) );
}
$post_data['post_author'] = absint( $post_data['post_author'] );
if ( ! empty( $post_data['post_author'] ) && $post_data['post_author'] != $user->ID ) {
if ( ! current_user_can( $post_type->cap->edit_others_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to create posts as this user.' ) );
}
$author = get_userdata( $post_data['post_author'] );
if ( ! $author ) {
return new IXR_Error( 404, __( 'Invalid author ID.' ) );
}
} else {
$post_data['post_author'] = $user->ID;
}
if ( 'open' !== $post_data['comment_status'] && 'closed' !== $post_data['comment_status'] ) {
unset( $post_data['comment_status'] );
}
if ( 'open' !== $post_data['ping_status'] && 'closed' !== $post_data['ping_status'] ) {
unset( $post_data['ping_status'] );
}
// Do some timestamp voodoo.
if ( ! empty( $post_data['post_date_gmt'] ) ) {
// We know this is supposed to be GMT, so we're going to slap that Z on there by force.
$dateCreated = rtrim( $post_data['post_date_gmt']->getIso(), 'Z' ) . 'Z';
} elseif ( ! empty( $post_data['post_date'] ) ) {
$dateCreated = $post_data['post_date']->getIso();
}
// Default to not flagging the post date to be edited unless it's intentional.
$post_data['edit_date'] = false;
if ( ! empty( $dateCreated ) ) {
$post_data['post_date'] = iso8601_to_datetime( $dateCreated );
$post_data['post_date_gmt'] = iso8601_to_datetime( $dateCreated, 'gmt' );
// Flag the post date to be edited.
$post_data['edit_date'] = true;
}
if ( ! isset( $post_data['ID'] ) ) {
$post_data['ID'] = get_default_post_to_edit( $post_data['post_type'], true )->ID;
}
$post_ID = $post_data['ID'];
if ( 'post' === $post_data['post_type'] ) {
$error = $this->_toggle_sticky( $post_data, $update );
if ( $error ) {
return $error;
}
}
if ( isset( $post_data['post_thumbnail'] ) ) {
// Empty value deletes, non-empty value adds/updates.
if ( ! $post_data['post_thumbnail'] ) {
delete_post_thumbnail( $post_ID );
} elseif ( ! get_post( absint( $post_data['post_thumbnail'] ) ) ) {
return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
}
set_post_thumbnail( $post_ID, $post_data['post_thumbnail'] );
unset( $content_struct['post_thumbnail'] );
}
if ( isset( $post_data['custom_fields'] ) ) {
$this->set_custom_fields( $post_ID, $post_data['custom_fields'] );
}
if ( isset( $post_data['terms'] ) || isset( $post_data['terms_names'] ) ) {
$post_type_taxonomies = get_object_taxonomies( $post_data['post_type'], 'objects' );
// Accumulate term IDs from terms and terms_names.
$terms = array();
// First validate the terms specified by ID.
if ( isset( $post_data['terms'] ) && is_array( $post_data['terms'] ) ) {
$taxonomies = array_keys( $post_data['terms'] );
// Validating term IDs.
foreach ( $taxonomies as $taxonomy ) {
if ( ! array_key_exists( $taxonomy, $post_type_taxonomies ) ) {
return new IXR_Error( 401, __( 'Sorry, one of the given taxonomies is not supported by the post type.' ) );
}
if ( ! current_user_can( $post_type_taxonomies[ $taxonomy ]->cap->assign_terms ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign a term to one of the given taxonomies.' ) );
}
$term_ids = $post_data['terms'][ $taxonomy ];
$terms[ $taxonomy ] = array();
foreach ( $term_ids as $term_id ) {
$term = get_term_by( 'id', $term_id, $taxonomy );
if ( ! $term ) {
return new IXR_Error( 403, __( 'Invalid term ID.' ) );
}
$terms[ $taxonomy ][] = (int) $term_id;
}
}
}
// Now validate terms specified by name.
if ( isset( $post_data['terms_names'] ) && is_array( $post_data['terms_names'] ) ) {
$taxonomies = array_keys( $post_data['terms_names'] );
foreach ( $taxonomies as $taxonomy ) {
if ( ! array_key_exists( $taxonomy, $post_type_taxonomies ) ) {
return new IXR_Error( 401, __( 'Sorry, one of the given taxonomies is not supported by the post type.' ) );
}
if ( ! current_user_can( $post_type_taxonomies[ $taxonomy ]->cap->assign_terms ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign a term to one of the given taxonomies.' ) );
}
/*
* For hierarchical taxonomies, we can't assign a term when multiple terms
* in the hierarchy share the same name.
*/
$ambiguous_terms = array();
if ( is_taxonomy_hierarchical( $taxonomy ) ) {
$tax_term_names = get_terms(
array(
'taxonomy' => $taxonomy,
'fields' => 'names',
'hide_empty' => false,
)
);
// Count the number of terms with the same name.
$tax_term_names_count = array_count_values( $tax_term_names );
// Filter out non-ambiguous term names.
$ambiguous_tax_term_counts = array_filter( $tax_term_names_count, array( $this, '_is_greater_than_one' ) );
$ambiguous_terms = array_keys( $ambiguous_tax_term_counts );
}
$term_names = $post_data['terms_names'][ $taxonomy ];
foreach ( $term_names as $term_name ) {
if ( in_array( $term_name, $ambiguous_terms, true ) ) {
return new IXR_Error( 401, __( 'Ambiguous term name used in a hierarchical taxonomy. Please use term ID instead.' ) );
}
$term = get_term_by( 'name', $term_name, $taxonomy );
if ( ! $term ) {
// Term doesn't exist, so check that the user is allowed to create new terms.
if ( ! current_user_can( $post_type_taxonomies[ $taxonomy ]->cap->edit_terms ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to add a term to one of the given taxonomies.' ) );
}
// Create the new term.
$term_info = wp_insert_term( $term_name, $taxonomy );
if ( is_wp_error( $term_info ) ) {
return new IXR_Error( 500, $term_info->get_error_message() );
}
$terms[ $taxonomy ][] = (int) $term_info['term_id'];
} else {
$terms[ $taxonomy ][] = (int) $term->term_id;
}
}
}
}
$post_data['tax_input'] = $terms;
unset( $post_data['terms'], $post_data['terms_names'] );
}
if ( isset( $post_data['post_format'] ) ) {
$format = set_post_format( $post_ID, $post_data['post_format'] );
if ( is_wp_error( $format ) ) {
return new IXR_Error( 500, $format->get_error_message() );
}
unset( $post_data['post_format'] );
}
// Handle enclosures.
$enclosure = isset( $post_data['enclosure'] ) ? $post_data['enclosure'] : null;
$this->add_enclosure_if_new( $post_ID, $enclosure );
$this->attach_uploads( $post_ID, $post_data['post_content'] );
/**
* Filters post data array to be inserted via XML-RPC.
*
* @since 3.4.0
*
* @param array $post_data Parsed array of post data.
* @param array $content_struct Post data array.
*/
$post_data = apply_filters( 'xmlrpc_wp_insert_post_data', $post_data, $content_struct );
// Remove all null values to allow for using the insert/update post default values for those keys instead.
$post_data = array_filter(
$post_data,
static function ( $value ) {
return null !== $value;
}
);
$post_ID = $update ? wp_update_post( $post_data, true ) : wp_insert_post( $post_data, true );
if ( is_wp_error( $post_ID ) ) {
return new IXR_Error( 500, $post_ID->get_error_message() );
}
if ( ! $post_ID ) {
if ( $update ) {
return new IXR_Error( 401, __( 'Sorry, the post could not be updated.' ) );
} else {
return new IXR_Error( 401, __( 'Sorry, the post could not be created.' ) );
}
}
return (string) $post_ID;
}
```
[apply\_filters( 'xmlrpc\_wp\_insert\_post\_data', array $post\_data, array $content\_struct )](../../hooks/xmlrpc_wp_insert_post_data)
Filters post data array to be inserted via XML-RPC.
| Uses | Description |
| --- | --- |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [get\_term\_by()](../../functions/get_term_by) wp-includes/taxonomy.php | Gets all term data from database by term field and data. |
| [wp\_update\_post()](../../functions/wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [set\_post\_thumbnail()](../../functions/set_post_thumbnail) wp-includes/post.php | Sets the post thumbnail (featured image) for the given post. |
| [delete\_post\_thumbnail()](../../functions/delete_post_thumbnail) wp-includes/post.php | Removes the thumbnail (featured image) from the given post. |
| [wp\_xmlrpc\_server::\_toggle\_sticky()](_toggle_sticky) wp-includes/class-wp-xmlrpc-server.php | Encapsulate the logic for sticking a post and determining if the user has permission to do so |
| [is\_taxonomy\_hierarchical()](../../functions/is_taxonomy_hierarchical) wp-includes/taxonomy.php | Determines whether the taxonomy object is hierarchical. |
| [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\_terms()](../../functions/get_terms) wp-includes/taxonomy.php | Retrieves the terms in a given taxonomy or list of taxonomies. |
| [wp\_insert\_term()](../../functions/wp_insert_term) wp-includes/taxonomy.php | Adds a new term to the database. |
| [get\_post\_type()](../../functions/get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| [get\_post\_status\_object()](../../functions/get_post_status_object) wp-includes/post.php | Retrieves a post status object by name. |
| [set\_post\_format()](../../functions/set_post_format) wp-includes/post-formats.php | Assign a format to a post |
| [wp\_xmlrpc\_server::add\_enclosure\_if\_new()](add_enclosure_if_new) wp-includes/class-wp-xmlrpc-server.php | Adds an enclosure to a post if it’s new. |
| [iso8601\_to\_datetime()](../../functions/iso8601_to_datetime) wp-includes/formatting.php | Given an ISO 8601 (Ymd\TH:i:sO) date, returns a MySQL DateTime (Y-m-d H:i:s) format used by post\_date[\_gmt]. |
| [wp\_xmlrpc\_server::attach\_uploads()](attach_uploads) wp-includes/class-wp-xmlrpc-server.php | Attach upload to a post. |
| [wp\_xmlrpc\_server::set\_custom\_fields()](set_custom_fields) wp-includes/class-wp-xmlrpc-server.php | Set custom fields for post. |
| [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. |
| [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. |
| [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. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [get\_userdata()](../../functions/get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [\_\_()](../../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. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::wp\_newPost()](wp_newpost) wp-includes/class-wp-xmlrpc-server.php | Create a new post for any registered post type. |
| [wp\_xmlrpc\_server::wp\_editPost()](wp_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post for any registered post type. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::wp_getMediaLibrary( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getMediaLibrary( array $args ): array|IXR\_Error
========================================================================
Retrieves a collection of media library items (or attachments)
Besides the common blog\_id (unused), username, and password arguments, it takes a filter array as last argument.
Accepted ‘filter’ keys are ‘parent\_id’, ‘mime\_type’, ‘offset’, and ‘number’.
The defaults are as follows:
* ‘number’ – Default is 5. Total number of media items to retrieve.
* ‘offset’ – Default is 0. See [WP\_Query::query()](../wp_query/query) for more.
* ‘parent\_id’ – Default is ”. The post where the media item is attached. Empty string shows all media items. 0 shows unattached media items.
* ‘mime\_type’ – Default is ”. Filter by mime type (e.g., ‘image/jpeg’, ‘application/pdf’)
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayQuery arguments.
array|[IXR\_Error](../ixr_error) Contains a collection of media items. See [wp\_xmlrpc\_server::wp\_getMediaItem()](wp_getmediaitem) for a description of each item contents
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getMediaLibrary( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$struct = isset( $args[3] ) ? $args[3] : array();
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'upload_files' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to upload files.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getMediaLibrary', $args, $this );
$parent_id = ( isset( $struct['parent_id'] ) ) ? absint( $struct['parent_id'] ) : '';
$mime_type = ( isset( $struct['mime_type'] ) ) ? $struct['mime_type'] : '';
$offset = ( isset( $struct['offset'] ) ) ? absint( $struct['offset'] ) : 0;
$number = ( isset( $struct['number'] ) ) ? absint( $struct['number'] ) : -1;
$attachments = get_posts(
array(
'post_type' => 'attachment',
'post_parent' => $parent_id,
'offset' => $offset,
'numberposts' => $number,
'post_mime_type' => $mime_type,
)
);
$attachments_struct = array();
foreach ( $attachments as $attachment ) {
$attachments_struct[] = $this->_prepare_media_item( $attachment );
}
return $attachments_struct;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_prepare\_media\_item()](_prepare_media_item) wp-includes/class-wp-xmlrpc-server.php | Prepares media item data for return in an XML-RPC object. |
| [get\_posts()](../../functions/get_posts) wp-includes/post.php | Retrieves an array of the latest posts, or posts matching the given criteria. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress wp_xmlrpc_server::mt_setPostCategories( array $args ): true|IXR_Error wp\_xmlrpc\_server::mt\_setPostCategories( array $args ): true|IXR\_Error
=========================================================================
Sets categories for a post.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intPost ID.
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayCategories.
true|[IXR\_Error](../ixr_error) True on success.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mt_setPostCategories( $args ) {
$this->escape( $args );
$post_ID = (int) $args[0];
$username = $args[1];
$password = $args[2];
$categories = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.setPostCategories', $args, $this );
if ( ! get_post( $post_ID ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
$catids = array();
foreach ( $categories as $cat ) {
$catids[] = $cat['categoryId'];
}
wp_set_post_categories( $post_ID, $catids );
return true;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_set\_post\_categories()](../../functions/wp_set_post_categories) wp-includes/post.php | Sets categories for a post. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_editComment( array $args ): true|IXR_Error wp\_xmlrpc\_server::wp\_editComment( array $args ): true|IXR\_Error
===================================================================
Edit comment.
Besides the common blog\_id (unused), username, and password arguments, it takes a comment\_id integer and a content\_struct array as last argument.
The allowed keys in the content\_struct array are:
* ‘author’
* ‘author\_url’
* ‘author\_email’
* ‘content’
* ‘date\_created\_gmt’
* ‘status’. Common statuses are ‘approve’, ‘hold’, ‘spam’. See [get\_comment\_statuses()](../../functions/get_comment_statuses) for more details
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intComment ID.
* `4`arrayContent structure.
true|[IXR\_Error](../ixr_error) True, on success.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_editComment( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$comment_ID = (int) $args[3];
$content_struct = $args[4];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! get_comment( $comment_ID ) ) {
return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
}
if ( ! current_user_can( 'edit_comment', $comment_ID ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to moderate or edit this comment.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.editComment', $args, $this );
$comment = array(
'comment_ID' => $comment_ID,
);
if ( isset( $content_struct['status'] ) ) {
$statuses = get_comment_statuses();
$statuses = array_keys( $statuses );
if ( ! in_array( $content_struct['status'], $statuses, true ) ) {
return new IXR_Error( 401, __( 'Invalid comment status.' ) );
}
$comment['comment_approved'] = $content_struct['status'];
}
// Do some timestamp voodoo.
if ( ! empty( $content_struct['date_created_gmt'] ) ) {
// We know this is supposed to be GMT, so we're going to slap that Z on there by force.
$dateCreated = rtrim( $content_struct['date_created_gmt']->getIso(), 'Z' ) . 'Z';
$comment['comment_date'] = get_date_from_gmt( $dateCreated );
$comment['comment_date_gmt'] = iso8601_to_datetime( $dateCreated, 'gmt' );
}
if ( isset( $content_struct['content'] ) ) {
$comment['comment_content'] = $content_struct['content'];
}
if ( isset( $content_struct['author'] ) ) {
$comment['comment_author'] = $content_struct['author'];
}
if ( isset( $content_struct['author_url'] ) ) {
$comment['comment_author_url'] = $content_struct['author_url'];
}
if ( isset( $content_struct['author_email'] ) ) {
$comment['comment_author_email'] = $content_struct['author_email'];
}
$result = wp_update_comment( $comment, true );
if ( is_wp_error( $result ) ) {
return new IXR_Error( 500, $result->get_error_message() );
}
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, the comment could not be updated.' ) );
}
/**
* Fires after a comment has been successfully updated via XML-RPC.
*
* @since 3.4.0
*
* @param int $comment_ID ID of the updated comment.
* @param array $args An array of arguments to update the comment.
*/
do_action( 'xmlrpc_call_success_wp_editComment', $comment_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return true;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[do\_action( 'xmlrpc\_call\_success\_wp\_editComment', int $comment\_ID, array $args )](../../hooks/xmlrpc_call_success_wp_editcomment)
Fires after a comment has been successfully updated via XML-RPC.
| Uses | Description |
| --- | --- |
| [get\_date\_from\_gmt()](../../functions/get_date_from_gmt) wp-includes/formatting.php | Given a date in UTC or GMT timezone, returns that date in the timezone of the site. |
| [iso8601\_to\_datetime()](../../functions/iso8601_to_datetime) wp-includes/formatting.php | Given an ISO 8601 (Ymd\TH:i:sO) date, returns a MySQL DateTime (Y-m-d H:i:s) format used by post\_date[\_gmt]. |
| [wp\_update\_comment()](../../functions/wp_update_comment) wp-includes/comment.php | Updates an existing comment in the database. |
| [get\_comment\_statuses()](../../functions/get_comment_statuses) wp-includes/comment.php | Retrieves all of the WordPress supported comment statuses. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [get\_comment()](../../functions/get_comment) wp-includes/comment.php | Retrieves comment data given a comment ID or comment object. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_restoreRevision( array $args ): bool|IXR_Error wp\_xmlrpc\_server::wp\_restoreRevision( array $args ): bool|IXR\_Error
=======================================================================
Restore a post revision
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intRevision ID.
bool|[IXR\_Error](../ixr_error) false if there was an error restoring, true if success.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_restoreRevision( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$revision_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.restoreRevision', $args, $this );
$revision = wp_get_post_revision( $revision_id );
if ( ! $revision ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( wp_is_post_autosave( $revision ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
$post = get_post( $revision->post_parent );
if ( ! $post ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $revision->post_parent ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
// Check if revisions are disabled.
if ( ! wp_revisions_enabled( $post ) ) {
return new IXR_Error( 401, __( 'Sorry, revisions are disabled.' ) );
}
$post = wp_restore_post_revision( $revision_id );
return (bool) $post;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_is\_post\_autosave()](../../functions/wp_is_post_autosave) wp-includes/revision.php | Determines if the specified post is an autosave. |
| [wp\_get\_post\_revision()](../../functions/wp_get_post_revision) wp-includes/revision.php | Gets a post revision. |
| [wp\_revisions\_enabled()](../../functions/wp_revisions_enabled) wp-includes/revision.php | Determines whether revisions are enabled for a given post. |
| [wp\_restore\_post\_revision()](../../functions/wp_restore_post_revision) wp-includes/revision.php | Restores a post to the specified revision. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::_prepare_post_type( WP_Post_Type $post_type, array $fields ): array wp\_xmlrpc\_server::\_prepare\_post\_type( WP\_Post\_Type $post\_type, array $fields ): array
=============================================================================================
Prepares post data for return in an XML-RPC object.
`$post_type` [WP\_Post\_Type](../wp_post_type) Required Post type object. `$fields` array Required The subset of post fields to return. array The prepared post type data.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function _prepare_post_type( $post_type, $fields ) {
$_post_type = array(
'name' => $post_type->name,
'label' => $post_type->label,
'hierarchical' => (bool) $post_type->hierarchical,
'public' => (bool) $post_type->public,
'show_ui' => (bool) $post_type->show_ui,
'_builtin' => (bool) $post_type->_builtin,
'has_archive' => (bool) $post_type->has_archive,
'supports' => get_all_post_type_supports( $post_type->name ),
);
if ( in_array( 'labels', $fields, true ) ) {
$_post_type['labels'] = (array) $post_type->labels;
}
if ( in_array( 'cap', $fields, true ) ) {
$_post_type['cap'] = (array) $post_type->cap;
$_post_type['map_meta_cap'] = (bool) $post_type->map_meta_cap;
}
if ( in_array( 'menu', $fields, true ) ) {
$_post_type['menu_position'] = (int) $post_type->menu_position;
$_post_type['menu_icon'] = $post_type->menu_icon;
$_post_type['show_in_menu'] = (bool) $post_type->show_in_menu;
}
if ( in_array( 'taxonomies', $fields, true ) ) {
$_post_type['taxonomies'] = get_object_taxonomies( $post_type->name, 'names' );
}
/**
* Filters XML-RPC-prepared date for the given post type.
*
* @since 3.4.0
* @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
*
* @param array $_post_type An array of post type data.
* @param WP_Post_Type $post_type Post type object.
*/
return apply_filters( 'xmlrpc_prepare_post_type', $_post_type, $post_type );
}
```
[apply\_filters( 'xmlrpc\_prepare\_post\_type', array $\_post\_type, WP\_Post\_Type $post\_type )](../../hooks/xmlrpc_prepare_post_type)
Filters XML-RPC-prepared date for the given post type.
| 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\_all\_post\_type\_supports()](../../functions/get_all_post_type_supports) wp-includes/post.php | Gets all the post type features |
| [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\_xmlrpc\_server::wp\_getPostType()](wp_getposttype) wp-includes/class-wp-xmlrpc-server.php | Retrieves a post type |
| [wp\_xmlrpc\_server::wp\_getPostTypes()](wp_getposttypes) wp-includes/class-wp-xmlrpc-server.php | Retrieves a post types |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Converted the `$post_type` parameter to accept a [WP\_Post\_Type](../wp_post_type) object. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::wp_setOptions( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_setOptions( array $args ): array|IXR\_Error
===================================================================
Update blog options.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayOptions.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_setOptions( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$options = (array) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'manage_options' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to update options.' ) );
}
$option_names = array();
foreach ( $options as $o_name => $o_value ) {
$option_names[] = $o_name;
if ( ! array_key_exists( $o_name, $this->blog_options ) ) {
continue;
}
if ( true == $this->blog_options[ $o_name ]['readonly'] ) {
continue;
}
update_option( $this->blog_options[ $o_name ]['option'], wp_unslash( $o_value ) );
}
// Now return the updated values.
return $this->_getOptions( $option_names );
}
```
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_getOptions()](_getoptions) wp-includes/class-wp-xmlrpc-server.php | Retrieve blog options value from list. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress wp_xmlrpc_server::set_custom_fields( int $post_id, array $fields ) wp\_xmlrpc\_server::set\_custom\_fields( int $post\_id, array $fields )
=======================================================================
Set custom fields for post.
`$post_id` int Required Post ID. `$fields` array Required Custom fields. File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function set_custom_fields( $post_id, $fields ) {
$post_id = (int) $post_id;
foreach ( (array) $fields as $meta ) {
if ( isset( $meta['id'] ) ) {
$meta['id'] = (int) $meta['id'];
$pmeta = get_metadata_by_mid( 'post', $meta['id'] );
if ( ! $pmeta || $pmeta->post_id != $post_id ) {
continue;
}
if ( isset( $meta['key'] ) ) {
$meta['key'] = wp_unslash( $meta['key'] );
if ( $meta['key'] !== $pmeta->meta_key ) {
continue;
}
$meta['value'] = wp_unslash( $meta['value'] );
if ( current_user_can( 'edit_post_meta', $post_id, $meta['key'] ) ) {
update_metadata_by_mid( 'post', $meta['id'], $meta['value'] );
}
} elseif ( current_user_can( 'delete_post_meta', $post_id, $pmeta->meta_key ) ) {
delete_metadata_by_mid( 'post', $meta['id'] );
}
} elseif ( current_user_can( 'add_post_meta', $post_id, wp_unslash( $meta['key'] ) ) ) {
add_post_meta( $post_id, $meta['key'], $meta['value'] );
}
}
}
```
| Uses | Description |
| --- | --- |
| [add\_post\_meta()](../../functions/add_post_meta) wp-includes/post.php | Adds a meta field to the given post. |
| [get\_metadata\_by\_mid()](../../functions/get_metadata_by_mid) wp-includes/meta.php | Retrieves metadata by meta ID. |
| [update\_metadata\_by\_mid()](../../functions/update_metadata_by_mid) wp-includes/meta.php | Updates metadata by meta ID. |
| [delete\_metadata\_by\_mid()](../../functions/delete_metadata_by_mid) wp-includes/meta.php | Deletes metadata by meta ID. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::mw\_editPost()](mw_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post. |
| [wp\_xmlrpc\_server::mw\_newPost()](mw_newpost) wp-includes/class-wp-xmlrpc-server.php | Create a new post. |
| [wp\_xmlrpc\_server::\_insert\_post()](_insert_post) wp-includes/class-wp-xmlrpc-server.php | Helper method for wp\_newPost() and wp\_editPost(), containing shared logic. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::attach_uploads( int $post_ID, string $post_content ) wp\_xmlrpc\_server::attach\_uploads( int $post\_ID, string $post\_content )
===========================================================================
Attach upload to a post.
`$post_ID` int Required Post ID. `$post_content` string Required Post Content for attachment. File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function attach_uploads( $post_ID, $post_content ) {
global $wpdb;
// Find any unattached files.
$attachments = $wpdb->get_results( "SELECT ID, guid FROM {$wpdb->posts} WHERE post_parent = '0' AND post_type = 'attachment'" );
if ( is_array( $attachments ) ) {
foreach ( $attachments as $file ) {
if ( ! empty( $file->guid ) && strpos( $post_content, $file->guid ) !== false ) {
$wpdb->update( $wpdb->posts, array( 'post_parent' => $post_ID ), array( 'ID' => $file->ID ) );
}
}
}
}
```
| Uses | Description |
| --- | --- |
| [wpdb::update()](../wpdb/update) wp-includes/class-wpdb.php | Updates a row in the table. |
| [wpdb::get\_results()](../wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::mw\_editPost()](mw_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post. |
| [wp\_xmlrpc\_server::blogger\_newPost()](blogger_newpost) wp-includes/class-wp-xmlrpc-server.php | Creates new post. |
| [wp\_xmlrpc\_server::blogger\_editPost()](blogger_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post. |
| [wp\_xmlrpc\_server::mw\_newPost()](mw_newpost) wp-includes/class-wp-xmlrpc-server.php | Create a new post. |
| [wp\_xmlrpc\_server::\_insert\_post()](_insert_post) wp-includes/class-wp-xmlrpc-server.php | Helper method for wp\_newPost() and wp\_editPost(), containing shared logic. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress wp_xmlrpc_server::mw_getPost( array $args ): array|IXR_Error wp\_xmlrpc\_server::mw\_getPost( array $args ): array|IXR\_Error
================================================================
Retrieve post.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intPost ID.
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mw_getPost( $args ) {
$this->escape( $args );
$post_ID = (int) $args[0];
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
$postdata = get_post( $post_ID, ARRAY_A );
if ( ! $postdata ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'metaWeblog.getPost', $args, $this );
if ( '' !== $postdata['post_date'] ) {
$post_date = $this->_convert_date( $postdata['post_date'] );
$post_date_gmt = $this->_convert_date_gmt( $postdata['post_date_gmt'], $postdata['post_date'] );
$post_modified = $this->_convert_date( $postdata['post_modified'] );
$post_modified_gmt = $this->_convert_date_gmt( $postdata['post_modified_gmt'], $postdata['post_modified'] );
$categories = array();
$catids = wp_get_post_categories( $post_ID );
foreach ( $catids as $catid ) {
$categories[] = get_cat_name( $catid );
}
$tagnames = array();
$tags = wp_get_post_tags( $post_ID );
if ( ! empty( $tags ) ) {
foreach ( $tags as $tag ) {
$tagnames[] = $tag->name;
}
$tagnames = implode( ', ', $tagnames );
} else {
$tagnames = '';
}
$post = get_extended( $postdata['post_content'] );
$link = get_permalink( $postdata['ID'] );
// Get the author info.
$author = get_userdata( $postdata['post_author'] );
$allow_comments = ( 'open' === $postdata['comment_status'] ) ? 1 : 0;
$allow_pings = ( 'open' === $postdata['ping_status'] ) ? 1 : 0;
// Consider future posts as published.
if ( 'future' === $postdata['post_status'] ) {
$postdata['post_status'] = 'publish';
}
// Get post format.
$post_format = get_post_format( $post_ID );
if ( empty( $post_format ) ) {
$post_format = 'standard';
}
$sticky = false;
if ( is_sticky( $post_ID ) ) {
$sticky = true;
}
$enclosure = array();
foreach ( (array) get_post_custom( $post_ID ) as $key => $val ) {
if ( 'enclosure' === $key ) {
foreach ( (array) $val as $enc ) {
$encdata = explode( "\n", $enc );
$enclosure['url'] = trim( htmlspecialchars( $encdata[0] ) );
$enclosure['length'] = (int) trim( $encdata[1] );
$enclosure['type'] = trim( $encdata[2] );
break 2;
}
}
}
$resp = array(
'dateCreated' => $post_date,
'userid' => $postdata['post_author'],
'postid' => $postdata['ID'],
'description' => $post['main'],
'title' => $postdata['post_title'],
'link' => $link,
'permaLink' => $link,
// Commented out because no other tool seems to use this.
// 'content' => $entry['post_content'],
'categories' => $categories,
'mt_excerpt' => $postdata['post_excerpt'],
'mt_text_more' => $post['extended'],
'wp_more_text' => $post['more_text'],
'mt_allow_comments' => $allow_comments,
'mt_allow_pings' => $allow_pings,
'mt_keywords' => $tagnames,
'wp_slug' => $postdata['post_name'],
'wp_password' => $postdata['post_password'],
'wp_author_id' => (string) $author->ID,
'wp_author_display_name' => $author->display_name,
'date_created_gmt' => $post_date_gmt,
'post_status' => $postdata['post_status'],
'custom_fields' => $this->get_custom_fields( $post_ID ),
'wp_post_format' => $post_format,
'sticky' => $sticky,
'date_modified' => $post_modified,
'date_modified_gmt' => $post_modified_gmt,
);
if ( ! empty( $enclosure ) ) {
$resp['enclosure'] = $enclosure;
}
$resp['wp_post_thumbnail'] = get_post_thumbnail_id( $postdata['ID'] );
return $resp;
} else {
return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
}
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::get\_custom\_fields()](get_custom_fields) wp-includes/class-wp-xmlrpc-server.php | Retrieve custom fields for post. |
| [wp\_get\_post\_tags()](../../functions/wp_get_post_tags) wp-includes/post.php | Retrieves the tags for a post. |
| [wp\_xmlrpc\_server::\_convert\_date\_gmt()](_convert_date_gmt) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress GMT date string to an [IXR\_Date](../ixr_date) object. |
| [wp\_xmlrpc\_server::\_convert\_date()](_convert_date) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress date string to an [IXR\_Date](../ixr_date) object. |
| [get\_post\_format()](../../functions/get_post_format) wp-includes/post-formats.php | Retrieve the format slug for a post |
| [get\_extended()](../../functions/get_extended) wp-includes/post.php | Gets extended entry info (`<!--more-->`). |
| [get\_post\_custom()](../../functions/get_post_custom) wp-includes/post.php | Retrieves post meta fields, based on post ID. |
| [is\_sticky()](../../functions/is_sticky) wp-includes/post.php | Determines whether a post is sticky. |
| [wp\_get\_post\_categories()](../../functions/wp_get_post_categories) wp-includes/post.php | Retrieves the list of categories for a post. |
| [get\_post\_thumbnail\_id()](../../functions/get_post_thumbnail_id) wp-includes/post-thumbnail-template.php | Retrieves the post thumbnail ID. |
| [get\_cat\_name()](../../functions/get_cat_name) wp-includes/category.php | Retrieves the name of a category from its ID. |
| [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. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [get\_permalink()](../../functions/get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [get\_userdata()](../../functions/get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::_prepare_post( array $post, array $fields ): array wp\_xmlrpc\_server::\_prepare\_post( array $post, array $fields ): array
========================================================================
Prepares post data for return in an XML-RPC object.
`$post` array Required The unprepared post data. `$fields` array Required The subset of post type fields to return. array The prepared post data.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function _prepare_post( $post, $fields ) {
// Holds the data for this post. built up based on $fields.
$_post = array( 'post_id' => (string) $post['ID'] );
// Prepare common post fields.
$post_fields = array(
'post_title' => $post['post_title'],
'post_date' => $this->_convert_date( $post['post_date'] ),
'post_date_gmt' => $this->_convert_date_gmt( $post['post_date_gmt'], $post['post_date'] ),
'post_modified' => $this->_convert_date( $post['post_modified'] ),
'post_modified_gmt' => $this->_convert_date_gmt( $post['post_modified_gmt'], $post['post_modified'] ),
'post_status' => $post['post_status'],
'post_type' => $post['post_type'],
'post_name' => $post['post_name'],
'post_author' => $post['post_author'],
'post_password' => $post['post_password'],
'post_excerpt' => $post['post_excerpt'],
'post_content' => $post['post_content'],
'post_parent' => (string) $post['post_parent'],
'post_mime_type' => $post['post_mime_type'],
'link' => get_permalink( $post['ID'] ),
'guid' => $post['guid'],
'menu_order' => (int) $post['menu_order'],
'comment_status' => $post['comment_status'],
'ping_status' => $post['ping_status'],
'sticky' => ( 'post' === $post['post_type'] && is_sticky( $post['ID'] ) ),
);
// Thumbnail.
$post_fields['post_thumbnail'] = array();
$thumbnail_id = get_post_thumbnail_id( $post['ID'] );
if ( $thumbnail_id ) {
$thumbnail_size = current_theme_supports( 'post-thumbnail' ) ? 'post-thumbnail' : 'thumbnail';
$post_fields['post_thumbnail'] = $this->_prepare_media_item( get_post( $thumbnail_id ), $thumbnail_size );
}
// Consider future posts as published.
if ( 'future' === $post_fields['post_status'] ) {
$post_fields['post_status'] = 'publish';
}
// Fill in blank post format.
$post_fields['post_format'] = get_post_format( $post['ID'] );
if ( empty( $post_fields['post_format'] ) ) {
$post_fields['post_format'] = 'standard';
}
// Merge requested $post_fields fields into $_post.
if ( in_array( 'post', $fields, true ) ) {
$_post = array_merge( $_post, $post_fields );
} else {
$requested_fields = array_intersect_key( $post_fields, array_flip( $fields ) );
$_post = array_merge( $_post, $requested_fields );
}
$all_taxonomy_fields = in_array( 'taxonomies', $fields, true );
if ( $all_taxonomy_fields || in_array( 'terms', $fields, true ) ) {
$post_type_taxonomies = get_object_taxonomies( $post['post_type'], 'names' );
$terms = wp_get_object_terms( $post['ID'], $post_type_taxonomies );
$_post['terms'] = array();
foreach ( $terms as $term ) {
$_post['terms'][] = $this->_prepare_term( $term );
}
}
if ( in_array( 'custom_fields', $fields, true ) ) {
$_post['custom_fields'] = $this->get_custom_fields( $post['ID'] );
}
if ( in_array( 'enclosure', $fields, true ) ) {
$_post['enclosure'] = array();
$enclosures = (array) get_post_meta( $post['ID'], 'enclosure' );
if ( ! empty( $enclosures ) ) {
$encdata = explode( "\n", $enclosures[0] );
$_post['enclosure']['url'] = trim( htmlspecialchars( $encdata[0] ) );
$_post['enclosure']['length'] = (int) trim( $encdata[1] );
$_post['enclosure']['type'] = trim( $encdata[2] );
}
}
/**
* Filters XML-RPC-prepared date for the given post.
*
* @since 3.4.0
*
* @param array $_post An array of modified post data.
* @param array $post An array of post data.
* @param array $fields An array of post fields.
*/
return apply_filters( 'xmlrpc_prepare_post', $_post, $post, $fields );
}
```
[apply\_filters( 'xmlrpc\_prepare\_post', array $\_post, array $post, array $fields )](../../hooks/xmlrpc_prepare_post)
Filters XML-RPC-prepared date for the given post.
| Uses | Description |
| --- | --- |
| [wp\_get\_object\_terms()](../../functions/wp_get_object_terms) wp-includes/taxonomy.php | Retrieves the terms associated with the given object(s), in the supplied taxonomies. |
| [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\_post\_thumbnail\_id()](../../functions/get_post_thumbnail_id) wp-includes/post-thumbnail-template.php | Retrieves the post thumbnail ID. |
| [is\_sticky()](../../functions/is_sticky) wp-includes/post.php | Determines whether a post is sticky. |
| [get\_post\_format()](../../functions/get_post_format) wp-includes/post-formats.php | Retrieve the format slug for a post |
| [wp\_xmlrpc\_server::\_convert\_date()](_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()](_convert_date_gmt) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress GMT date string to an [IXR\_Date](../ixr_date) object. |
| [wp\_xmlrpc\_server::\_prepare\_media\_item()](_prepare_media_item) wp-includes/class-wp-xmlrpc-server.php | Prepares media item data for return in an XML-RPC object. |
| [wp\_xmlrpc\_server::\_prepare\_term()](_prepare_term) wp-includes/class-wp-xmlrpc-server.php | Prepares term data for return in an XML-RPC object. |
| [wp\_xmlrpc\_server::get\_custom\_fields()](get_custom_fields) wp-includes/class-wp-xmlrpc-server.php | Retrieve custom fields for post. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [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\_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\_xmlrpc\_server::wp\_getRevisions()](wp_getrevisions) wp-includes/class-wp-xmlrpc-server.php | Retrieve revisions for a specific post. |
| [wp\_xmlrpc\_server::wp\_getPosts()](wp_getposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve posts. |
| [wp\_xmlrpc\_server::wp\_getPost()](wp_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve a post. |
| programming_docs |
wordpress wp_xmlrpc_server::pingback_error( int $code, string $message ): IXR_Error wp\_xmlrpc\_server::pingback\_error( int $code, string $message ): IXR\_Error
=============================================================================
Sends a pingback error based on the given error code and message.
`$code` int Required Error code. `$message` string Required Error message. [IXR\_Error](../ixr_error) Error object.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function pingback_error( $code, $message ) {
/**
* Filters the XML-RPC pingback error return.
*
* @since 3.5.1
*
* @param IXR_Error $error An IXR_Error object containing the error code and message.
*/
return apply_filters( 'xmlrpc_pingback_error', new IXR_Error( $code, $message ) );
}
```
[apply\_filters( 'xmlrpc\_pingback\_error', IXR\_Error $error )](../../hooks/xmlrpc_pingback_error)
Filters the XML-RPC pingback error return.
| Uses | Description |
| --- | --- |
| [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. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::pingback\_ping()](pingback_ping) wp-includes/class-wp-xmlrpc-server.php | Retrieves a pingback and registers it. |
| [wp\_xmlrpc\_server::pingback\_extensions\_getPingbacks()](pingback_extensions_getpingbacks) wp-includes/class-wp-xmlrpc-server.php | Retrieve array of URLs that pingbacked the given URL. |
| Version | Description |
| --- | --- |
| [3.6.0](https://developer.wordpress.org/reference/since/3.6.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getMediaItem( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getMediaItem( array $args ): array|IXR\_Error
=====================================================================
Retrieve a media item by ID
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intAttachment ID.
array|[IXR\_Error](../ixr_error) Associative array contains:
* `'date_created_gmt'`
* `'parent'`
* `'link'`
* `'thumbnail'`
* `'title'`
* `'caption'`
* `'description'`
* `'metadata'`
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getMediaItem( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$attachment_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'upload_files' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to upload files.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getMediaItem', $args, $this );
$attachment = get_post( $attachment_id );
if ( ! $attachment || 'attachment' !== $attachment->post_type ) {
return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
}
return $this->_prepare_media_item( $attachment );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_prepare\_media\_item()](_prepare_media_item) wp-includes/class-wp-xmlrpc-server.php | Prepares media item data for return in an XML-RPC object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress wp_xmlrpc_server::mt_getTrackbackPings( int $post_ID ): array|IXR_Error wp\_xmlrpc\_server::mt\_getTrackbackPings( int $post\_ID ): array|IXR\_Error
============================================================================
Retrieve trackbacks sent to a given post.
`$post_ID` int Required array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mt_getTrackbackPings( $post_ID ) {
global $wpdb;
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.getTrackbackPings', $post_ID, $this );
$actual_post = get_post( $post_ID, ARRAY_A );
if ( ! $actual_post ) {
return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
}
$comments = $wpdb->get_results( $wpdb->prepare( "SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = %d", $post_ID ) );
if ( ! $comments ) {
return array();
}
$trackback_pings = array();
foreach ( $comments as $comment ) {
if ( 'trackback' === $comment->comment_type ) {
$content = $comment->comment_content;
$title = substr( $content, 8, ( strpos( $content, '</strong>' ) - 8 ) );
$trackback_pings[] = array(
'pingTitle' => $title,
'pingURL' => $comment->comment_author_url,
'pingIP' => $comment->comment_author_IP,
);
}
}
return $trackback_pings;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [\_\_()](../../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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [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 |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getPageList( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getPageList( array $args ): array|IXR\_Error
====================================================================
Retrieve page list.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getPageList( $args ) {
global $wpdb;
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_pages' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit pages.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPageList', $args, $this );
// Get list of page IDs and titles.
$page_list = $wpdb->get_results(
"
SELECT ID page_id,
post_title page_title,
post_parent page_parent_id,
post_date_gmt,
post_date,
post_status
FROM {$wpdb->posts}
WHERE post_type = 'page'
ORDER BY ID
"
);
// The date needs to be formatted properly.
$num_pages = count( $page_list );
for ( $i = 0; $i < $num_pages; $i++ ) {
$page_list[ $i ]->dateCreated = $this->_convert_date( $page_list[ $i ]->post_date );
$page_list[ $i ]->date_created_gmt = $this->_convert_date_gmt( $page_list[ $i ]->post_date_gmt, $page_list[ $i ]->post_date );
unset( $page_list[ $i ]->post_date_gmt );
unset( $page_list[ $i ]->post_date );
unset( $page_list[ $i ]->post_status );
}
return $page_list;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_convert\_date()](_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()](_convert_date_gmt) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress GMT date string to an [IXR\_Date](../ixr_date) object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [wpdb::get\_results()](../wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| Version | Description |
| --- | --- |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress wp_xmlrpc_server::add_enclosure_if_new( int $post_ID, array $enclosure ) wp\_xmlrpc\_server::add\_enclosure\_if\_new( int $post\_ID, array $enclosure )
==============================================================================
Adds an enclosure to a post if it’s new.
`$post_ID` int Required Post ID. `$enclosure` array Required Enclosure data. File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function add_enclosure_if_new( $post_ID, $enclosure ) {
if ( is_array( $enclosure ) && isset( $enclosure['url'] ) && isset( $enclosure['length'] ) && isset( $enclosure['type'] ) ) {
$encstring = $enclosure['url'] . "\n" . $enclosure['length'] . "\n" . $enclosure['type'] . "\n";
$found = false;
$enclosures = get_post_meta( $post_ID, 'enclosure' );
if ( $enclosures ) {
foreach ( $enclosures as $enc ) {
// This method used to omit the trailing new line. #23219
if ( rtrim( $enc, "\n" ) == rtrim( $encstring, "\n" ) ) {
$found = true;
break;
}
}
}
if ( ! $found ) {
add_post_meta( $post_ID, 'enclosure', $encstring );
}
}
}
```
| Uses | Description |
| --- | --- |
| [add\_post\_meta()](../../functions/add_post_meta) wp-includes/post.php | Adds a meta field to the given post. |
| [get\_post\_meta()](../../functions/get_post_meta) wp-includes/post.php | Retrieves a post meta field for the given post ID. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::mw\_editPost()](mw_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post. |
| [wp\_xmlrpc\_server::mw\_newPost()](mw_newpost) wp-includes/class-wp-xmlrpc-server.php | Create a new post. |
| [wp\_xmlrpc\_server::\_insert\_post()](_insert_post) wp-includes/class-wp-xmlrpc-server.php | Helper method for wp\_newPost() and wp\_editPost(), containing shared logic. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress wp_xmlrpc_server::minimum_args( array $args, int $count ): bool wp\_xmlrpc\_server::minimum\_args( array $args, int $count ): bool
==================================================================
Checks if the method received at least the minimum number of arguments.
`$args` array Required An array of arguments to check. `$count` int Required Minimum number of arguments. bool True if `$args` contains at least `$count` arguments, false otherwise.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function minimum_args( $args, $count ) {
if ( ! is_array( $args ) || count( $args ) < $count ) {
$this->error = new IXR_Error( 400, __( 'Insufficient arguments passed to this XML-RPC method.' ) );
return false;
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::wp\_getPostType()](wp_getposttype) wp-includes/class-wp-xmlrpc-server.php | Retrieves a post type |
| [wp\_xmlrpc\_server::wp\_getPostTypes()](wp_getposttypes) wp-includes/class-wp-xmlrpc-server.php | Retrieves a post types |
| [wp\_xmlrpc\_server::wp\_getRevisions()](wp_getrevisions) wp-includes/class-wp-xmlrpc-server.php | Retrieve revisions for a specific post. |
| [wp\_xmlrpc\_server::wp\_restoreRevision()](wp_restorerevision) wp-includes/class-wp-xmlrpc-server.php | Restore a post revision |
| [wp\_xmlrpc\_server::blogger\_getUsersBlogs()](blogger_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Retrieve blogs that user owns. |
| [wp\_xmlrpc\_server::wp\_getPosts()](wp_getposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve posts. |
| [wp\_xmlrpc\_server::wp\_newTerm()](wp_newterm) wp-includes/class-wp-xmlrpc-server.php | Create a new term. |
| [wp\_xmlrpc\_server::wp\_editTerm()](wp_editterm) wp-includes/class-wp-xmlrpc-server.php | Edit a term. |
| [wp\_xmlrpc\_server::wp\_deleteTerm()](wp_deleteterm) wp-includes/class-wp-xmlrpc-server.php | Delete a term. |
| [wp\_xmlrpc\_server::wp\_getTerm()](wp_getterm) wp-includes/class-wp-xmlrpc-server.php | Retrieve a term. |
| [wp\_xmlrpc\_server::wp\_getTerms()](wp_getterms) wp-includes/class-wp-xmlrpc-server.php | Retrieve all terms for a taxonomy. |
| [wp\_xmlrpc\_server::wp\_getTaxonomy()](wp_gettaxonomy) wp-includes/class-wp-xmlrpc-server.php | Retrieve a taxonomy. |
| [wp\_xmlrpc\_server::wp\_getTaxonomies()](wp_gettaxonomies) wp-includes/class-wp-xmlrpc-server.php | Retrieve all taxonomies. |
| [wp\_xmlrpc\_server::wp\_getUser()](wp_getuser) wp-includes/class-wp-xmlrpc-server.php | Retrieve a user. |
| [wp\_xmlrpc\_server::wp\_getUsers()](wp_getusers) wp-includes/class-wp-xmlrpc-server.php | Retrieve users. |
| [wp\_xmlrpc\_server::wp\_getProfile()](wp_getprofile) wp-includes/class-wp-xmlrpc-server.php | Retrieve information about the requesting user. |
| [wp\_xmlrpc\_server::wp\_editProfile()](wp_editprofile) wp-includes/class-wp-xmlrpc-server.php | Edit user’s profile. |
| [wp\_xmlrpc\_server::wp\_newPost()](wp_newpost) wp-includes/class-wp-xmlrpc-server.php | Create a new post for any registered post type. |
| [wp\_xmlrpc\_server::wp\_editPost()](wp_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post for any registered post type. |
| [wp\_xmlrpc\_server::wp\_deletePost()](wp_deletepost) wp-includes/class-wp-xmlrpc-server.php | Delete a post for any registered post type. |
| [wp\_xmlrpc\_server::wp\_getPost()](wp_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve a post. |
| [wp\_xmlrpc\_server::wp\_getUsersBlogs()](wp_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Retrieve the blogs of the user. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wp_xmlrpc_server::_prepare_page( WP_Post $page ): array wp\_xmlrpc\_server::\_prepare\_page( WP\_Post $page ): array
============================================================
Prepares page data for return in an XML-RPC object.
`$page` [WP\_Post](../wp_post) Required The unprepared page data. array The prepared page data.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function _prepare_page( $page ) {
// Get all of the page content and link.
$full_page = get_extended( $page->post_content );
$link = get_permalink( $page->ID );
// Get info the page parent if there is one.
$parent_title = '';
if ( ! empty( $page->post_parent ) ) {
$parent = get_post( $page->post_parent );
$parent_title = $parent->post_title;
}
// Determine comment and ping settings.
$allow_comments = comments_open( $page->ID ) ? 1 : 0;
$allow_pings = pings_open( $page->ID ) ? 1 : 0;
// Format page date.
$page_date = $this->_convert_date( $page->post_date );
$page_date_gmt = $this->_convert_date_gmt( $page->post_date_gmt, $page->post_date );
// Pull the categories info together.
$categories = array();
if ( is_object_in_taxonomy( 'page', 'category' ) ) {
foreach ( wp_get_post_categories( $page->ID ) as $cat_id ) {
$categories[] = get_cat_name( $cat_id );
}
}
// Get the author info.
$author = get_userdata( $page->post_author );
$page_template = get_page_template_slug( $page->ID );
if ( empty( $page_template ) ) {
$page_template = 'default';
}
$_page = array(
'dateCreated' => $page_date,
'userid' => $page->post_author,
'page_id' => $page->ID,
'page_status' => $page->post_status,
'description' => $full_page['main'],
'title' => $page->post_title,
'link' => $link,
'permaLink' => $link,
'categories' => $categories,
'excerpt' => $page->post_excerpt,
'text_more' => $full_page['extended'],
'mt_allow_comments' => $allow_comments,
'mt_allow_pings' => $allow_pings,
'wp_slug' => $page->post_name,
'wp_password' => $page->post_password,
'wp_author' => $author->display_name,
'wp_page_parent_id' => $page->post_parent,
'wp_page_parent_title' => $parent_title,
'wp_page_order' => $page->menu_order,
'wp_author_id' => (string) $author->ID,
'wp_author_display_name' => $author->display_name,
'date_created_gmt' => $page_date_gmt,
'custom_fields' => $this->get_custom_fields( $page->ID ),
'wp_page_template' => $page_template,
);
/**
* Filters XML-RPC-prepared data for the given page.
*
* @since 3.4.0
*
* @param array $_page An array of page data.
* @param WP_Post $page Page object.
*/
return apply_filters( 'xmlrpc_prepare_page', $_page, $page );
}
```
[apply\_filters( 'xmlrpc\_prepare\_page', array $\_page, WP\_Post $page )](../../hooks/xmlrpc_prepare_page)
Filters XML-RPC-prepared data for the given page.
| Uses | Description |
| --- | --- |
| [get\_cat\_name()](../../functions/get_cat_name) wp-includes/category.php | Retrieves the name of a category from its ID. |
| [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\_page\_template\_slug()](../../functions/get_page_template_slug) wp-includes/post-template.php | Gets the specific template filename for a given post. |
| [wp\_get\_post\_categories()](../../functions/wp_get_post_categories) wp-includes/post.php | Retrieves the list of categories for a post. |
| [get\_extended()](../../functions/get_extended) wp-includes/post.php | Gets extended entry info (`<!--more-->`). |
| [wp\_xmlrpc\_server::\_convert\_date()](_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()](_convert_date_gmt) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress GMT date string to an [IXR\_Date](../ixr_date) object. |
| [wp\_xmlrpc\_server::get\_custom\_fields()](get_custom_fields) wp-includes/class-wp-xmlrpc-server.php | Retrieve custom fields for post. |
| [comments\_open()](../../functions/comments_open) wp-includes/comment-template.php | Determines whether the current post is open for comments. |
| [pings\_open()](../../functions/pings_open) wp-includes/comment-template.php | Determines whether the current post is open for pings. |
| [get\_userdata()](../../functions/get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::wp\_getPages()](wp_getpages) wp-includes/class-wp-xmlrpc-server.php | Retrieve Pages. |
| [wp\_xmlrpc\_server::wp\_getPage()](wp_getpage) wp-includes/class-wp-xmlrpc-server.php | Retrieve page. |
| programming_docs |
wordpress wp_xmlrpc_server::wp_deleteCategory( array $args ): bool|IXR_Error wp\_xmlrpc\_server::wp\_deleteCategory( array $args ): bool|IXR\_Error
======================================================================
Remove category.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intCategory ID.
bool|[IXR\_Error](../ixr_error) See [wp\_delete\_term()](../../functions/wp_delete_term) for return info.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_deleteCategory( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$category_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.deleteCategory', $args, $this );
if ( ! current_user_can( 'delete_term', $category_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this category.' ) );
}
$status = wp_delete_term( $category_id, 'category' );
if ( true == $status ) {
/**
* Fires after a category has been successfully deleted via XML-RPC.
*
* @since 3.4.0
*
* @param int $category_id ID of the deleted category.
* @param array $args An array of arguments to delete the category.
*/
do_action( 'xmlrpc_call_success_wp_deleteCategory', $category_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
}
return $status;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[do\_action( 'xmlrpc\_call\_success\_wp\_deleteCategory', int $category\_id, array $args )](../../hooks/xmlrpc_call_success_wp_deletecategory)
Fires after a category has been successfully deleted via XML-RPC.
| Uses | Description |
| --- | --- |
| [wp\_delete\_term()](../../functions/wp_delete_term) wp-includes/taxonomy.php | Removes a term from the database. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getPostFormats( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getPostFormats( array $args ): array|IXR\_Error
=======================================================================
Retrieves a list of post formats used by the site.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error) List of post formats, otherwise [IXR\_Error](../ixr_error) object.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getPostFormats( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPostFormats', $args, $this );
$formats = get_post_format_strings();
// Find out if they want a list of currently supports formats.
if ( isset( $args[3] ) && is_array( $args[3] ) ) {
if ( $args[3]['show-supported'] ) {
if ( current_theme_supports( 'post-formats' ) ) {
$supported = get_theme_support( 'post-formats' );
$data = array();
$data['all'] = $formats;
$data['supported'] = $supported[0];
$formats = $data;
}
}
}
return $formats;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [get\_post\_format\_strings()](../../functions/get_post_format_strings) wp-includes/post-formats.php | Returns an array of post format slugs to their translated and pretty display versions |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress wp_xmlrpc_server::blogger_deletePost( array $args ): true|IXR_Error wp\_xmlrpc\_server::blogger\_deletePost( array $args ): true|IXR\_Error
=======================================================================
Remove a post.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`intPost ID.
* `2`stringUsername.
* `3`stringPassword.
true|[IXR\_Error](../ixr_error) True when post is deleted.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function blogger_deletePost( $args ) {
$this->escape( $args );
$post_ID = (int) $args[1];
$username = $args[2];
$password = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.deletePost', $args, $this );
$actual_post = get_post( $post_ID, ARRAY_A );
if ( ! $actual_post || 'post' !== $actual_post['post_type'] ) {
return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
}
if ( ! current_user_can( 'delete_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this post.' ) );
}
$result = wp_delete_post( $post_ID );
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, the post could not be deleted.' ) );
}
/**
* Fires after a post has been successfully deleted via the XML-RPC Blogger API.
*
* @since 3.4.0
*
* @param int $post_ID ID of the deleted post.
* @param array $args An array of arguments to delete the post.
*/
do_action( 'xmlrpc_call_success_blogger_deletePost', $post_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return true;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[do\_action( 'xmlrpc\_call\_success\_blogger\_deletePost', int $post\_ID, array $args )](../../hooks/xmlrpc_call_success_blogger_deletepost)
Fires after a post has been successfully deleted via the XML-RPC Blogger API.
| Uses | Description |
| --- | --- |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::login_pass_ok( string $username, string $password ): bool wp\_xmlrpc\_server::login\_pass\_ok( string $username, string $password ): bool
===============================================================================
This method has been deprecated. Use [wp\_xmlrpc\_server::login()](login) instead.
Check user’s credentials. Deprecated.
* [wp\_xmlrpc\_server::login()](login)
`$username` string Required User's username. `$password` string Required User's password. bool Whether authentication passed.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function login_pass_ok( $username, $password ) {
return (bool) $this->login( $username, $password );
}
```
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Use [wp\_xmlrpc\_server::login()](login) |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::get_custom_fields( int $post_id ): array wp\_xmlrpc\_server::get\_custom\_fields( int $post\_id ): array
===============================================================
Retrieve custom fields for post.
`$post_id` int Required Post ID. array Custom fields, if exist.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function get_custom_fields( $post_id ) {
$post_id = (int) $post_id;
$custom_fields = array();
foreach ( (array) has_meta( $post_id ) as $meta ) {
// Don't expose protected fields.
if ( ! current_user_can( 'edit_post_meta', $post_id, $meta['meta_key'] ) ) {
continue;
}
$custom_fields[] = array(
'id' => $meta['meta_id'],
'key' => $meta['meta_key'],
'value' => $meta['meta_value'],
);
}
return $custom_fields;
}
```
| Uses | Description |
| --- | --- |
| [has\_meta()](../../functions/has_meta) wp-admin/includes/post.php | Returns meta data for the given post ID. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::mw\_getPost()](mw_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve post. |
| [wp\_xmlrpc\_server::mw\_getRecentPosts()](mw_getrecentposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve list of recent posts. |
| [wp\_xmlrpc\_server::\_prepare\_page()](_prepare_page) wp-includes/class-wp-xmlrpc-server.php | Prepares page data for return in an XML-RPC object. |
| [wp\_xmlrpc\_server::\_prepare\_post()](_prepare_post) wp-includes/class-wp-xmlrpc-server.php | Prepares post data for return in an XML-RPC object. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getPostTypes( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getPostTypes( array $args ): array|IXR\_Error
=====================================================================
Retrieves a post types
* [get\_post\_types()](../../functions/get_post_types)
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayOptional. Query arguments.
* `4`arrayOptional. Fields to fetch.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getPostTypes( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$filter = isset( $args[3] ) ? $args[3] : array( 'public' => true );
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
$fields = apply_filters( 'xmlrpc_default_posttype_fields', array( 'labels', 'cap', 'taxonomies' ), 'wp.getPostTypes' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPostTypes', $args, $this );
$post_types = get_post_types( $filter, 'objects' );
$struct = array();
foreach ( $post_types as $post_type ) {
if ( ! current_user_can( $post_type->cap->edit_posts ) ) {
continue;
}
$struct[ $post_type->name ] = $this->_prepare_post_type( $post_type, $fields );
}
return $struct;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[apply\_filters( 'xmlrpc\_default\_posttype\_fields', array $fields, string $method )](../../hooks/xmlrpc_default_posttype_fields)
Filters the default query fields used by the given XML-RPC method.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [wp\_xmlrpc\_server::\_prepare\_post\_type()](_prepare_post_type) wp-includes/class-wp-xmlrpc-server.php | Prepares post data for return in an XML-RPC object. |
| [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. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wp_xmlrpc_server::_is_greater_than_one( int $count ): bool wp\_xmlrpc\_server::\_is\_greater\_than\_one( int $count ): 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.
Helper method for filtering out elements from an array.
`$count` int Required Number to compare to one. bool True if the number is greater than one, false otherwise.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
private function _is_greater_than_one( $count ) {
return $count > 1;
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wp_xmlrpc_server::_toggle_sticky( array $post_data, bool $update = false ): void|IXR_Error wp\_xmlrpc\_server::\_toggle\_sticky( array $post\_data, bool $update = false ): void|IXR\_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.
Encapsulate the logic for sticking a post and determining if the user has permission to do so
`$post_data` array Required `$update` bool Optional Default: `false`
void|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
private function _toggle_sticky( $post_data, $update = false ) {
$post_type = get_post_type_object( $post_data['post_type'] );
// Private and password-protected posts cannot be stickied.
if ( 'private' === $post_data['post_status'] || ! empty( $post_data['post_password'] ) ) {
// Error if the client tried to stick the post, otherwise, silently unstick.
if ( ! empty( $post_data['sticky'] ) ) {
return new IXR_Error( 401, __( 'Sorry, you cannot stick a private post.' ) );
}
if ( $update ) {
unstick_post( $post_data['ID'] );
}
} elseif ( isset( $post_data['sticky'] ) ) {
if ( ! current_user_can( $post_type->cap->edit_others_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to make posts sticky.' ) );
}
$sticky = wp_validate_boolean( $post_data['sticky'] );
if ( $sticky ) {
stick_post( $post_data['ID'] );
} else {
unstick_post( $post_data['ID'] );
}
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_validate\_boolean()](../../functions/wp_validate_boolean) wp-includes/functions.php | Filters/validates a variable as a boolean. |
| [unstick\_post()](../../functions/unstick_post) wp-includes/post.php | Un-sticks a post. |
| [stick\_post()](../../functions/stick_post) wp-includes/post.php | Makes a post sticky. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::mw\_editPost()](mw_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post. |
| [wp\_xmlrpc\_server::mw\_newPost()](mw_newpost) wp-includes/class-wp-xmlrpc-server.php | Create a new post. |
| [wp\_xmlrpc\_server::\_insert\_post()](_insert_post) wp-includes/class-wp-xmlrpc-server.php | Helper method for wp\_newPost() and wp\_editPost(), containing shared logic. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::wp_getTerms( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getTerms( array $args ): array|IXR\_Error
=================================================================
Retrieve all terms for a taxonomy.
* [get\_terms()](../../functions/get_terms)
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`stringTaxonomy name.
* `4`arrayOptional. Modifies the query used to retrieve posts. Accepts `'number'`, `'offset'`, `'orderby'`, `'order'`, `'hide_empty'`, and `'search'`. Default empty array.
array|[IXR\_Error](../ixr_error) An associative array of terms data on success, [IXR\_Error](../ixr_error) instance otherwise.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getTerms( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$taxonomy = $args[3];
$filter = isset( $args[4] ) ? $args[4] : array();
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getTerms', $args, $this );
if ( ! taxonomy_exists( $taxonomy ) ) {
return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
}
$taxonomy = get_taxonomy( $taxonomy );
if ( ! current_user_can( $taxonomy->cap->assign_terms ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign terms in this taxonomy.' ) );
}
$query = array( 'taxonomy' => $taxonomy->name );
if ( isset( $filter['number'] ) ) {
$query['number'] = absint( $filter['number'] );
}
if ( isset( $filter['offset'] ) ) {
$query['offset'] = absint( $filter['offset'] );
}
if ( isset( $filter['orderby'] ) ) {
$query['orderby'] = $filter['orderby'];
if ( isset( $filter['order'] ) ) {
$query['order'] = $filter['order'];
}
}
if ( isset( $filter['hide_empty'] ) ) {
$query['hide_empty'] = $filter['hide_empty'];
} else {
$query['get'] = 'all';
}
if ( isset( $filter['search'] ) ) {
$query['search'] = $filter['search'];
}
$terms = get_terms( $query );
if ( is_wp_error( $terms ) ) {
return new IXR_Error( 500, $terms->get_error_message() );
}
$struct = array();
foreach ( $terms as $term ) {
$struct[] = $this->_prepare_term( $term );
}
return $struct;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [get\_terms()](../../functions/get_terms) wp-includes/taxonomy.php | Retrieves the terms in a given taxonomy or list of taxonomies. |
| [taxonomy\_exists()](../../functions/taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [wp\_xmlrpc\_server::\_prepare\_term()](_prepare_term) wp-includes/class-wp-xmlrpc-server.php | Prepares term data for return in an XML-RPC object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wp_xmlrpc_server::blogger_setTemplate( array $args ): IXR_Error wp\_xmlrpc\_server::blogger\_setTemplate( array $args ): IXR\_Error
===================================================================
This method has been deprecated.
Deprecated.
`$args` array Required Unused. [IXR\_Error](../ixr_error) Error object.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function blogger_setTemplate( $args ) {
return new IXR_Error( 403, __( 'Sorry, this method is not supported.' ) );
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | This method has been deprecated. |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::pingback_extensions_getPingbacks( string $url ): array|IXR_Error wp\_xmlrpc\_server::pingback\_extensions\_getPingbacks( string $url ): array|IXR\_Error
=======================================================================================
Retrieve array of URLs that pingbacked the given URL.
Specs on <http://www.aquarionics.com/misc/archives/blogite/0198.html>
`$url` string Required array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function pingback_extensions_getPingbacks( $url ) {
global $wpdb;
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'pingback.extensions.getPingbacks', $url, $this );
$url = $this->escape( $url );
$post_ID = url_to_postid( $url );
if ( ! $post_ID ) {
// We aren't sure that the resource is available and/or pingback enabled.
return $this->pingback_error( 33, __( 'The specified target URL cannot be used as a target. It either does not exist, or it is not a pingback-enabled resource.' ) );
}
$actual_post = get_post( $post_ID, ARRAY_A );
if ( ! $actual_post ) {
// No such post = resource not found.
return $this->pingback_error( 32, __( 'The specified target URL does not exist.' ) );
}
$comments = $wpdb->get_results( $wpdb->prepare( "SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = %d", $post_ID ) );
if ( ! $comments ) {
return array();
}
$pingbacks = array();
foreach ( $comments as $comment ) {
if ( 'pingback' === $comment->comment_type ) {
$pingbacks[] = $comment->comment_author_url;
}
}
return $pingbacks;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [url\_to\_postid()](../../functions/url_to_postid) wp-includes/rewrite.php | Examines a URL and try to determine the post ID it represents. |
| [wp\_xmlrpc\_server::pingback\_error()](pingback_error) wp-includes/class-wp-xmlrpc-server.php | Sends a pingback error based on the given error code and message. |
| [\_\_()](../../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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [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 |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::mw_newMediaObject( array $args ): array|IXR_Error wp\_xmlrpc\_server::mw\_newMediaObject( array $args ): array|IXR\_Error
=======================================================================
Uploads a file, following your settings.
Adapted from a patch by Johann Richard.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayData.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mw_newMediaObject( $args ) {
global $wpdb;
$username = $this->escape( $args[1] );
$password = $this->escape( $args[2] );
$data = $args[3];
$name = sanitize_file_name( $data['name'] );
$type = $data['type'];
$bits = $data['bits'];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'metaWeblog.newMediaObject', $args, $this );
if ( ! current_user_can( 'upload_files' ) ) {
$this->error = new IXR_Error( 401, __( 'Sorry, you are not allowed to upload files.' ) );
return $this->error;
}
if ( is_multisite() && upload_is_user_over_quota( false ) ) {
$this->error = new IXR_Error(
401,
sprintf(
/* translators: %s: Allowed space allocation. */
__( 'Sorry, you have used your space allocation of %s. Please delete some files to upload more files.' ),
size_format( get_space_allowed() * MB_IN_BYTES )
)
);
return $this->error;
}
/**
* Filters whether to preempt the XML-RPC media upload.
*
* Returning a truthy value will effectively short-circuit the media upload,
* returning that value as a 500 error instead.
*
* @since 2.1.0
*
* @param bool $error Whether to pre-empt the media upload. Default false.
*/
$upload_err = apply_filters( 'pre_upload_error', false );
if ( $upload_err ) {
return new IXR_Error( 500, $upload_err );
}
$upload = wp_upload_bits( $name, null, $bits );
if ( ! empty( $upload['error'] ) ) {
/* translators: 1: File name, 2: Error message. */
$errorString = sprintf( __( 'Could not write file %1$s (%2$s).' ), $name, $upload['error'] );
return new IXR_Error( 500, $errorString );
}
// Construct the attachment array.
$post_id = 0;
if ( ! empty( $data['post_id'] ) ) {
$post_id = (int) $data['post_id'];
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
}
$attachment = array(
'post_title' => $name,
'post_content' => '',
'post_type' => 'attachment',
'post_parent' => $post_id,
'post_mime_type' => $type,
'guid' => $upload['url'],
);
// Save the data.
$id = wp_insert_attachment( $attachment, $upload['file'], $post_id );
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );
/**
* Fires after a new attachment has been added via the XML-RPC MovableType API.
*
* @since 3.4.0
*
* @param int $id ID of the new attachment.
* @param array $args An array of arguments to add the attachment.
*/
do_action( 'xmlrpc_call_success_mw_newMediaObject', $id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
$struct = $this->_prepare_media_item( get_post( $id ) );
// Deprecated values.
$struct['id'] = $struct['attachment_id'];
$struct['file'] = $struct['title'];
$struct['url'] = $struct['link'];
return $struct;
}
```
[apply\_filters( 'pre\_upload\_error', bool $error )](../../hooks/pre_upload_error)
Filters whether to preempt the XML-RPC media upload.
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[do\_action( 'xmlrpc\_call\_success\_mw\_newMediaObject', int $id, array $args )](../../hooks/xmlrpc_call_success_mw_newmediaobject)
Fires after a new attachment has been added via the XML-RPC MovableType API.
| Uses | Description |
| --- | --- |
| [wp\_insert\_attachment()](../../functions/wp_insert_attachment) wp-includes/post.php | Inserts an attachment. |
| [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\_xmlrpc\_server::\_prepare\_media\_item()](_prepare_media_item) wp-includes/class-wp-xmlrpc-server.php | Prepares media item data for return in an XML-RPC object. |
| [sanitize\_file\_name()](../../functions/sanitize_file_name) wp-includes/formatting.php | Sanitizes a filename, replacing whitespace with dashes. |
| [get\_space\_allowed()](../../functions/get_space_allowed) wp-includes/ms-functions.php | Returns the upload quota for the current blog. |
| [wp\_upload\_bits()](../../functions/wp_upload_bits) wp-includes/functions.php | Creates a file in the upload folder with given content. |
| [size\_format()](../../functions/size_format) wp-includes/functions.php | Converts a number of bytes to the largest unit the bytes will fit into. |
| [upload\_is\_user\_over\_quota()](../../functions/upload_is_user_over_quota) wp-admin/includes/ms.php | Check whether a site has used its allotted upload space. |
| [wp\_update\_attachment\_metadata()](../../functions/wp_update_attachment_metadata) wp-includes/post.php | Updates metadata for an attachment. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [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\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [\_\_()](../../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. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getPosts( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getPosts( array $args ): array|IXR\_Error
=================================================================
Retrieve posts.
* [wp\_get\_recent\_posts()](../../functions/wp_get_recent_posts)
* [wp\_getPost()](../../functions/wp_getpost): for more on `$fields`
* [get\_posts()](../../functions/get_posts) : for more on `$filter` values
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayOptional. Modifies the query used to retrieve posts. Accepts `'post_type'`, `'post_status'`, `'number'`, `'offset'`, `'orderby'`, `'s'`, and `'order'`.
Default empty array.
* `4`arrayOptional. The subset of post type fields to return in the response array.
array|[IXR\_Error](../ixr_error) Array contains a collection of posts.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getPosts( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$filter = isset( $args[3] ) ? $args[3] : array();
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
$fields = apply_filters( 'xmlrpc_default_post_fields', array( 'post', 'terms', 'custom_fields' ), 'wp.getPosts' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPosts', $args, $this );
$query = array();
if ( isset( $filter['post_type'] ) ) {
$post_type = get_post_type_object( $filter['post_type'] );
if ( ! ( (bool) $post_type ) ) {
return new IXR_Error( 403, __( 'Invalid post type.' ) );
}
} else {
$post_type = get_post_type_object( 'post' );
}
if ( ! current_user_can( $post_type->cap->edit_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts in this post type.' ) );
}
$query['post_type'] = $post_type->name;
if ( isset( $filter['post_status'] ) ) {
$query['post_status'] = $filter['post_status'];
}
if ( isset( $filter['number'] ) ) {
$query['numberposts'] = absint( $filter['number'] );
}
if ( isset( $filter['offset'] ) ) {
$query['offset'] = absint( $filter['offset'] );
}
if ( isset( $filter['orderby'] ) ) {
$query['orderby'] = $filter['orderby'];
if ( isset( $filter['order'] ) ) {
$query['order'] = $filter['order'];
}
}
if ( isset( $filter['s'] ) ) {
$query['s'] = $filter['s'];
}
$posts_list = wp_get_recent_posts( $query );
if ( ! $posts_list ) {
return array();
}
// Holds all the posts data.
$struct = array();
foreach ( $posts_list as $post ) {
if ( ! current_user_can( 'edit_post', $post['ID'] ) ) {
continue;
}
$struct[] = $this->_prepare_post( $post, $fields );
}
return $struct;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[apply\_filters( 'xmlrpc\_default\_post\_fields', array $fields, string $method )](../../hooks/xmlrpc_default_post_fields)
Filters the list of post query fields used by the given XML-RPC method.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [wp\_get\_recent\_posts()](../../functions/wp_get_recent_posts) wp-includes/post.php | Retrieves a number of recent posts. |
| [wp\_xmlrpc\_server::\_prepare\_post()](_prepare_post) wp-includes/class-wp-xmlrpc-server.php | Prepares post data for return in an XML-RPC object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [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. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::mw_newPost( array $args ): int|IXR_Error wp\_xmlrpc\_server::mw\_newPost( array $args ): int|IXR\_Error
==============================================================
Create a new post.
The ‘content\_struct’ argument must contain:
* title
* description
* mt\_excerpt
* mt\_text\_more
* mt\_keywords
* mt\_tb\_ping\_urls
* categories
Also, it can optionally contain:
* wp\_slug
* wp\_password
* wp\_page\_parent\_id
* wp\_page\_order
* wp\_author\_id
* post\_status | page\_status – can be ‘draft’, ‘private’, ‘publish’, or ‘pending’
* mt\_allow\_comments – can be ‘open’ or ‘closed’
* mt\_allow\_pings – can be ‘open’ or ‘closed’
* date\_created\_gmt
* dateCreated
* wp\_post\_thumbnail
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayContent structure.
* `4`intOptional. Publish flag. 0 for draft, 1 for publish. Default 0.
int|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mw_newPost( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$content_struct = $args[3];
$publish = isset( $args[4] ) ? $args[4] : 0;
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'metaWeblog.newPost', $args, $this );
$page_template = '';
if ( ! empty( $content_struct['post_type'] ) ) {
if ( 'page' === $content_struct['post_type'] ) {
if ( $publish ) {
$cap = 'publish_pages';
} elseif ( isset( $content_struct['page_status'] ) && 'publish' === $content_struct['page_status'] ) {
$cap = 'publish_pages';
} else {
$cap = 'edit_pages';
}
$error_message = __( 'Sorry, you are not allowed to publish pages on this site.' );
$post_type = 'page';
if ( ! empty( $content_struct['wp_page_template'] ) ) {
$page_template = $content_struct['wp_page_template'];
}
} elseif ( 'post' === $content_struct['post_type'] ) {
if ( $publish ) {
$cap = 'publish_posts';
} elseif ( isset( $content_struct['post_status'] ) && 'publish' === $content_struct['post_status'] ) {
$cap = 'publish_posts';
} else {
$cap = 'edit_posts';
}
$error_message = __( 'Sorry, you are not allowed to publish posts on this site.' );
$post_type = 'post';
} else {
// No other 'post_type' values are allowed here.
return new IXR_Error( 401, __( 'Invalid post type.' ) );
}
} else {
if ( $publish ) {
$cap = 'publish_posts';
} elseif ( isset( $content_struct['post_status'] ) && 'publish' === $content_struct['post_status'] ) {
$cap = 'publish_posts';
} else {
$cap = 'edit_posts';
}
$error_message = __( 'Sorry, you are not allowed to publish posts on this site.' );
$post_type = 'post';
}
if ( ! current_user_can( get_post_type_object( $post_type )->cap->create_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish posts on this site.' ) );
}
if ( ! current_user_can( $cap ) ) {
return new IXR_Error( 401, $error_message );
}
// Check for a valid post format if one was given.
if ( isset( $content_struct['wp_post_format'] ) ) {
$content_struct['wp_post_format'] = sanitize_key( $content_struct['wp_post_format'] );
if ( ! array_key_exists( $content_struct['wp_post_format'], get_post_format_strings() ) ) {
return new IXR_Error( 404, __( 'Invalid post format.' ) );
}
}
// Let WordPress generate the 'post_name' (slug) unless
// one has been provided.
$post_name = null;
if ( isset( $content_struct['wp_slug'] ) ) {
$post_name = $content_struct['wp_slug'];
}
// Only use a password if one was given.
$post_password = '';
if ( isset( $content_struct['wp_password'] ) ) {
$post_password = $content_struct['wp_password'];
}
// Only set a post parent if one was given.
$post_parent = 0;
if ( isset( $content_struct['wp_page_parent_id'] ) ) {
$post_parent = $content_struct['wp_page_parent_id'];
}
// Only set the 'menu_order' if it was given.
$menu_order = 0;
if ( isset( $content_struct['wp_page_order'] ) ) {
$menu_order = $content_struct['wp_page_order'];
}
$post_author = $user->ID;
// If an author id was provided then use it instead.
if ( isset( $content_struct['wp_author_id'] ) && ( $user->ID != $content_struct['wp_author_id'] ) ) {
switch ( $post_type ) {
case 'post':
if ( ! current_user_can( 'edit_others_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to create posts as this user.' ) );
}
break;
case 'page':
if ( ! current_user_can( 'edit_others_pages' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to create pages as this user.' ) );
}
break;
default:
return new IXR_Error( 401, __( 'Invalid post type.' ) );
}
$author = get_userdata( $content_struct['wp_author_id'] );
if ( ! $author ) {
return new IXR_Error( 404, __( 'Invalid author ID.' ) );
}
$post_author = $content_struct['wp_author_id'];
}
$post_title = isset( $content_struct['title'] ) ? $content_struct['title'] : '';
$post_content = isset( $content_struct['description'] ) ? $content_struct['description'] : '';
$post_status = $publish ? 'publish' : 'draft';
if ( isset( $content_struct[ "{$post_type}_status" ] ) ) {
switch ( $content_struct[ "{$post_type}_status" ] ) {
case 'draft':
case 'pending':
case 'private':
case 'publish':
$post_status = $content_struct[ "{$post_type}_status" ];
break;
default:
// Deliberably left empty.
break;
}
}
$post_excerpt = isset( $content_struct['mt_excerpt'] ) ? $content_struct['mt_excerpt'] : '';
$post_more = isset( $content_struct['mt_text_more'] ) ? $content_struct['mt_text_more'] : '';
$tags_input = isset( $content_struct['mt_keywords'] ) ? $content_struct['mt_keywords'] : array();
if ( isset( $content_struct['mt_allow_comments'] ) ) {
if ( ! is_numeric( $content_struct['mt_allow_comments'] ) ) {
switch ( $content_struct['mt_allow_comments'] ) {
case 'closed':
$comment_status = 'closed';
break;
case 'open':
$comment_status = 'open';
break;
default:
$comment_status = get_default_comment_status( $post_type );
break;
}
} else {
switch ( (int) $content_struct['mt_allow_comments'] ) {
case 0:
case 2:
$comment_status = 'closed';
break;
case 1:
$comment_status = 'open';
break;
default:
$comment_status = get_default_comment_status( $post_type );
break;
}
}
} else {
$comment_status = get_default_comment_status( $post_type );
}
if ( isset( $content_struct['mt_allow_pings'] ) ) {
if ( ! is_numeric( $content_struct['mt_allow_pings'] ) ) {
switch ( $content_struct['mt_allow_pings'] ) {
case 'closed':
$ping_status = 'closed';
break;
case 'open':
$ping_status = 'open';
break;
default:
$ping_status = get_default_comment_status( $post_type, 'pingback' );
break;
}
} else {
switch ( (int) $content_struct['mt_allow_pings'] ) {
case 0:
$ping_status = 'closed';
break;
case 1:
$ping_status = 'open';
break;
default:
$ping_status = get_default_comment_status( $post_type, 'pingback' );
break;
}
}
} else {
$ping_status = get_default_comment_status( $post_type, 'pingback' );
}
if ( $post_more ) {
$post_content .= '<!--more-->' . $post_more;
}
$to_ping = '';
if ( isset( $content_struct['mt_tb_ping_urls'] ) ) {
$to_ping = $content_struct['mt_tb_ping_urls'];
if ( is_array( $to_ping ) ) {
$to_ping = implode( ' ', $to_ping );
}
}
// Do some timestamp voodoo.
if ( ! empty( $content_struct['date_created_gmt'] ) ) {
// We know this is supposed to be GMT, so we're going to slap that Z on there by force.
$dateCreated = rtrim( $content_struct['date_created_gmt']->getIso(), 'Z' ) . 'Z';
} elseif ( ! empty( $content_struct['dateCreated'] ) ) {
$dateCreated = $content_struct['dateCreated']->getIso();
}
$post_date = '';
$post_date_gmt = '';
if ( ! empty( $dateCreated ) ) {
$post_date = iso8601_to_datetime( $dateCreated );
$post_date_gmt = iso8601_to_datetime( $dateCreated, 'gmt' );
}
$post_category = array();
if ( isset( $content_struct['categories'] ) ) {
$catnames = $content_struct['categories'];
if ( is_array( $catnames ) ) {
foreach ( $catnames as $cat ) {
$post_category[] = get_cat_ID( $cat );
}
}
}
$postdata = compact( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'to_ping', 'post_type', 'post_name', 'post_password', 'post_parent', 'menu_order', 'tags_input', 'page_template' );
$post_ID = get_default_post_to_edit( $post_type, true )->ID;
$postdata['ID'] = $post_ID;
// Only posts can be sticky.
if ( 'post' === $post_type && isset( $content_struct['sticky'] ) ) {
$data = $postdata;
$data['sticky'] = $content_struct['sticky'];
$error = $this->_toggle_sticky( $data );
if ( $error ) {
return $error;
}
}
if ( isset( $content_struct['custom_fields'] ) ) {
$this->set_custom_fields( $post_ID, $content_struct['custom_fields'] );
}
if ( isset( $content_struct['wp_post_thumbnail'] ) ) {
if ( set_post_thumbnail( $post_ID, $content_struct['wp_post_thumbnail'] ) === false ) {
return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
}
unset( $content_struct['wp_post_thumbnail'] );
}
// Handle enclosures.
$thisEnclosure = isset( $content_struct['enclosure'] ) ? $content_struct['enclosure'] : null;
$this->add_enclosure_if_new( $post_ID, $thisEnclosure );
$this->attach_uploads( $post_ID, $post_content );
// Handle post formats if assigned, value is validated earlier
// in this function.
if ( isset( $content_struct['wp_post_format'] ) ) {
set_post_format( $post_ID, $content_struct['wp_post_format'] );
}
$post_ID = wp_insert_post( $postdata, true );
if ( is_wp_error( $post_ID ) ) {
return new IXR_Error( 500, $post_ID->get_error_message() );
}
if ( ! $post_ID ) {
return new IXR_Error( 500, __( 'Sorry, the post could not be created.' ) );
}
/**
* Fires after a new post has been successfully created via the XML-RPC MovableType API.
*
* @since 3.4.0
*
* @param int $post_ID ID of the new post.
* @param array $args An array of arguments to create the new post.
*/
do_action( 'xmlrpc_call_success_mw_newPost', $post_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return (string) $post_ID;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[do\_action( 'xmlrpc\_call\_success\_mw\_newPost', int $post\_ID, array $args )](../../hooks/xmlrpc_call_success_mw_newpost)
Fires after a new post has been successfully created via the XML-RPC MovableType API.
| Uses | Description |
| --- | --- |
| [set\_post\_thumbnail()](../../functions/set_post_thumbnail) wp-includes/post.php | Sets the post thumbnail (featured image) for the given post. |
| [get\_post\_format\_strings()](../../functions/get_post_format_strings) wp-includes/post-formats.php | Returns an array of post format slugs to their translated and pretty display versions |
| [get\_default\_comment\_status()](../../functions/get_default_comment_status) wp-includes/comment.php | Gets the default comment status for a post type. |
| [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. |
| [wp\_xmlrpc\_server::set\_custom\_fields()](set_custom_fields) wp-includes/class-wp-xmlrpc-server.php | Set custom fields for post. |
| [iso8601\_to\_datetime()](../../functions/iso8601_to_datetime) wp-includes/formatting.php | Given an ISO 8601 (Ymd\TH:i:sO) date, returns a MySQL DateTime (Y-m-d H:i:s) format used by post\_date[\_gmt]. |
| [wp\_xmlrpc\_server::attach\_uploads()](attach_uploads) wp-includes/class-wp-xmlrpc-server.php | Attach upload to a post. |
| [get\_cat\_ID()](../../functions/get_cat_id) wp-includes/category.php | Retrieves the ID of a category from its name. |
| [wp\_xmlrpc\_server::add\_enclosure\_if\_new()](add_enclosure_if_new) wp-includes/class-wp-xmlrpc-server.php | Adds an enclosure to a post if it’s new. |
| [wp\_xmlrpc\_server::\_toggle\_sticky()](_toggle_sticky) wp-includes/class-wp-xmlrpc-server.php | Encapsulate the logic for sticking a post and determining if the user has permission to do so |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [set\_post\_format()](../../functions/set_post_format) wp-includes/post-formats.php | Assign a format to a post |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_userdata()](../../functions/get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [sanitize\_key()](../../functions/sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [\_\_()](../../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. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::wp\_newPage()](wp_newpage) wp-includes/class-wp-xmlrpc-server.php | Create new page. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getProfile( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getProfile( array $args ): array|IXR\_Error
===================================================================
Retrieve information about the requesting user.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername
* `2`stringPassword
* `3`arrayOptional. Fields to return.
array|[IXR\_Error](../ixr_error) (@see wp\_getUser)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getProfile( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
if ( isset( $args[3] ) ) {
$fields = $args[3];
} else {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
$fields = apply_filters( 'xmlrpc_default_user_fields', array( 'all' ), 'wp.getProfile' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getProfile', $args, $this );
if ( ! current_user_can( 'edit_user', $user->ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit your profile.' ) );
}
$user_data = get_userdata( $user->ID );
return $this->_prepare_user( $user_data, $fields );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[apply\_filters( 'xmlrpc\_default\_user\_fields', array $fields, string $method )](../../hooks/xmlrpc_default_user_fields)
Filters the default user query fields used by the given XML-RPC method.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_prepare\_user()](_prepare_user) wp-includes/class-wp-xmlrpc-server.php | Prepares user data for return in an XML-RPC object. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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\_userdata()](../../functions/get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
wordpress wp_xmlrpc_server::wp_getCommentCount( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getCommentCount( array $args ): array|IXR\_Error
========================================================================
Retrieve comment count.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intPost ID.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getCommentCount( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
$post = get_post( $post_id, ARRAY_A );
if ( empty( $post['ID'] ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details of this post.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getCommentCount', $args, $this );
$count = wp_count_comments( $post_id );
return array(
'approved' => $count->approved,
'awaiting_moderation' => $count->moderated,
'spam' => $count->spam,
'total_comments' => $count->total_comments,
);
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_count\_comments()](../../functions/wp_count_comments) wp-includes/comment.php | Retrieves the total comment counts for the whole site or a single post. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::wp_getPostStatusList( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getPostStatusList( array $args ): array|IXR\_Error
==========================================================================
Retrieve post statuses.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getPostStatusList( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPostStatusList', $args, $this );
return get_post_statuses();
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [get\_post\_statuses()](../../functions/get_post_statuses) wp-includes/post.php | Retrieves all of the WordPress supported post statuses. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::_convert_date_gmt( string $date_gmt, string $date ): IXR_Date wp\_xmlrpc\_server::\_convert\_date\_gmt( string $date\_gmt, string $date ): IXR\_Date
======================================================================================
Convert a WordPress GMT date string to an [IXR\_Date](../ixr_date) object.
`$date_gmt` string Required WordPress GMT date string. `$date` string Required Date string. [IXR\_Date](../ixr_date) [IXR\_Date](../ixr_date) object.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function _convert_date_gmt( $date_gmt, $date ) {
if ( '0000-00-00 00:00:00' !== $date && '0000-00-00 00:00:00' === $date_gmt ) {
return new IXR_Date( get_gmt_from_date( mysql2date( 'Y-m-d H:i:s', $date, false ), 'Ymd\TH:i:s' ) );
}
return $this->_convert_date( $date_gmt );
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Date::\_\_construct()](../ixr_date/__construct) wp-includes/IXR/class-IXR-date.php | PHP5 constructor. |
| [get\_gmt\_from\_date()](../../functions/get_gmt_from_date) wp-includes/formatting.php | Given a date in the timezone of the site, returns that date in UTC. |
| [mysql2date()](../../functions/mysql2date) wp-includes/functions.php | Converts given MySQL date string into a different format. |
| [wp\_xmlrpc\_server::\_convert\_date()](_convert_date) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress date string to an [IXR\_Date](../ixr_date) object. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::mw\_getPost()](mw_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve post. |
| [wp\_xmlrpc\_server::mw\_getRecentPosts()](mw_getrecentposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve list of recent posts. |
| [wp\_xmlrpc\_server::mt\_getRecentPostTitles()](mt_getrecentposttitles) wp-includes/class-wp-xmlrpc-server.php | Retrieve the post titles of recent posts. |
| [wp\_xmlrpc\_server::wp\_getPageList()](wp_getpagelist) wp-includes/class-wp-xmlrpc-server.php | Retrieve page list. |
| [wp\_xmlrpc\_server::\_prepare\_page()](_prepare_page) wp-includes/class-wp-xmlrpc-server.php | Prepares page data for return in an XML-RPC object. |
| [wp\_xmlrpc\_server::\_prepare\_comment()](_prepare_comment) wp-includes/class-wp-xmlrpc-server.php | Prepares comment data for return in an XML-RPC object. |
| [wp\_xmlrpc\_server::\_prepare\_post()](_prepare_post) wp-includes/class-wp-xmlrpc-server.php | Prepares post data for return in an XML-RPC object. |
| [wp\_xmlrpc\_server::\_prepare\_media\_item()](_prepare_media_item) wp-includes/class-wp-xmlrpc-server.php | Prepares media item data for return in an XML-RPC object. |
wordpress wp_xmlrpc_server::wp_getPostType( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getPostType( array $args ): array|IXR\_Error
====================================================================
Retrieves a post type
* [get\_post\_type\_object()](../../functions/get_post_type_object)
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`stringPost type name.
* `4`arrayOptional. Fields to fetch.
array|[IXR\_Error](../ixr_error) Array contains:
* `'labels'`
* `'description'`
* `'capability_type'`
* `'cap'`
* `'map_meta_cap'`
* `'hierarchical'`
* `'menu_position'`
* `'taxonomies'`
* `'supports'`
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getPostType( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post_type_name = $args[3];
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/**
* Filters the default query fields used by the given XML-RPC method.
*
* @since 3.4.0
*
* @param array $fields An array of post type query fields for the given method.
* @param string $method The method name.
*/
$fields = apply_filters( 'xmlrpc_default_posttype_fields', array( 'labels', 'cap', 'taxonomies' ), 'wp.getPostType' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPostType', $args, $this );
if ( ! post_type_exists( $post_type_name ) ) {
return new IXR_Error( 403, __( 'Invalid post type.' ) );
}
$post_type = get_post_type_object( $post_type_name );
if ( ! current_user_can( $post_type->cap->edit_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts in this post type.' ) );
}
return $this->_prepare_post_type( $post_type, $fields );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[apply\_filters( 'xmlrpc\_default\_posttype\_fields', array $fields, string $method )](../../hooks/xmlrpc_default_posttype_fields)
Filters the default query fields used by the given XML-RPC method.
| Uses | Description |
| --- | --- |
| [post\_type\_exists()](../../functions/post_type_exists) wp-includes/post.php | Determines whether a post type is registered. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [wp\_xmlrpc\_server::\_prepare\_post\_type()](_prepare_post_type) wp-includes/class-wp-xmlrpc-server.php | Prepares post data for return in an XML-RPC object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wp_xmlrpc_server::blogger_getUsersBlogs( array $args ): array|IXR_Error wp\_xmlrpc\_server::blogger\_getUsersBlogs( array $args ): array|IXR\_Error
===========================================================================
Retrieve blogs that user owns.
Will make more sense once we support multiple blogs.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function blogger_getUsersBlogs( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
if ( is_multisite() ) {
return $this->_multisite_getUsersBlogs( $args );
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.getUsersBlogs', $args, $this );
$is_admin = current_user_can( 'manage_options' );
$struct = array(
'isAdmin' => $is_admin,
'url' => get_option( 'home' ) . '/',
'blogid' => '1',
'blogName' => get_option( 'blogname' ),
'xmlrpc' => site_url( 'xmlrpc.php', 'rpc' ),
);
return array( $struct );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| 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\_xmlrpc\_server::\_multisite\_getUsersBlogs()](_multisite_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Private function for retrieving a users blogs for multisite setups |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::wp\_getUsersBlogs()](wp_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Retrieve the blogs of the user. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::__construct() wp\_xmlrpc\_server::\_\_construct()
===================================
Registers all of the XMLRPC methods that XMLRPC server understands.
Sets up server and method property. Passes XMLRPC methods through the [‘xmlrpc\_methods’](../../hooks/xmlrpc_methods) filter to allow plugins to extend or replace XML-RPC methods.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function __construct() {
$this->methods = array(
// WordPress API.
'wp.getUsersBlogs' => 'this:wp_getUsersBlogs',
'wp.newPost' => 'this:wp_newPost',
'wp.editPost' => 'this:wp_editPost',
'wp.deletePost' => 'this:wp_deletePost',
'wp.getPost' => 'this:wp_getPost',
'wp.getPosts' => 'this:wp_getPosts',
'wp.newTerm' => 'this:wp_newTerm',
'wp.editTerm' => 'this:wp_editTerm',
'wp.deleteTerm' => 'this:wp_deleteTerm',
'wp.getTerm' => 'this:wp_getTerm',
'wp.getTerms' => 'this:wp_getTerms',
'wp.getTaxonomy' => 'this:wp_getTaxonomy',
'wp.getTaxonomies' => 'this:wp_getTaxonomies',
'wp.getUser' => 'this:wp_getUser',
'wp.getUsers' => 'this:wp_getUsers',
'wp.getProfile' => 'this:wp_getProfile',
'wp.editProfile' => 'this:wp_editProfile',
'wp.getPage' => 'this:wp_getPage',
'wp.getPages' => 'this:wp_getPages',
'wp.newPage' => 'this:wp_newPage',
'wp.deletePage' => 'this:wp_deletePage',
'wp.editPage' => 'this:wp_editPage',
'wp.getPageList' => 'this:wp_getPageList',
'wp.getAuthors' => 'this:wp_getAuthors',
'wp.getCategories' => 'this:mw_getCategories', // Alias.
'wp.getTags' => 'this:wp_getTags',
'wp.newCategory' => 'this:wp_newCategory',
'wp.deleteCategory' => 'this:wp_deleteCategory',
'wp.suggestCategories' => 'this:wp_suggestCategories',
'wp.uploadFile' => 'this:mw_newMediaObject', // Alias.
'wp.deleteFile' => 'this:wp_deletePost', // Alias.
'wp.getCommentCount' => 'this:wp_getCommentCount',
'wp.getPostStatusList' => 'this:wp_getPostStatusList',
'wp.getPageStatusList' => 'this:wp_getPageStatusList',
'wp.getPageTemplates' => 'this:wp_getPageTemplates',
'wp.getOptions' => 'this:wp_getOptions',
'wp.setOptions' => 'this:wp_setOptions',
'wp.getComment' => 'this:wp_getComment',
'wp.getComments' => 'this:wp_getComments',
'wp.deleteComment' => 'this:wp_deleteComment',
'wp.editComment' => 'this:wp_editComment',
'wp.newComment' => 'this:wp_newComment',
'wp.getCommentStatusList' => 'this:wp_getCommentStatusList',
'wp.getMediaItem' => 'this:wp_getMediaItem',
'wp.getMediaLibrary' => 'this:wp_getMediaLibrary',
'wp.getPostFormats' => 'this:wp_getPostFormats',
'wp.getPostType' => 'this:wp_getPostType',
'wp.getPostTypes' => 'this:wp_getPostTypes',
'wp.getRevisions' => 'this:wp_getRevisions',
'wp.restoreRevision' => 'this:wp_restoreRevision',
// Blogger API.
'blogger.getUsersBlogs' => 'this:blogger_getUsersBlogs',
'blogger.getUserInfo' => 'this:blogger_getUserInfo',
'blogger.getPost' => 'this:blogger_getPost',
'blogger.getRecentPosts' => 'this:blogger_getRecentPosts',
'blogger.newPost' => 'this:blogger_newPost',
'blogger.editPost' => 'this:blogger_editPost',
'blogger.deletePost' => 'this:blogger_deletePost',
// MetaWeblog API (with MT extensions to structs).
'metaWeblog.newPost' => 'this:mw_newPost',
'metaWeblog.editPost' => 'this:mw_editPost',
'metaWeblog.getPost' => 'this:mw_getPost',
'metaWeblog.getRecentPosts' => 'this:mw_getRecentPosts',
'metaWeblog.getCategories' => 'this:mw_getCategories',
'metaWeblog.newMediaObject' => 'this:mw_newMediaObject',
// MetaWeblog API aliases for Blogger API.
// See http://www.xmlrpc.com/stories/storyReader$2460
'metaWeblog.deletePost' => 'this:blogger_deletePost',
'metaWeblog.getUsersBlogs' => 'this:blogger_getUsersBlogs',
// MovableType API.
'mt.getCategoryList' => 'this:mt_getCategoryList',
'mt.getRecentPostTitles' => 'this:mt_getRecentPostTitles',
'mt.getPostCategories' => 'this:mt_getPostCategories',
'mt.setPostCategories' => 'this:mt_setPostCategories',
'mt.supportedMethods' => 'this:mt_supportedMethods',
'mt.supportedTextFilters' => 'this:mt_supportedTextFilters',
'mt.getTrackbackPings' => 'this:mt_getTrackbackPings',
'mt.publishPost' => 'this:mt_publishPost',
// Pingback.
'pingback.ping' => 'this:pingback_ping',
'pingback.extensions.getPingbacks' => 'this:pingback_extensions_getPingbacks',
'demo.sayHello' => 'this:sayHello',
'demo.addTwoNumbers' => 'this:addTwoNumbers',
);
$this->initialise_blog_option_info();
/**
* Filters the methods exposed by the XML-RPC server.
*
* This filter can be used to add new methods, and remove built-in methods.
*
* @since 1.5.0
*
* @param string[] $methods An array of XML-RPC methods, keyed by their methodName.
*/
$this->methods = apply_filters( 'xmlrpc_methods', $this->methods );
$this->set_is_enabled();
}
```
[apply\_filters( 'xmlrpc\_methods', string[] $methods )](../../hooks/xmlrpc_methods)
Filters the methods exposed by the XML-RPC server.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::set\_is\_enabled()](set_is_enabled) wp-includes/class-wp-xmlrpc-server.php | Set wp\_xmlrpc\_server::$is\_enabled property. |
| [wp\_xmlrpc\_server::initialise\_blog\_option\_info()](initialise_blog_option_info) wp-includes/class-wp-xmlrpc-server.php | Set up blog options property. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::get_term_custom_fields( int $term_id ): array wp\_xmlrpc\_server::get\_term\_custom\_fields( int $term\_id ): array
=====================================================================
Retrieve custom fields for a term.
`$term_id` int Required Term ID. array Array of custom fields, if they exist.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function get_term_custom_fields( $term_id ) {
$term_id = (int) $term_id;
$custom_fields = array();
foreach ( (array) has_term_meta( $term_id ) as $meta ) {
if ( ! current_user_can( 'edit_term_meta', $term_id ) ) {
continue;
}
$custom_fields[] = array(
'id' => $meta['meta_id'],
'key' => $meta['meta_key'],
'value' => $meta['meta_value'],
);
}
return $custom_fields;
}
```
| Uses | Description |
| --- | --- |
| [has\_term\_meta()](../../functions/has_term_meta) wp-includes/taxonomy.php | Gets all meta data, including meta IDs, for the given term ID. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_prepare\_term()](_prepare_term) wp-includes/class-wp-xmlrpc-server.php | Prepares term data for return in an XML-RPC object. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::mw_getCategories( array $args ): array|IXR_Error wp\_xmlrpc\_server::mw\_getCategories( array $args ): array|IXR\_Error
======================================================================
Retrieve the list of categories on a given blog.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mw_getCategories( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view categories.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'metaWeblog.getCategories', $args, $this );
$categories_struct = array();
$cats = get_categories( array( 'get' => 'all' ) );
if ( $cats ) {
foreach ( $cats as $cat ) {
$struct = array();
$struct['categoryId'] = $cat->term_id;
$struct['parentId'] = $cat->parent;
$struct['description'] = $cat->name;
$struct['categoryDescription'] = $cat->description;
$struct['categoryName'] = $cat->name;
$struct['htmlUrl'] = esc_html( get_category_link( $cat->term_id ) );
$struct['rssUrl'] = esc_html( get_category_feed_link( $cat->term_id, 'rss2' ) );
$categories_struct[] = $struct;
}
}
return $categories_struct;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [get\_category\_link()](../../functions/get_category_link) wp-includes/category-template.php | Retrieves category link URL. |
| [get\_categories()](../../functions/get_categories) wp-includes/category.php | Retrieves a list of category objects. |
| [get\_category\_feed\_link()](../../functions/get_category_feed_link) wp-includes/link-template.php | Retrieves the feed link for a category. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::mt_supportedTextFilters() wp\_xmlrpc\_server::mt\_supportedTextFilters()
==============================================
Retrieve an empty array because we don’t support per-post text filters.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mt_supportedTextFilters() {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.supportedTextFilters', array(), $this );
/**
* Filters the MoveableType text filters list for XML-RPC.
*
* @since 2.2.0
*
* @param array $filters An array of text filters.
*/
return apply_filters( 'xmlrpc_text_filters', array() );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
[apply\_filters( 'xmlrpc\_text\_filters', array $filters )](../../hooks/xmlrpc_text_filters)
Filters the MoveableType text filters list for XML-RPC.
| Uses | Description |
| --- | --- |
| [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 |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getCommentStatusList( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getCommentStatusList( array $args ): array|IXR\_Error
=============================================================================
Retrieve all of the comment status.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getCommentStatusList( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'publish_posts' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getCommentStatusList', $args, $this );
return get_comment_statuses();
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [get\_comment\_statuses()](../../functions/get_comment_statuses) wp-includes/comment.php | Retrieves all of the WordPress supported comment statuses. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_editPost( array $args ): true|IXR_Error wp\_xmlrpc\_server::wp\_editPost( array $args ): true|IXR\_Error
================================================================
Edit a post for any registered post type.
The $content\_struct parameter only needs to contain fields that should be changed. All other fields will retain their existing values.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intPost ID.
* `4`arrayExtra content arguments.
true|[IXR\_Error](../ixr_error) True on success, [IXR\_Error](../ixr_error) on failure.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_editPost( $args ) {
if ( ! $this->minimum_args( $args, 5 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post_id = (int) $args[3];
$content_struct = $args[4];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.editPost', $args, $this );
$post = get_post( $post_id, ARRAY_A );
if ( empty( $post['ID'] ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( isset( $content_struct['if_not_modified_since'] ) ) {
// If the post has been modified since the date provided, return an error.
if ( mysql2date( 'U', $post['post_modified_gmt'] ) > $content_struct['if_not_modified_since']->getTimestamp() ) {
return new IXR_Error( 409, __( 'There is a revision of this post that is more recent.' ) );
}
}
// Convert the date field back to IXR form.
$post['post_date'] = $this->_convert_date( $post['post_date'] );
/*
* Ignore the existing GMT date if it is empty or a non-GMT date was supplied in $content_struct,
* since _insert_post() will ignore the non-GMT date if the GMT date is set.
*/
if ( '0000-00-00 00:00:00' === $post['post_date_gmt'] || isset( $content_struct['post_date'] ) ) {
unset( $post['post_date_gmt'] );
} else {
$post['post_date_gmt'] = $this->_convert_date( $post['post_date_gmt'] );
}
/*
* If the API client did not provide 'post_date', then we must not perpetuate the value that
* was stored in the database, or it will appear to be an intentional edit. Conveying it here
* as if it was coming from the API client will cause an otherwise zeroed out 'post_date_gmt'
* to get set with the value that was originally stored in the database when the draft was created.
*/
if ( ! isset( $content_struct['post_date'] ) ) {
unset( $post['post_date'] );
}
$this->escape( $post );
$merged_content_struct = array_merge( $post, $content_struct );
$retval = $this->_insert_post( $user, $merged_content_struct );
if ( $retval instanceof IXR_Error ) {
return $retval;
}
return true;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [mysql2date()](../../functions/mysql2date) wp-includes/functions.php | Converts given MySQL date string into a different format. |
| [wp\_xmlrpc\_server::\_insert\_post()](_insert_post) wp-includes/class-wp-xmlrpc-server.php | Helper method for wp\_newPost() and wp\_editPost(), containing shared logic. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [wp\_xmlrpc\_server::\_convert\_date()](_convert_date) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress date string to an [IXR\_Date](../ixr_date) object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [\_\_()](../../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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wp_xmlrpc_server::_prepare_taxonomy( WP_Taxonomy $taxonomy, array $fields ): array wp\_xmlrpc\_server::\_prepare\_taxonomy( WP\_Taxonomy $taxonomy, array $fields ): array
=======================================================================================
Prepares taxonomy data for return in an XML-RPC object.
`$taxonomy` [WP\_Taxonomy](../wp_taxonomy) Required The unprepared taxonomy data. `$fields` array Required The subset of taxonomy fields to return. array The prepared taxonomy data.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function _prepare_taxonomy( $taxonomy, $fields ) {
$_taxonomy = array(
'name' => $taxonomy->name,
'label' => $taxonomy->label,
'hierarchical' => (bool) $taxonomy->hierarchical,
'public' => (bool) $taxonomy->public,
'show_ui' => (bool) $taxonomy->show_ui,
'_builtin' => (bool) $taxonomy->_builtin,
);
if ( in_array( 'labels', $fields, true ) ) {
$_taxonomy['labels'] = (array) $taxonomy->labels;
}
if ( in_array( 'cap', $fields, true ) ) {
$_taxonomy['cap'] = (array) $taxonomy->cap;
}
if ( in_array( 'menu', $fields, true ) ) {
$_taxonomy['show_in_menu'] = (bool) $taxonomy->show_in_menu;
}
if ( in_array( 'object_type', $fields, true ) ) {
$_taxonomy['object_type'] = array_unique( (array) $taxonomy->object_type );
}
/**
* Filters XML-RPC-prepared data for the given taxonomy.
*
* @since 3.4.0
*
* @param array $_taxonomy An array of taxonomy data.
* @param WP_Taxonomy $taxonomy Taxonomy object.
* @param array $fields The subset of taxonomy fields to return.
*/
return apply_filters( 'xmlrpc_prepare_taxonomy', $_taxonomy, $taxonomy, $fields );
}
```
[apply\_filters( 'xmlrpc\_prepare\_taxonomy', array $\_taxonomy, WP\_Taxonomy $taxonomy, array $fields )](../../hooks/xmlrpc_prepare_taxonomy)
Filters XML-RPC-prepared data for the given taxonomy.
| 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\_xmlrpc\_server::wp\_getTaxonomy()](wp_gettaxonomy) wp-includes/class-wp-xmlrpc-server.php | Retrieve a taxonomy. |
| [wp\_xmlrpc\_server::wp\_getTaxonomies()](wp_gettaxonomies) wp-includes/class-wp-xmlrpc-server.php | Retrieve all taxonomies. |
wordpress wp_xmlrpc_server::_getOptions( array $options ): array wp\_xmlrpc\_server::\_getOptions( array $options ): array
=========================================================
Retrieve blog options value from list.
`$options` array Required Options to retrieve. array
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function _getOptions( $options ) {
$data = array();
$can_manage = current_user_can( 'manage_options' );
foreach ( $options as $option ) {
if ( array_key_exists( $option, $this->blog_options ) ) {
$data[ $option ] = $this->blog_options[ $option ];
// Is the value static or dynamic?
if ( isset( $data[ $option ]['option'] ) ) {
$data[ $option ]['value'] = get_option( $data[ $option ]['option'] );
unset( $data[ $option ]['option'] );
}
if ( ! $can_manage ) {
$data[ $option ]['readonly'] = true;
}
}
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [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. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::wp\_getOptions()](wp_getoptions) wp-includes/class-wp-xmlrpc-server.php | Retrieve blog options. |
| [wp\_xmlrpc\_server::wp\_setOptions()](wp_setoptions) wp-includes/class-wp-xmlrpc-server.php | Update blog options. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_editProfile( array $args ): true|IXR_Error wp\_xmlrpc\_server::wp\_editProfile( array $args ): true|IXR\_Error
===================================================================
Edit user’s profile.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayContent struct. It can optionally contain:
+ `'first_name'`
+ `'last_name'`
+ `'website'`
+ `'display_name'`
+ `'nickname'`
+ `'nicename'`
+ `'bio'`
true|[IXR\_Error](../ixr_error) True, on success.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_editProfile( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$content_struct = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.editProfile', $args, $this );
if ( ! current_user_can( 'edit_user', $user->ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit your profile.' ) );
}
// Holds data of the user.
$user_data = array();
$user_data['ID'] = $user->ID;
// Only set the user details if they were given.
if ( isset( $content_struct['first_name'] ) ) {
$user_data['first_name'] = $content_struct['first_name'];
}
if ( isset( $content_struct['last_name'] ) ) {
$user_data['last_name'] = $content_struct['last_name'];
}
if ( isset( $content_struct['url'] ) ) {
$user_data['user_url'] = $content_struct['url'];
}
if ( isset( $content_struct['display_name'] ) ) {
$user_data['display_name'] = $content_struct['display_name'];
}
if ( isset( $content_struct['nickname'] ) ) {
$user_data['nickname'] = $content_struct['nickname'];
}
if ( isset( $content_struct['nicename'] ) ) {
$user_data['user_nicename'] = $content_struct['nicename'];
}
if ( isset( $content_struct['bio'] ) ) {
$user_data['description'] = $content_struct['bio'];
}
$result = wp_update_user( $user_data );
if ( is_wp_error( $result ) ) {
return new IXR_Error( 500, $result->get_error_message() );
}
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, the user could not be updated.' ) );
}
return true;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_update\_user()](../../functions/wp_update_user) wp-includes/user.php | Updates a user in the database. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| programming_docs |
wordpress wp_xmlrpc_server::wp_getTerm( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getTerm( array $args ): array|IXR\_Error
================================================================
Retrieve a term.
* [get\_term()](../../functions/get_term)
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`stringTaxonomy name.
* `4`intTerm ID.
array|[IXR\_Error](../ixr_error) [IXR\_Error](../ixr_error) on failure, array on success, containing:
* `'term_id'`
* `'name'`
* `'slug'`
* `'term_group'`
* `'term_taxonomy_id'`
* `'taxonomy'`
* `'description'`
* `'parent'`
* `'count'`
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getTerm( $args ) {
if ( ! $this->minimum_args( $args, 5 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$taxonomy = $args[3];
$term_id = (int) $args[4];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getTerm', $args, $this );
if ( ! taxonomy_exists( $taxonomy ) ) {
return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
}
$taxonomy = get_taxonomy( $taxonomy );
$term = get_term( $term_id, $taxonomy->name, ARRAY_A );
if ( is_wp_error( $term ) ) {
return new IXR_Error( 500, $term->get_error_message() );
}
if ( ! $term ) {
return new IXR_Error( 404, __( 'Invalid term ID.' ) );
}
if ( ! current_user_can( 'assign_term', $term_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign this term.' ) );
}
return $this->_prepare_term( $term );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [taxonomy\_exists()](../../functions/taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [wp\_xmlrpc\_server::\_prepare\_term()](_prepare_term) wp-includes/class-wp-xmlrpc-server.php | Prepares term data for return in an XML-RPC object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wp_xmlrpc_server::wp_editPage( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_editPage( array $args ): array|IXR\_Error
=================================================================
Edit page.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`intPage ID.
* `2`stringUsername.
* `3`stringPassword.
* `4`stringContent.
* `5`intPublish flag. 0 for draft, 1 for publish.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_editPage( $args ) {
// Items will be escaped in mw_editPost().
$page_id = (int) $args[1];
$username = $args[2];
$password = $args[3];
$content = $args[4];
$publish = $args[5];
$escaped_username = $this->escape( $username );
$escaped_password = $this->escape( $password );
$user = $this->login( $escaped_username, $escaped_password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.editPage', $args, $this );
// Get the page data and make sure it is a page.
$actual_page = get_post( $page_id, ARRAY_A );
if ( ! $actual_page || ( 'page' !== $actual_page['post_type'] ) ) {
return new IXR_Error( 404, __( 'Sorry, no such page.' ) );
}
// Make sure the user is allowed to edit pages.
if ( ! current_user_can( 'edit_page', $page_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this page.' ) );
}
// Mark this as content for a page.
$content['post_type'] = 'page';
// Arrange args in the way mw_editPost() understands.
$args = array(
$page_id,
$username,
$password,
$content,
$publish,
);
// Let mw_editPost() do all of the heavy lifting.
return $this->mw_editPost( $args );
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::mw\_editPost()](mw_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
wordpress wp_xmlrpc_server::escape( string|array $data ): string|void wp\_xmlrpc\_server::escape( string|array $data ): string|void
=============================================================
Escape string or array of strings for database.
`$data` string|array Required Escape single string or array of strings. string|void Returns with string is passed, alters by-reference when array is passed.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function escape( &$data ) {
if ( ! is_array( $data ) ) {
return wp_slash( $data );
}
foreach ( $data as &$v ) {
if ( is_array( $v ) ) {
$this->escape( $v );
} elseif ( ! is_object( $v ) ) {
$v = wp_slash( $v );
}
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::mt\_getPostCategories()](mt_getpostcategories) wp-includes/class-wp-xmlrpc-server.php | Retrieve post categories. |
| [wp\_xmlrpc\_server::mt\_setPostCategories()](mt_setpostcategories) wp-includes/class-wp-xmlrpc-server.php | Sets categories for a post. |
| [wp\_xmlrpc\_server::mt\_publishPost()](mt_publishpost) wp-includes/class-wp-xmlrpc-server.php | Sets a post’s publish status to ‘publish’. |
| [wp\_xmlrpc\_server::pingback\_ping()](pingback_ping) wp-includes/class-wp-xmlrpc-server.php | Retrieves a pingback and registers it. |
| [wp\_xmlrpc\_server::pingback\_extensions\_getPingbacks()](pingback_extensions_getpingbacks) wp-includes/class-wp-xmlrpc-server.php | Retrieve array of URLs that pingbacked the given URL. |
| [wp\_xmlrpc\_server::mw\_editPost()](mw_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post. |
| [wp\_xmlrpc\_server::mw\_getPost()](mw_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve post. |
| [wp\_xmlrpc\_server::mw\_getRecentPosts()](mw_getrecentposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve list of recent posts. |
| [wp\_xmlrpc\_server::mw\_getCategories()](mw_getcategories) wp-includes/class-wp-xmlrpc-server.php | Retrieve the list of categories on a given blog. |
| [wp\_xmlrpc\_server::mw\_newMediaObject()](mw_newmediaobject) wp-includes/class-wp-xmlrpc-server.php | Uploads a file, following your settings. |
| [wp\_xmlrpc\_server::mt\_getRecentPostTitles()](mt_getrecentposttitles) wp-includes/class-wp-xmlrpc-server.php | Retrieve the post titles of recent posts. |
| [wp\_xmlrpc\_server::mt\_getCategoryList()](mt_getcategorylist) wp-includes/class-wp-xmlrpc-server.php | Retrieve list of all categories on blog. |
| [wp\_xmlrpc\_server::blogger\_getUserInfo()](blogger_getuserinfo) wp-includes/class-wp-xmlrpc-server.php | Retrieve user’s data. |
| [wp\_xmlrpc\_server::blogger\_getPost()](blogger_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve post. |
| [wp\_xmlrpc\_server::blogger\_getRecentPosts()](blogger_getrecentposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve list of recent posts. |
| [wp\_xmlrpc\_server::blogger\_newPost()](blogger_newpost) wp-includes/class-wp-xmlrpc-server.php | Creates new post. |
| [wp\_xmlrpc\_server::blogger\_editPost()](blogger_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post. |
| [wp\_xmlrpc\_server::blogger\_deletePost()](blogger_deletepost) wp-includes/class-wp-xmlrpc-server.php | Remove a post. |
| [wp\_xmlrpc\_server::mw\_newPost()](mw_newpost) wp-includes/class-wp-xmlrpc-server.php | Create a new post. |
| [wp\_xmlrpc\_server::wp\_getOptions()](wp_getoptions) wp-includes/class-wp-xmlrpc-server.php | Retrieve blog options. |
| [wp\_xmlrpc\_server::wp\_setOptions()](wp_setoptions) wp-includes/class-wp-xmlrpc-server.php | Update blog options. |
| [wp\_xmlrpc\_server::wp\_getMediaItem()](wp_getmediaitem) wp-includes/class-wp-xmlrpc-server.php | Retrieve a media item by ID |
| [wp\_xmlrpc\_server::wp\_getMediaLibrary()](wp_getmedialibrary) wp-includes/class-wp-xmlrpc-server.php | Retrieves a collection of media library items (or attachments) |
| [wp\_xmlrpc\_server::wp\_getPostFormats()](wp_getpostformats) wp-includes/class-wp-xmlrpc-server.php | Retrieves a list of post formats used by the site. |
| [wp\_xmlrpc\_server::wp\_getPostType()](wp_getposttype) wp-includes/class-wp-xmlrpc-server.php | Retrieves a post type |
| [wp\_xmlrpc\_server::wp\_getPostTypes()](wp_getposttypes) wp-includes/class-wp-xmlrpc-server.php | Retrieves a post types |
| [wp\_xmlrpc\_server::wp\_getRevisions()](wp_getrevisions) wp-includes/class-wp-xmlrpc-server.php | Retrieve revisions for a specific post. |
| [wp\_xmlrpc\_server::wp\_restoreRevision()](wp_restorerevision) wp-includes/class-wp-xmlrpc-server.php | Restore a post revision |
| [wp\_xmlrpc\_server::blogger\_getUsersBlogs()](blogger_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Retrieve blogs that user owns. |
| [wp\_xmlrpc\_server::wp\_getComments()](wp_getcomments) wp-includes/class-wp-xmlrpc-server.php | Retrieve comments. |
| [wp\_xmlrpc\_server::wp\_deleteComment()](wp_deletecomment) wp-includes/class-wp-xmlrpc-server.php | Delete a comment. |
| [wp\_xmlrpc\_server::wp\_editComment()](wp_editcomment) wp-includes/class-wp-xmlrpc-server.php | Edit comment. |
| [wp\_xmlrpc\_server::wp\_newComment()](wp_newcomment) wp-includes/class-wp-xmlrpc-server.php | Create new comment. |
| [wp\_xmlrpc\_server::wp\_getCommentStatusList()](wp_getcommentstatuslist) wp-includes/class-wp-xmlrpc-server.php | Retrieve all of the comment status. |
| [wp\_xmlrpc\_server::wp\_getCommentCount()](wp_getcommentcount) wp-includes/class-wp-xmlrpc-server.php | Retrieve comment count. |
| [wp\_xmlrpc\_server::wp\_getPostStatusList()](wp_getpoststatuslist) wp-includes/class-wp-xmlrpc-server.php | Retrieve post statuses. |
| [wp\_xmlrpc\_server::wp\_getPageStatusList()](wp_getpagestatuslist) wp-includes/class-wp-xmlrpc-server.php | Retrieve page statuses. |
| [wp\_xmlrpc\_server::wp\_getPageTemplates()](wp_getpagetemplates) wp-includes/class-wp-xmlrpc-server.php | Retrieve page templates. |
| [wp\_xmlrpc\_server::wp\_getPages()](wp_getpages) wp-includes/class-wp-xmlrpc-server.php | Retrieve Pages. |
| [wp\_xmlrpc\_server::wp\_newPage()](wp_newpage) wp-includes/class-wp-xmlrpc-server.php | Create new page. |
| [wp\_xmlrpc\_server::wp\_deletePage()](wp_deletepage) wp-includes/class-wp-xmlrpc-server.php | Delete page. |
| [wp\_xmlrpc\_server::wp\_editPage()](wp_editpage) wp-includes/class-wp-xmlrpc-server.php | Edit page. |
| [wp\_xmlrpc\_server::wp\_getPageList()](wp_getpagelist) wp-includes/class-wp-xmlrpc-server.php | Retrieve page list. |
| [wp\_xmlrpc\_server::wp\_getAuthors()](wp_getauthors) wp-includes/class-wp-xmlrpc-server.php | Retrieve authors list. |
| [wp\_xmlrpc\_server::wp\_getTags()](wp_gettags) wp-includes/class-wp-xmlrpc-server.php | Get list of all tags |
| [wp\_xmlrpc\_server::wp\_newCategory()](wp_newcategory) wp-includes/class-wp-xmlrpc-server.php | Create new category. |
| [wp\_xmlrpc\_server::wp\_deleteCategory()](wp_deletecategory) wp-includes/class-wp-xmlrpc-server.php | Remove category. |
| [wp\_xmlrpc\_server::wp\_suggestCategories()](wp_suggestcategories) wp-includes/class-wp-xmlrpc-server.php | Retrieve category list. |
| [wp\_xmlrpc\_server::wp\_getComment()](wp_getcomment) wp-includes/class-wp-xmlrpc-server.php | Retrieve comment. |
| [wp\_xmlrpc\_server::wp\_getPosts()](wp_getposts) wp-includes/class-wp-xmlrpc-server.php | Retrieve posts. |
| [wp\_xmlrpc\_server::wp\_newTerm()](wp_newterm) wp-includes/class-wp-xmlrpc-server.php | Create a new term. |
| [wp\_xmlrpc\_server::wp\_editTerm()](wp_editterm) wp-includes/class-wp-xmlrpc-server.php | Edit a term. |
| [wp\_xmlrpc\_server::wp\_deleteTerm()](wp_deleteterm) wp-includes/class-wp-xmlrpc-server.php | Delete a term. |
| [wp\_xmlrpc\_server::wp\_getTerm()](wp_getterm) wp-includes/class-wp-xmlrpc-server.php | Retrieve a term. |
| [wp\_xmlrpc\_server::wp\_getTerms()](wp_getterms) wp-includes/class-wp-xmlrpc-server.php | Retrieve all terms for a taxonomy. |
| [wp\_xmlrpc\_server::wp\_getTaxonomy()](wp_gettaxonomy) wp-includes/class-wp-xmlrpc-server.php | Retrieve a taxonomy. |
| [wp\_xmlrpc\_server::wp\_getTaxonomies()](wp_gettaxonomies) wp-includes/class-wp-xmlrpc-server.php | Retrieve all taxonomies. |
| [wp\_xmlrpc\_server::wp\_getUser()](wp_getuser) wp-includes/class-wp-xmlrpc-server.php | Retrieve a user. |
| [wp\_xmlrpc\_server::wp\_getUsers()](wp_getusers) wp-includes/class-wp-xmlrpc-server.php | Retrieve users. |
| [wp\_xmlrpc\_server::wp\_getProfile()](wp_getprofile) wp-includes/class-wp-xmlrpc-server.php | Retrieve information about the requesting user. |
| [wp\_xmlrpc\_server::wp\_editProfile()](wp_editprofile) wp-includes/class-wp-xmlrpc-server.php | Edit user’s profile. |
| [wp\_xmlrpc\_server::wp\_getPage()](wp_getpage) wp-includes/class-wp-xmlrpc-server.php | Retrieve page. |
| [wp\_xmlrpc\_server::wp\_newPost()](wp_newpost) wp-includes/class-wp-xmlrpc-server.php | Create a new post for any registered post type. |
| [wp\_xmlrpc\_server::wp\_editPost()](wp_editpost) wp-includes/class-wp-xmlrpc-server.php | Edit a post for any registered post type. |
| [wp\_xmlrpc\_server::wp\_deletePost()](wp_deletepost) wp-includes/class-wp-xmlrpc-server.php | Delete a post for any registered post type. |
| [wp\_xmlrpc\_server::wp\_getPost()](wp_getpost) wp-includes/class-wp-xmlrpc-server.php | Retrieve a post. |
| [wp\_xmlrpc\_server::wp\_getUsersBlogs()](wp_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Retrieve the blogs of the user. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| Version | Description |
| --- | --- |
| [1.5.2](https://developer.wordpress.org/reference/since/1.5.2/) | Introduced. |
wordpress wp_xmlrpc_server::wp_getPages( array $args ): array|IXR_Error wp\_xmlrpc\_server::wp\_getPages( array $args ): array|IXR\_Error
=================================================================
Retrieve Pages.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intOptional. Number of pages. Default 10.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_getPages( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$num_pages = isset( $args[3] ) ? (int) $args[3] : 10;
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_pages' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit pages.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPages', $args, $this );
$pages = get_posts(
array(
'post_type' => 'page',
'post_status' => 'any',
'numberposts' => $num_pages,
)
);
$num_pages = count( $pages );
// If we have pages, put together their info.
if ( $num_pages >= 1 ) {
$pages_struct = array();
foreach ( $pages as $page ) {
if ( current_user_can( 'edit_page', $page->ID ) ) {
$pages_struct[] = $this->_prepare_page( $page );
}
}
return $pages_struct;
}
return array();
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [get\_posts()](../../functions/get_posts) wp-includes/post.php | Retrieves an array of the latest posts, or posts matching the given criteria. |
| [wp\_xmlrpc\_server::\_prepare\_page()](_prepare_page) wp-includes/class-wp-xmlrpc-server.php | Prepares page data for return in an XML-RPC object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [2.2.0](https://developer.wordpress.org/reference/since/2.2.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::wp_newTerm( array $args ): int|IXR_Error wp\_xmlrpc\_server::wp\_newTerm( array $args ): int|IXR\_Error
==============================================================
Create a new term.
* [wp\_insert\_term()](../../functions/wp_insert_term)
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`arrayContent struct for adding a new term. The struct must contain the term `'name'` and `'taxonomy'`. Optional accepted values include `'parent'`, `'description'`, and `'slug'`.
int|[IXR\_Error](../ixr_error) The term ID on success, or an [IXR\_Error](../ixr_error) object on failure.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_newTerm( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$content_struct = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.newTerm', $args, $this );
if ( ! taxonomy_exists( $content_struct['taxonomy'] ) ) {
return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
}
$taxonomy = get_taxonomy( $content_struct['taxonomy'] );
if ( ! current_user_can( $taxonomy->cap->edit_terms ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to create terms in this taxonomy.' ) );
}
$taxonomy = (array) $taxonomy;
// Hold the data of the term.
$term_data = array();
$term_data['name'] = trim( $content_struct['name'] );
if ( empty( $term_data['name'] ) ) {
return new IXR_Error( 403, __( 'The term name cannot be empty.' ) );
}
if ( isset( $content_struct['parent'] ) ) {
if ( ! $taxonomy['hierarchical'] ) {
return new IXR_Error( 403, __( 'This taxonomy is not hierarchical.' ) );
}
$parent_term_id = (int) $content_struct['parent'];
$parent_term = get_term( $parent_term_id, $taxonomy['name'] );
if ( is_wp_error( $parent_term ) ) {
return new IXR_Error( 500, $parent_term->get_error_message() );
}
if ( ! $parent_term ) {
return new IXR_Error( 403, __( 'Parent term does not exist.' ) );
}
$term_data['parent'] = $content_struct['parent'];
}
if ( isset( $content_struct['description'] ) ) {
$term_data['description'] = $content_struct['description'];
}
if ( isset( $content_struct['slug'] ) ) {
$term_data['slug'] = $content_struct['slug'];
}
$term = wp_insert_term( $term_data['name'], $taxonomy['name'], $term_data );
if ( is_wp_error( $term ) ) {
return new IXR_Error( 500, $term->get_error_message() );
}
if ( ! $term ) {
return new IXR_Error( 500, __( 'Sorry, the term could not be created.' ) );
}
// Add term meta.
if ( isset( $content_struct['custom_fields'] ) ) {
$this->set_term_custom_fields( $term['term_id'], $content_struct['custom_fields'] );
}
return (string) $term['term_id'];
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::set\_term\_custom\_fields()](set_term_custom_fields) wp-includes/class-wp-xmlrpc-server.php | Set custom fields for a term. |
| [wp\_insert\_term()](../../functions/wp_insert_term) wp-includes/taxonomy.php | Adds a new term to the database. |
| [taxonomy\_exists()](../../functions/taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wp_xmlrpc_server::set_term_custom_fields( int $term_id, array $fields ) wp\_xmlrpc\_server::set\_term\_custom\_fields( int $term\_id, array $fields )
=============================================================================
Set custom fields for a term.
`$term_id` int Required Term ID. `$fields` array Required Custom fields. File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function set_term_custom_fields( $term_id, $fields ) {
$term_id = (int) $term_id;
foreach ( (array) $fields as $meta ) {
if ( isset( $meta['id'] ) ) {
$meta['id'] = (int) $meta['id'];
$pmeta = get_metadata_by_mid( 'term', $meta['id'] );
if ( isset( $meta['key'] ) ) {
$meta['key'] = wp_unslash( $meta['key'] );
if ( $meta['key'] !== $pmeta->meta_key ) {
continue;
}
$meta['value'] = wp_unslash( $meta['value'] );
if ( current_user_can( 'edit_term_meta', $term_id ) ) {
update_metadata_by_mid( 'term', $meta['id'], $meta['value'] );
}
} elseif ( current_user_can( 'delete_term_meta', $term_id ) ) {
delete_metadata_by_mid( 'term', $meta['id'] );
}
} elseif ( current_user_can( 'add_term_meta', $term_id ) ) {
add_term_meta( $term_id, $meta['key'], $meta['value'] );
}
}
}
```
| Uses | Description |
| --- | --- |
| [add\_term\_meta()](../../functions/add_term_meta) wp-includes/taxonomy.php | Adds metadata to a term. |
| [get\_metadata\_by\_mid()](../../functions/get_metadata_by_mid) wp-includes/meta.php | Retrieves metadata by meta ID. |
| [update\_metadata\_by\_mid()](../../functions/update_metadata_by_mid) wp-includes/meta.php | Updates metadata by meta ID. |
| [delete\_metadata\_by\_mid()](../../functions/delete_metadata_by_mid) wp-includes/meta.php | Deletes metadata by meta ID. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::wp\_newTerm()](wp_newterm) wp-includes/class-wp-xmlrpc-server.php | Create a new term. |
| [wp\_xmlrpc\_server::wp\_editTerm()](wp_editterm) wp-includes/class-wp-xmlrpc-server.php | Edit a term. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress wp_xmlrpc_server::error( IXR_Error|string $error, false $message = false ) wp\_xmlrpc\_server::error( IXR\_Error|string $error, false $message = false )
=============================================================================
Send error response to client.
Send an XML error response to the client. If the endpoint is enabled an HTTP 200 response is always sent per the XML-RPC specification.
`$error` [IXR\_Error](../ixr_error)|string Required Error code or an error object. `$message` false Optional Error message. Optional. Default: `false`
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function error( $error, $message = false ) {
// Accepts either an error object or an error code and message
if ( $message && ! is_object( $error ) ) {
$error = new IXR_Error( $error, $message );
}
if ( ! $this->is_enabled ) {
status_header( $error->code );
}
$this->output( $error->getXml() );
}
```
| Uses | Description |
| --- | --- |
| [status\_header()](../../functions/status_header) wp-includes/functions.php | Sets HTTP status header. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| Version | Description |
| --- | --- |
| [5.7.3](https://developer.wordpress.org/reference/since/5.7.3/) | Introduced. |
wordpress wp_xmlrpc_server::mw_getRecentPosts( array $args ): array|IXR_Error wp\_xmlrpc\_server::mw\_getRecentPosts( array $args ): array|IXR\_Error
=======================================================================
Retrieve list of recent posts.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`intOptional. Number of posts.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mw_getRecentPosts( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
if ( isset( $args[3] ) ) {
$query = array( 'numberposts' => absint( $args[3] ) );
} else {
$query = array();
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'metaWeblog.getRecentPosts', $args, $this );
$posts_list = wp_get_recent_posts( $query );
if ( ! $posts_list ) {
return array();
}
$recent_posts = array();
foreach ( $posts_list as $entry ) {
if ( ! current_user_can( 'edit_post', $entry['ID'] ) ) {
continue;
}
$post_date = $this->_convert_date( $entry['post_date'] );
$post_date_gmt = $this->_convert_date_gmt( $entry['post_date_gmt'], $entry['post_date'] );
$post_modified = $this->_convert_date( $entry['post_modified'] );
$post_modified_gmt = $this->_convert_date_gmt( $entry['post_modified_gmt'], $entry['post_modified'] );
$categories = array();
$catids = wp_get_post_categories( $entry['ID'] );
foreach ( $catids as $catid ) {
$categories[] = get_cat_name( $catid );
}
$tagnames = array();
$tags = wp_get_post_tags( $entry['ID'] );
if ( ! empty( $tags ) ) {
foreach ( $tags as $tag ) {
$tagnames[] = $tag->name;
}
$tagnames = implode( ', ', $tagnames );
} else {
$tagnames = '';
}
$post = get_extended( $entry['post_content'] );
$link = get_permalink( $entry['ID'] );
// Get the post author info.
$author = get_userdata( $entry['post_author'] );
$allow_comments = ( 'open' === $entry['comment_status'] ) ? 1 : 0;
$allow_pings = ( 'open' === $entry['ping_status'] ) ? 1 : 0;
// Consider future posts as published.
if ( 'future' === $entry['post_status'] ) {
$entry['post_status'] = 'publish';
}
// Get post format.
$post_format = get_post_format( $entry['ID'] );
if ( empty( $post_format ) ) {
$post_format = 'standard';
}
$recent_posts[] = array(
'dateCreated' => $post_date,
'userid' => $entry['post_author'],
'postid' => (string) $entry['ID'],
'description' => $post['main'],
'title' => $entry['post_title'],
'link' => $link,
'permaLink' => $link,
// Commented out because no other tool seems to use this.
// 'content' => $entry['post_content'],
'categories' => $categories,
'mt_excerpt' => $entry['post_excerpt'],
'mt_text_more' => $post['extended'],
'wp_more_text' => $post['more_text'],
'mt_allow_comments' => $allow_comments,
'mt_allow_pings' => $allow_pings,
'mt_keywords' => $tagnames,
'wp_slug' => $entry['post_name'],
'wp_password' => $entry['post_password'],
'wp_author_id' => (string) $author->ID,
'wp_author_display_name' => $author->display_name,
'date_created_gmt' => $post_date_gmt,
'post_status' => $entry['post_status'],
'custom_fields' => $this->get_custom_fields( $entry['ID'] ),
'wp_post_format' => $post_format,
'date_modified' => $post_modified,
'date_modified_gmt' => $post_modified_gmt,
'sticky' => ( 'post' === $entry['post_type'] && is_sticky( $entry['ID'] ) ),
'wp_post_thumbnail' => get_post_thumbnail_id( $entry['ID'] ),
);
}
return $recent_posts;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::get\_custom\_fields()](get_custom_fields) wp-includes/class-wp-xmlrpc-server.php | Retrieve custom fields for post. |
| [wp\_get\_recent\_posts()](../../functions/wp_get_recent_posts) wp-includes/post.php | Retrieves a number of recent posts. |
| [wp\_xmlrpc\_server::\_convert\_date\_gmt()](_convert_date_gmt) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress GMT date string to an [IXR\_Date](../ixr_date) object. |
| [wp\_xmlrpc\_server::\_convert\_date()](_convert_date) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress date string to an [IXR\_Date](../ixr_date) object. |
| [get\_post\_format()](../../functions/get_post_format) wp-includes/post-formats.php | Retrieve the format slug for a post |
| [get\_extended()](../../functions/get_extended) wp-includes/post.php | Gets extended entry info (`<!--more-->`). |
| [is\_sticky()](../../functions/is_sticky) wp-includes/post.php | Determines whether a post is sticky. |
| [wp\_get\_post\_tags()](../../functions/wp_get_post_tags) wp-includes/post.php | Retrieves the tags for a post. |
| [wp\_get\_post\_categories()](../../functions/wp_get_post_categories) wp-includes/post.php | Retrieves the list of categories for a post. |
| [get\_post\_thumbnail\_id()](../../functions/get_post_thumbnail_id) wp-includes/post-thumbnail-template.php | Retrieves the post thumbnail ID. |
| [get\_cat\_name()](../../functions/get_cat_name) wp-includes/category.php | Retrieves the name of a category from its ID. |
| [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. |
| [get\_permalink()](../../functions/get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [get\_userdata()](../../functions/get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::_prepare_user( WP_User $user, array $fields ): array wp\_xmlrpc\_server::\_prepare\_user( WP\_User $user, array $fields ): array
===========================================================================
Prepares user data for return in an XML-RPC object.
`$user` [WP\_User](../wp_user) Required The unprepared user object. `$fields` array Required The subset of user fields to return. array The prepared user data.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function _prepare_user( $user, $fields ) {
$_user = array( 'user_id' => (string) $user->ID );
$user_fields = array(
'username' => $user->user_login,
'first_name' => $user->user_firstname,
'last_name' => $user->user_lastname,
'registered' => $this->_convert_date( $user->user_registered ),
'bio' => $user->user_description,
'email' => $user->user_email,
'nickname' => $user->nickname,
'nicename' => $user->user_nicename,
'url' => $user->user_url,
'display_name' => $user->display_name,
'roles' => $user->roles,
);
if ( in_array( 'all', $fields, true ) ) {
$_user = array_merge( $_user, $user_fields );
} else {
if ( in_array( 'basic', $fields, true ) ) {
$basic_fields = array( 'username', 'email', 'registered', 'display_name', 'nicename' );
$fields = array_merge( $fields, $basic_fields );
}
$requested_fields = array_intersect_key( $user_fields, array_flip( $fields ) );
$_user = array_merge( $_user, $requested_fields );
}
/**
* Filters XML-RPC-prepared data for the given user.
*
* @since 3.5.0
*
* @param array $_user An array of user data.
* @param WP_User $user User object.
* @param array $fields An array of user fields.
*/
return apply_filters( 'xmlrpc_prepare_user', $_user, $user, $fields );
}
```
[apply\_filters( 'xmlrpc\_prepare\_user', array $\_user, WP\_User $user, array $fields )](../../hooks/xmlrpc_prepare_user)
Filters XML-RPC-prepared data for the given user.
| Uses | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_convert\_date()](_convert_date) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress date string to an [IXR\_Date](../ixr_date) object. |
| [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\_xmlrpc\_server::wp\_getUser()](wp_getuser) wp-includes/class-wp-xmlrpc-server.php | Retrieve a user. |
| [wp\_xmlrpc\_server::wp\_getUsers()](wp_getusers) wp-includes/class-wp-xmlrpc-server.php | Retrieve users. |
| [wp\_xmlrpc\_server::wp\_getProfile()](wp_getprofile) wp-includes/class-wp-xmlrpc-server.php | Retrieve information about the requesting user. |
wordpress wp_xmlrpc_server::wp_deleteTerm( array $args ): true|IXR_Error wp\_xmlrpc\_server::wp\_deleteTerm( array $args ): true|IXR\_Error
==================================================================
Delete a term.
* [wp\_delete\_term()](../../functions/wp_delete_term)
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
* `3`stringTaxonomy name.
* `4`intTerm ID.
true|[IXR\_Error](../ixr_error) True on success, [IXR\_Error](../ixr_error) instance on failure.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function wp_deleteTerm( $args ) {
if ( ! $this->minimum_args( $args, 5 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$taxonomy = $args[3];
$term_id = (int) $args[4];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.deleteTerm', $args, $this );
if ( ! taxonomy_exists( $taxonomy ) ) {
return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
}
$taxonomy = get_taxonomy( $taxonomy );
$term = get_term( $term_id, $taxonomy->name );
if ( is_wp_error( $term ) ) {
return new IXR_Error( 500, $term->get_error_message() );
}
if ( ! $term ) {
return new IXR_Error( 404, __( 'Invalid term ID.' ) );
}
if ( ! current_user_can( 'delete_term', $term_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this term.' ) );
}
$result = wp_delete_term( $term_id, $taxonomy->name );
if ( is_wp_error( $result ) ) {
return new IXR_Error( 500, $term->get_error_message() );
}
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, deleting the term failed.' ) );
}
return $result;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_delete\_term()](../../functions/wp_delete_term) wp-includes/taxonomy.php | Removes a term from the database. |
| [taxonomy\_exists()](../../functions/taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| [wp\_xmlrpc\_server::minimum\_args()](minimum_args) wp-includes/class-wp-xmlrpc-server.php | Checks if the method received at least the minimum number of arguments. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
| programming_docs |
wordpress wp_xmlrpc_server::mt_getCategoryList( array $args ): array|IXR_Error wp\_xmlrpc\_server::mt\_getCategoryList( array $args ): array|IXR\_Error
========================================================================
Retrieve list of all categories on blog.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function mt_getCategoryList( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view categories.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.getCategoryList', $args, $this );
$categories_struct = array();
$cats = get_categories(
array(
'hide_empty' => 0,
'hierarchical' => 0,
)
);
if ( $cats ) {
foreach ( $cats as $cat ) {
$struct = array();
$struct['categoryId'] = $cat->term_id;
$struct['categoryName'] = $cat->name;
$categories_struct[] = $struct;
}
}
return $categories_struct;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [get\_categories()](../../functions/get_categories) wp-includes/category.php | Retrieves a list of category objects. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wp_xmlrpc_server::_multisite_getUsersBlogs( array $args ): array|IXR_Error wp\_xmlrpc\_server::\_multisite\_getUsersBlogs( array $args ): array|IXR\_Error
===============================================================================
Private function for retrieving a users blogs for multisite setups
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* intBlog ID (unused).
* `1`stringUsername.
* `2`stringPassword.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
protected function _multisite_getUsersBlogs( $args ) {
$current_blog = get_site();
$domain = $current_blog->domain;
$path = $current_blog->path . 'xmlrpc.php';
$blogs = $this->wp_getUsersBlogs( $args );
if ( $blogs instanceof IXR_Error ) {
return $blogs;
}
if ( $_SERVER['HTTP_HOST'] == $domain && $_SERVER['REQUEST_URI'] == $path ) {
return $blogs;
} else {
foreach ( (array) $blogs as $blog ) {
if ( strpos( $blog['url'], $_SERVER['HTTP_HOST'] ) ) {
return array( $blog );
}
}
return array();
}
}
```
| Uses | Description |
| --- | --- |
| [get\_site()](../../functions/get_site) wp-includes/ms-site.php | Retrieves site data given a site ID or site object. |
| [wp\_xmlrpc\_server::wp\_getUsersBlogs()](wp_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Retrieve the blogs of the user. |
| Used By | Description |
| --- | --- |
| [wp\_xmlrpc\_server::\_\_call()](__call) wp-includes/class-wp-xmlrpc-server.php | Make private/protected methods readable for backward compatibility. |
| [wp\_xmlrpc\_server::blogger\_getUsersBlogs()](blogger_getusersblogs) wp-includes/class-wp-xmlrpc-server.php | Retrieve blogs that user owns. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wp_xmlrpc_server::blogger_getRecentPosts( array $args ): array|IXR_Error wp\_xmlrpc\_server::blogger\_getRecentPosts( array $args ): array|IXR\_Error
============================================================================
Retrieve list of recent posts.
`$args` array Required Method arguments. Note: arguments must be ordered as documented.
* stringApp key (unused).
* `1`intBlog ID (unused).
* `2`stringUsername.
* `3`stringPassword.
* `4`intOptional. Number of posts.
array|[IXR\_Error](../ixr_error)
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
public function blogger_getRecentPosts( $args ) {
$this->escape( $args );
// $args[0] = appkey - ignored.
$username = $args[2];
$password = $args[3];
if ( isset( $args[4] ) ) {
$query = array( 'numberposts' => absint( $args[4] ) );
} else {
$query = array();
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.getRecentPosts', $args, $this );
$posts_list = wp_get_recent_posts( $query );
if ( ! $posts_list ) {
$this->error = new IXR_Error( 500, __( 'Either there are no posts, or something went wrong.' ) );
return $this->error;
}
$recent_posts = array();
foreach ( $posts_list as $entry ) {
if ( ! current_user_can( 'edit_post', $entry['ID'] ) ) {
continue;
}
$post_date = $this->_convert_date( $entry['post_date'] );
$categories = implode( ',', wp_get_post_categories( $entry['ID'] ) );
$content = '<title>' . wp_unslash( $entry['post_title'] ) . '</title>';
$content .= '<category>' . $categories . '</category>';
$content .= wp_unslash( $entry['post_content'] );
$recent_posts[] = array(
'userid' => $entry['post_author'],
'dateCreated' => $post_date,
'content' => $content,
'postid' => (string) $entry['ID'],
);
}
return $recent_posts;
}
```
[do\_action( 'xmlrpc\_call', string $name, array|string $args, wp\_xmlrpc\_server $server )](../../hooks/xmlrpc_call)
Fires after the XML-RPC user has been authenticated but before the rest of the method logic begins.
| Uses | Description |
| --- | --- |
| [wp\_get\_recent\_posts()](../../functions/wp_get_recent_posts) wp-includes/post.php | Retrieves a number of recent posts. |
| [wp\_get\_post\_categories()](../../functions/wp_get_post_categories) wp-includes/post.php | Retrieves the list of categories for a post. |
| [wp\_xmlrpc\_server::\_convert\_date()](_convert_date) wp-includes/class-wp-xmlrpc-server.php | Convert a WordPress date string to an [IXR\_Date](../ixr_date) object. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| [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\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wp\_xmlrpc\_server::escape()](escape) wp-includes/class-wp-xmlrpc-server.php | Escape string or array of strings for database. |
| [wp\_xmlrpc\_server::login()](login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress WP_Widget_RSS::form( array $instance ) WP\_Widget\_RSS::form( array $instance )
========================================
Outputs the settings form for the RSS widget.
`$instance` array Required Current settings. File: `wp-includes/widgets/class-wp-widget-rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-rss.php/)
```
public function form( $instance ) {
if ( empty( $instance ) ) {
$instance = array(
'title' => '',
'url' => '',
'items' => 10,
'error' => false,
'show_summary' => 0,
'show_author' => 0,
'show_date' => 0,
);
}
$instance['number'] = $this->number;
wp_widget_rss_form( $instance );
}
```
| Uses | Description |
| --- | --- |
| [wp\_widget\_rss\_form()](../../functions/wp_widget_rss_form) wp-includes/widgets.php | Display RSS widget options form. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_RSS::update( array $new_instance, array $old_instance ): array WP\_Widget\_RSS::update( array $new\_instance, array $old\_instance ): array
============================================================================
Handles updating settings for the current RSS 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-rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-rss.php/)
```
public function update( $new_instance, $old_instance ) {
$testurl = ( isset( $new_instance['url'] ) && ( ! isset( $old_instance['url'] ) || ( $new_instance['url'] !== $old_instance['url'] ) ) );
return wp_widget_rss_process( $new_instance, $testurl );
}
```
| Uses | Description |
| --- | --- |
| [wp\_widget\_rss\_process()](../../functions/wp_widget_rss_process) wp-includes/widgets.php | Process RSS feed widget data and optionally retrieve feed items. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_RSS::__construct() WP\_Widget\_RSS::\_\_construct()
================================
Sets up a new RSS widget instance.
File: `wp-includes/widgets/class-wp-widget-rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-rss.php/)
```
public function __construct() {
$widget_ops = array(
'description' => __( 'Entries from any RSS or Atom feed.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
$control_ops = array(
'width' => 400,
'height' => 200,
);
parent::__construct( 'rss', __( 'RSS' ), $widget_ops, $control_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_RSS::widget( array $args, array $instance ) WP\_Widget\_RSS::widget( array $args, array $instance )
=======================================================
Outputs the content for the current RSS widget instance.
`$args` array Required Display arguments including `'before_title'`, `'after_title'`, `'before_widget'`, and `'after_widget'`. `$instance` array Required Settings for the current RSS widget instance. File: `wp-includes/widgets/class-wp-widget-rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-rss.php/)
```
public function widget( $args, $instance ) {
if ( isset( $instance['error'] ) && $instance['error'] ) {
return;
}
$url = ! empty( $instance['url'] ) ? $instance['url'] : '';
while ( ! empty( $url ) && stristr( $url, 'http' ) !== $url ) {
$url = substr( $url, 1 );
}
if ( empty( $url ) ) {
return;
}
// Self-URL destruction sequence.
if ( in_array( untrailingslashit( $url ), array( site_url(), home_url() ), true ) ) {
return;
}
$rss = fetch_feed( $url );
$title = $instance['title'];
$desc = '';
$link = '';
if ( ! is_wp_error( $rss ) ) {
$desc = esc_attr( strip_tags( html_entity_decode( $rss->get_description(), ENT_QUOTES, get_option( 'blog_charset' ) ) ) );
if ( empty( $title ) ) {
$title = strip_tags( $rss->get_title() );
}
$link = strip_tags( $rss->get_permalink() );
while ( ! empty( $link ) && stristr( $link, 'http' ) !== $link ) {
$link = substr( $link, 1 );
}
}
if ( empty( $title ) ) {
$title = ! empty( $desc ) ? $desc : __( 'Unknown Feed' );
}
/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
if ( $title ) {
$feed_link = '';
$feed_url = strip_tags( $url );
$feed_icon = includes_url( 'images/rss.png' );
$feed_link = sprintf(
'<a class="rsswidget rss-widget-feed" href="%1$s"><img class="rss-widget-icon" style="border:0" width="14" height="14" src="%2$s" alt="%3$s"%4$s /></a> ',
esc_url( $feed_url ),
esc_url( $feed_icon ),
esc_attr__( 'RSS' ),
( wp_lazy_loading_enabled( 'img', 'rss_widget_feed_icon' ) ? ' loading="lazy"' : '' )
);
/**
* Filters the classic RSS widget's feed icon link.
*
* Themes can remove the icon link by using `add_filter( 'rss_widget_feed_link', '__return_false' );`.
*
* @since 5.9.0
*
* @param string $feed_link HTML for link to RSS feed.
* @param array $instance Array of settings for the current widget.
*/
$feed_link = apply_filters( 'rss_widget_feed_link', $feed_link, $instance );
$title = $feed_link . '<a class="rsswidget rss-widget-title" href="' . esc_url( $link ) . '">' . esc_html( $title ) . '</a>';
}
echo $args['before_widget'];
if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
}
$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 : __( 'RSS Feed' );
echo '<nav aria-label="' . esc_attr( $aria_label ) . '">';
}
wp_widget_rss_output( $rss, $instance );
if ( 'html5' === $format ) {
echo '</nav>';
}
echo $args['after_widget'];
if ( ! is_wp_error( $rss ) ) {
$rss->__destruct();
}
unset( $rss );
}
```
[apply\_filters( 'navigation\_widgets\_format', string $format )](../../hooks/navigation_widgets_format)
Filters the HTML format of widgets with navigation links.
[apply\_filters( 'rss\_widget\_feed\_link', string $feed\_link, array $instance )](../../hooks/rss_widget_feed_link)
Filters the classic RSS widget’s feed icon link.
[apply\_filters( 'widget\_title', string $title, array $instance, mixed $id\_base )](../../hooks/widget_title)
Filters the widget title.
| Uses | Description |
| --- | --- |
| [wp\_lazy\_loading\_enabled()](../../functions/wp_lazy_loading_enabled) wp-includes/media.php | Determines whether to add the `loading` attribute to the specified tag in the specified context. |
| [esc\_attr\_\_()](../../functions/esc_attr__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in an attribute. |
| [untrailingslashit()](../../functions/untrailingslashit) wp-includes/formatting.php | Removes trailing forward slashes and backslashes if they exist. |
| [wp\_widget\_rss\_output()](../../functions/wp_widget_rss_output) wp-includes/widgets.php | Display the RSS entries in a list. |
| [includes\_url()](../../functions/includes_url) wp-includes/link-template.php | Retrieves the URL to the includes directory. |
| [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. |
| [fetch\_feed()](../../functions/fetch_feed) wp-includes/feed.php | Builds SimplePie object based on RSS or Atom feed from URL. |
| [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\_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. |
| [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. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress Plugin_Upgrader_Skin::after() Plugin\_Upgrader\_Skin::after()
===============================
Action to perform following a single plugin update.
File: `wp-admin/includes/class-plugin-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-plugin-upgrader-skin.php/)
```
public function after() {
$this->plugin = $this->upgrader->plugin_info();
if ( ! empty( $this->plugin ) && ! is_wp_error( $this->result ) && $this->plugin_active ) {
// Currently used only when JS is off for a single plugin update?
printf(
'<iframe title="%s" style="border:0;overflow:hidden" width="100%%" height="170" src="%s"></iframe>',
esc_attr__( 'Update progress' ),
wp_nonce_url( 'update.php?action=activate-plugin&networkwide=' . $this->plugin_network_active . '&plugin=' . urlencode( $this->plugin ), 'activate-plugin_' . $this->plugin )
);
}
$this->decrement_update_count( 'plugin' );
$update_actions = array(
'activate_plugin' => sprintf(
'<a href="%s" target="_parent">%s</a>',
wp_nonce_url( 'plugins.php?action=activate&plugin=' . urlencode( $this->plugin ), 'activate-plugin_' . $this->plugin ),
__( 'Activate Plugin' )
),
'plugins_page' => sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'plugins.php' ),
__( 'Go to Plugins page' )
),
);
if ( $this->plugin_active || ! $this->result || is_wp_error( $this->result ) || ! current_user_can( 'activate_plugin', $this->plugin ) ) {
unset( $update_actions['activate_plugin'] );
}
/**
* Filters the list of action links available following a single plugin update.
*
* @since 2.7.0
*
* @param string[] $update_actions Array of plugin action links.
* @param string $plugin Path to the plugin file relative to the plugins directory.
*/
$update_actions = apply_filters( 'update_plugin_complete_actions', $update_actions, $this->plugin );
if ( ! empty( $update_actions ) ) {
$this->feedback( implode( ' | ', (array) $update_actions ) );
}
}
```
[apply\_filters( 'update\_plugin\_complete\_actions', string[] $update\_actions, string $plugin )](../../hooks/update_plugin_complete_actions)
Filters the list of action links available following a single plugin update.
| 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. |
| [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. |
| [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\_nonce\_url()](../../functions/wp_nonce_url) wp-includes/functions.php | Retrieves URL with nonce added to URL query. |
| [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 |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress Plugin_Upgrader_Skin::__construct( array $args = array() ) Plugin\_Upgrader\_Skin::\_\_construct( array $args = array() )
==============================================================
Constructor.
Sets up the plugin upgrader skin.
`$args` array Optional The plugin upgrader skin arguments to override default options. Default: `array()`
File: `wp-admin/includes/class-plugin-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-plugin-upgrader-skin.php/)
```
public function __construct( $args = array() ) {
$defaults = array(
'url' => '',
'plugin' => '',
'nonce' => '',
'title' => __( 'Update Plugin' ),
);
$args = wp_parse_args( $args, $defaults );
$this->plugin = $args['plugin'];
$this->plugin_active = is_plugin_active( $this->plugin );
$this->plugin_network_active = is_plugin_active_for_network( $this->plugin );
parent::__construct( $args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Upgrader\_Skin::\_\_construct()](../wp_upgrader_skin/__construct) wp-admin/includes/class-wp-upgrader-skin.php | Constructor. |
| [is\_plugin\_active()](../../functions/is_plugin_active) wp-admin/includes/plugin.php | Determines whether a plugin is active. |
| [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. |
| [\_\_()](../../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 |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Locale_Switcher::is_switched(): bool WP\_Locale\_Switcher::is\_switched(): bool
==========================================
Whether [switch\_to\_locale()](../../functions/switch_to_locale) is in effect.
bool True if the locale has been switched, false otherwise.
File: `wp-includes/class-wp-locale-switcher.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale-switcher.php/)
```
public function is_switched() {
return ! empty( $this->locales );
}
```
| Used By | Description |
| --- | --- |
| [is\_locale\_switched()](../../functions/is_locale_switched) wp-includes/l10n.php | Determines whether [switch\_to\_locale()](../../functions/switch_to_locale) is in effect. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Locale_Switcher::init() WP\_Locale\_Switcher::init()
============================
Initializes the locale switcher.
Hooks into the [‘locale’](../../hooks/locale) filter to change the locale on the fly.
File: `wp-includes/class-wp-locale-switcher.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale-switcher.php/)
```
public function init() {
add_filter( 'locale', array( $this, 'filter_locale' ) );
}
```
| Uses | Description |
| --- | --- |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Locale_Switcher::restore_previous_locale(): string|false WP\_Locale\_Switcher::restore\_previous\_locale(): string|false
===============================================================
Restores the translations according to the previous locale.
string|false Locale on success, false on failure.
File: `wp-includes/class-wp-locale-switcher.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale-switcher.php/)
```
public function restore_previous_locale() {
$previous_locale = array_pop( $this->locales );
if ( null === $previous_locale ) {
// The stack is empty, bail.
return false;
}
$locale = end( $this->locales );
if ( ! $locale ) {
// There's nothing left in the stack: go back to the original locale.
$locale = $this->original_locale;
}
$this->change_locale( $locale );
/**
* Fires when the locale is restored to the previous one.
*
* @since 4.7.0
*
* @param string $locale The new locale.
* @param string $previous_locale The previous locale.
*/
do_action( 'restore_previous_locale', $locale, $previous_locale );
return $locale;
}
```
[do\_action( 'restore\_previous\_locale', string $locale, string $previous\_locale )](../../hooks/restore_previous_locale)
Fires when the locale is restored to the previous one.
| Uses | Description |
| --- | --- |
| [WP\_Locale\_Switcher::change\_locale()](change_locale) wp-includes/class-wp-locale-switcher.php | Changes the site’s locale to the given one. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [restore\_previous\_locale()](../../functions/restore_previous_locale) wp-includes/l10n.php | Restores the translations according to the previous locale. |
| [WP\_Locale\_Switcher::restore\_current\_locale()](restore_current_locale) wp-includes/class-wp-locale-switcher.php | Restores the translations according to the original locale. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Locale_Switcher::restore_current_locale(): string|false WP\_Locale\_Switcher::restore\_current\_locale(): string|false
==============================================================
Restores the translations according to the original locale.
string|false Locale on success, false on failure.
File: `wp-includes/class-wp-locale-switcher.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale-switcher.php/)
```
public function restore_current_locale() {
if ( empty( $this->locales ) ) {
return false;
}
$this->locales = array( $this->original_locale );
return $this->restore_previous_locale();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Locale\_Switcher::restore\_previous\_locale()](restore_previous_locale) wp-includes/class-wp-locale-switcher.php | Restores the translations according to the previous locale. |
| Used By | Description |
| --- | --- |
| [restore\_current\_locale()](../../functions/restore_current_locale) wp-includes/l10n.php | Restores the translations according to the original locale. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Locale_Switcher::change_locale( string $locale ) WP\_Locale\_Switcher::change\_locale( string $locale )
======================================================
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.
Changes the site’s locale to the given one.
Loads the translations, changes the global `$wp_locale` object and updates all post type labels.
`$locale` string Required The locale to change to. File: `wp-includes/class-wp-locale-switcher.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale-switcher.php/)
```
private function change_locale( $locale ) {
global $wp_locale;
$this->load_translations( $locale );
$wp_locale = new WP_Locale();
/**
* Fires when the locale is switched to or restored.
*
* @since 4.7.0
*
* @param string $locale The new locale.
*/
do_action( 'change_locale', $locale );
}
```
[do\_action( 'change\_locale', string $locale )](../../hooks/change_locale)
Fires when the locale is switched to or restored.
| Uses | Description |
| --- | --- |
| [WP\_Locale\_Switcher::load\_translations()](load_translations) wp-includes/class-wp-locale-switcher.php | Load translations for a given locale. |
| [WP\_Locale::\_\_construct()](../wp_locale/__construct) wp-includes/class-wp-locale.php | Constructor which calls helper methods to set up object variables. |
| [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\_Locale\_Switcher::switch\_to\_locale()](switch_to_locale) wp-includes/class-wp-locale-switcher.php | Switches the translations according to the given locale. |
| [WP\_Locale\_Switcher::restore\_previous\_locale()](restore_previous_locale) wp-includes/class-wp-locale-switcher.php | Restores the translations according to the previous locale. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Locale_Switcher::load_translations( string $locale ) WP\_Locale\_Switcher::load\_translations( string $locale )
==========================================================
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.
Load translations for a given locale.
When switching to a locale, translations for this locale must be loaded from scratch.
`$locale` string Required The locale to load translations for. File: `wp-includes/class-wp-locale-switcher.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale-switcher.php/)
```
private function load_translations( $locale ) {
global $l10n;
$domains = $l10n ? array_keys( $l10n ) : array();
load_default_textdomain( $locale );
foreach ( $domains as $domain ) {
// The default text domain is handled by `load_default_textdomain()`.
if ( 'default' === $domain ) {
continue;
}
// Unload current text domain but allow them to be reloaded
// after switching back or to another locale.
unload_textdomain( $domain, true );
get_translations_for_domain( $domain );
}
}
```
| Uses | Description |
| --- | --- |
| [get\_translations\_for\_domain()](../../functions/get_translations_for_domain) wp-includes/l10n.php | Returns the Translations instance for a text domain. |
| [load\_default\_textdomain()](../../functions/load_default_textdomain) wp-includes/l10n.php | Loads default translated strings based on locale. |
| [unload\_textdomain()](../../functions/unload_textdomain) wp-includes/l10n.php | Unloads translations for a text domain. |
| Used By | Description |
| --- | --- |
| [WP\_Locale\_Switcher::change\_locale()](change_locale) wp-includes/class-wp-locale-switcher.php | Changes the site’s locale to the given one. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Locale_Switcher::switch_to_locale( string $locale ): bool WP\_Locale\_Switcher::switch\_to\_locale( string $locale ): bool
================================================================
Switches the translations according to the given locale.
`$locale` string Required The locale to switch to. bool True on success, false on failure.
File: `wp-includes/class-wp-locale-switcher.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale-switcher.php/)
```
public function switch_to_locale( $locale ) {
$current_locale = determine_locale();
if ( $current_locale === $locale ) {
return false;
}
if ( ! in_array( $locale, $this->available_languages, true ) ) {
return false;
}
$this->locales[] = $locale;
$this->change_locale( $locale );
/**
* Fires when the locale is switched.
*
* @since 4.7.0
*
* @param string $locale The new locale.
*/
do_action( 'switch_locale', $locale );
return true;
}
```
[do\_action( 'switch\_locale', string $locale )](../../hooks/switch_locale)
Fires when the locale is switched.
| Uses | Description |
| --- | --- |
| [determine\_locale()](../../functions/determine_locale) wp-includes/l10n.php | Determines the current locale desired for the request. |
| [WP\_Locale\_Switcher::change\_locale()](change_locale) wp-includes/class-wp-locale-switcher.php | Changes the site’s locale to the given one. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [switch\_to\_locale()](../../functions/switch_to_locale) wp-includes/l10n.php | Switches the translations according to the given locale. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Locale_Switcher::__construct() WP\_Locale\_Switcher::\_\_construct()
=====================================
Constructor.
Stores the original locale as well as a list of all available languages.
File: `wp-includes/class-wp-locale-switcher.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale-switcher.php/)
```
public function __construct() {
$this->original_locale = determine_locale();
$this->available_languages = array_merge( array( 'en_US' ), get_available_languages() );
}
```
| Uses | Description |
| --- | --- |
| [determine\_locale()](../../functions/determine_locale) wp-includes/l10n.php | Determines the current locale desired for the request. |
| [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. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Locale_Switcher::filter_locale( string $locale ): string WP\_Locale\_Switcher::filter\_locale( string $locale ): string
==============================================================
Filters the locale of the WordPress installation.
`$locale` string Required The locale of the WordPress installation. string The locale currently being switched to.
File: `wp-includes/class-wp-locale-switcher.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale-switcher.php/)
```
public function filter_locale( $locale ) {
$switched_locale = end( $this->locales );
if ( $switched_locale ) {
return $switched_locale;
}
return $locale;
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Scripts::reset() WP\_Scripts::reset()
====================
Resets class properties.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function reset() {
$this->do_concat = false;
$this->print_code = '';
$this->concat = '';
$this->concat_version = '';
$this->print_html = '';
$this->ext_version = '';
$this->ext_handles = '';
}
```
| Used By | Description |
| --- | --- |
| [WP\_Scripts::do\_item()](do_item) wp-includes/class-wp-scripts.php | Processes a script dependency. |
| [print\_head\_scripts()](../../functions/print_head_scripts) wp-includes/script-loader.php | Prints the script queue in the HTML head on admin pages. |
| [print\_footer\_scripts()](../../functions/print_footer_scripts) wp-includes/script-loader.php | Prints the scripts that were queued for the footer or too late for the HTML head. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Scripts::print_extra_script( string $handle, bool $display = true ): bool|string|void WP\_Scripts::print\_extra\_script( string $handle, bool $display = true ): bool|string|void
===========================================================================================
Prints extra scripts of a registered script.
`$handle` string Required The script's registered handle. `$display` bool Optional Whether to print the extra script instead of just returning it. Default: `true`
bool|string|void Void if no data exists, extra scripts if `$display` is true, true otherwise.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function print_extra_script( $handle, $display = true ) {
$output = $this->get_data( $handle, 'data' );
if ( ! $output ) {
return;
}
if ( ! $display ) {
return $output;
}
printf( "<script%s id='%s-js-extra'>\n", $this->type_attr, esc_attr( $handle ) );
// CDATA is not needed for HTML 5.
if ( $this->type_attr ) {
echo "/* <![CDATA[ */\n";
}
echo "$output\n";
if ( $this->type_attr ) {
echo "/* ]]> */\n";
}
echo "</script>\n";
return true;
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Used By | Description |
| --- | --- |
| [WP\_Scripts::print\_scripts\_l10n()](print_scripts_l10n) wp-includes/class-wp-scripts.php | Prints extra scripts of a registered script. |
| [WP\_Scripts::do\_item()](do_item) wp-includes/class-wp-scripts.php | Processes a script dependency. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_Scripts::print_scripts_l10n( string $handle, bool $display = true ): bool|string|void WP\_Scripts::print\_scripts\_l10n( string $handle, bool $display = true ): bool|string|void
===========================================================================================
This method has been deprecated. Use [print\_extra\_script()](../../functions/print_extra_script) instead.
Prints extra scripts of a registered script.
* [print\_extra\_script()](../../functions/print_extra_script)
`$handle` string Required The script's registered handle. `$display` bool Optional Whether to print the extra script instead of just returning it. Default: `true`
bool|string|void Void if no data exists, extra scripts if `$display` is true, true otherwise.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function print_scripts_l10n( $handle, $display = true ) {
_deprecated_function( __FUNCTION__, '3.3.0', 'WP_Scripts::print_extra_script()' );
return $this->print_extra_script( $handle, $display );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Scripts::print\_extra\_script()](print_extra_script) wp-includes/class-wp-scripts.php | Prints extra scripts of a registered script. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | This method has been deprecated. Use [print\_extra\_script()](../../functions/print_extra_script) instead. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Added the `$display` parameter. |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Scripts::init() WP\_Scripts::init()
===================
Initialize the class.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function init() {
if (
function_exists( 'is_admin' ) && ! is_admin()
&&
function_exists( 'current_theme_supports' ) && ! current_theme_supports( 'html5', 'script' )
) {
$this->type_attr = " type='text/javascript'";
}
/**
* Fires when the WP_Scripts instance is initialized.
*
* @since 2.6.0
*
* @param WP_Scripts $wp_scripts WP_Scripts instance (passed by reference).
*/
do_action_ref_array( 'wp_default_scripts', array( &$this ) );
}
```
[do\_action\_ref\_array( 'wp\_default\_scripts', WP\_Scripts $wp\_scripts )](../../hooks/wp_default_scripts)
Fires when the [WP\_Scripts](../wp_scripts) 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\_Scripts::\_\_construct()](__construct) wp-includes/class-wp-scripts.php | Constructor. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
| programming_docs |
wordpress WP_Scripts::add_inline_script( string $handle, string $data, string $position = 'after' ): bool WP\_Scripts::add\_inline\_script( string $handle, string $data, string $position = 'after' ): bool
==================================================================================================
Adds extra code to a registered script.
`$handle` string Required Name of the script to add the inline script to.
Must be lowercase. `$data` string Required String containing the JavaScript to be added. `$position` string Optional Whether to add the inline script before the handle or after. Default `'after'`. Default: `'after'`
bool True on success, false on failure.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function add_inline_script( $handle, $data, $position = 'after' ) {
if ( ! $data ) {
return false;
}
if ( 'after' !== $position ) {
$position = 'before';
}
$script = (array) $this->get_data( $handle, $position );
$script[] = $data;
return $this->add_data( $handle, $position, $script );
}
```
| Used By | Description |
| --- | --- |
| [wp\_tinymce\_inline\_scripts()](../../functions/wp_tinymce_inline_scripts) wp-includes/script-loader.php | Adds inline scripts required for the TinyMCE in the block editor. |
| [wp\_add\_inline\_script()](../../functions/wp_add_inline_script) wp-includes/functions.wp-scripts.php | Adds extra code to a registered script. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Scripts::in_default_dir( string $src ): bool WP\_Scripts::in\_default\_dir( string $src ): bool
==================================================
Whether a handle’s source is in a default directory.
`$src` string Required The source of the enqueued script. bool True if found, false if not.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function in_default_dir( $src ) {
if ( ! $this->default_dirs ) {
return true;
}
if ( 0 === strpos( $src, '/' . WPINC . '/js/l10n' ) ) {
return false;
}
foreach ( (array) $this->default_dirs as $test ) {
if ( 0 === strpos( $src, $test ) ) {
return true;
}
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Scripts::do\_item()](do_item) wp-includes/class-wp-scripts.php | Processes a script dependency. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Scripts::all_deps( string|string[] $handles, bool $recursion = false, int|false $group = false ): bool WP\_Scripts::all\_deps( string|string[] $handles, bool $recursion = false, int|false $group = false ): bool
===========================================================================================================
Determines script 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-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function all_deps( $handles, $recursion = false, $group = false ) {
$r = parent::all_deps( $handles, $recursion, $group );
if ( ! $recursion ) {
/**
* Filters the list of script dependencies left to print.
*
* @since 2.3.0
*
* @param string[] $to_do An array of script dependency handles.
*/
$this->to_do = apply_filters( 'print_scripts_array', $this->to_do );
}
return $r;
}
```
[apply\_filters( 'print\_scripts\_array', string[] $to\_do )](../../hooks/print_scripts_array)
Filters the list of script dependencies left to print.
| 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.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Scripts::do_item( string $handle, int|false $group = false ): bool WP\_Scripts::do\_item( string $handle, int|false $group = false ): bool
=======================================================================
Processes a script dependency.
* [WP\_Dependencies::do\_item()](../wp_dependencies/do_item)
`$handle` string Required The script'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-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function do_item( $handle, $group = false ) {
if ( ! parent::do_item( $handle ) ) {
return false;
}
if ( 0 === $group && $this->groups[ $handle ] > 0 ) {
$this->in_footer[] = $handle;
return false;
}
if ( false === $group && in_array( $handle, $this->in_footer, true ) ) {
$this->in_footer = array_diff( $this->in_footer, (array) $handle );
}
$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";
}
$before_handle = $this->print_inline_script( $handle, 'before', false );
$after_handle = $this->print_inline_script( $handle, 'after', false );
if ( $before_handle ) {
$before_handle = sprintf( "<script%s id='%s-js-before'>\n%s\n</script>\n", $this->type_attr, esc_attr( $handle ), $before_handle );
}
if ( $after_handle ) {
$after_handle = sprintf( "<script%s id='%s-js-after'>\n%s\n</script>\n", $this->type_attr, esc_attr( $handle ), $after_handle );
}
if ( $before_handle || $after_handle ) {
$inline_script_tag = $cond_before . $before_handle . $after_handle . $cond_after;
} else {
$inline_script_tag = '';
}
/*
* Prevent concatenation of scripts if the text domain is defined
* to ensure the dependency order is respected.
*/
$translations_stop_concat = ! empty( $obj->textdomain );
$translations = $this->print_translations( $handle, false );
if ( $translations ) {
$translations = sprintf( "<script%s id='%s-js-translations'>\n%s\n</script>\n", $this->type_attr, esc_attr( $handle ), $translations );
}
if ( $this->do_concat ) {
/**
* Filters the script loader source.
*
* @since 2.2.0
*
* @param string $src Script loader source path.
* @param string $handle Script handle.
*/
$srce = apply_filters( 'script_loader_src', $src, $handle );
if ( $this->in_default_dir( $srce ) && ( $before_handle || $after_handle || $translations_stop_concat ) ) {
$this->do_concat = false;
// Have to print the so-far concatenated scripts right away to maintain the right order.
_print_scripts();
$this->reset();
} elseif ( $this->in_default_dir( $srce ) && ! $conditional ) {
$this->print_code .= $this->print_extra_script( $handle, false );
$this->concat .= "$handle,";
$this->concat_version .= "$handle$ver";
return true;
} else {
$this->ext_handles .= "$handle,";
$this->ext_version .= "$handle$ver";
}
}
$has_conditional_data = $conditional && $this->get_data( $handle, 'data' );
if ( $has_conditional_data ) {
echo $cond_before;
}
$this->print_extra_script( $handle );
if ( $has_conditional_data ) {
echo $cond_after;
}
// A single item may alias a set of items, by having dependencies, but no source.
if ( ! $src ) {
if ( $inline_script_tag ) {
if ( $this->do_concat ) {
$this->print_html .= $inline_script_tag;
} else {
echo $inline_script_tag;
}
}
return true;
}
if ( ! 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 );
}
/** This filter is documented in wp-includes/class-wp-scripts.php */
$src = esc_url( apply_filters( 'script_loader_src', $src, $handle ) );
if ( ! $src ) {
return true;
}
$tag = $translations . $cond_before . $before_handle;
$tag .= sprintf( "<script%s src='%s' id='%s-js'></script>\n", $this->type_attr, $src, esc_attr( $handle ) );
$tag .= $after_handle . $cond_after;
/**
* Filters the HTML script tag of an enqueued script.
*
* @since 4.1.0
*
* @param string $tag The `<script>` tag for the enqueued script.
* @param string $handle The script's registered handle.
* @param string $src The script's source URL.
*/
$tag = apply_filters( 'script_loader_tag', $tag, $handle, $src );
if ( $this->do_concat ) {
$this->print_html .= $tag;
} else {
echo $tag;
}
return true;
}
```
[apply\_filters( 'script\_loader\_src', string $src, string $handle )](../../hooks/script_loader_src)
Filters the script loader source.
[apply\_filters( 'script\_loader\_tag', string $tag, string $handle, string $src )](../../hooks/script_loader_tag)
Filters the HTML script tag of an enqueued script.
| Uses | Description |
| --- | --- |
| [WP\_Scripts::print\_translations()](print_translations) wp-includes/class-wp-scripts.php | Prints translations set for a specific handle. |
| [WP\_Scripts::print\_inline\_script()](print_inline_script) wp-includes/class-wp-scripts.php | Prints inline scripts registered for a specific handle. |
| [WP\_Dependencies::do\_item()](../wp_dependencies/do_item) wp-includes/class-wp-dependencies.php | Processes a dependency. |
| [WP\_Scripts::in\_default\_dir()](in_default_dir) wp-includes/class-wp-scripts.php | Whether a handle’s source is in a default directory. |
| [WP\_Scripts::reset()](reset) wp-includes/class-wp-scripts.php | Resets class properties. |
| [WP\_Scripts::print\_extra\_script()](print_extra_script) wp-includes/class-wp-scripts.php | Prints extra scripts of a registered script. |
| [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. |
| [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/) | Added the `$group` parameter. |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress WP_Scripts::print_scripts( string|string[]|false $handles = false, int|false $group = false ): string[] WP\_Scripts::print\_scripts( string|string[]|false $handles = false, int|false $group = false ): string[]
=========================================================================================================
Prints scripts.
Prints the scripts passed to it or the print queue. Also prints all necessary dependencies.
`$handles` string|string[]|false Optional Scripts to be printed: queue (false), single script (string), or multiple scripts (array of strings).
Default: `false`
`$group` int|false Optional Group level: level (int), no groups (false).
Default: `false`
string[] Handles of scripts that have been printed.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function print_scripts( $handles = false, $group = false ) {
return $this->do_items( $handles, $group );
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Added the `$group` parameter. |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Scripts::set_translations( string $handle, string $domain = 'default', string $path = '' ): bool WP\_Scripts::set\_translations( string $handle, string $domain = 'default', string $path = '' ): bool
=====================================================================================================
Sets a translation textdomain.
`$handle` string Required Name of the script to register a translation domain to. `$domain` string Optional Text domain. Default `'default'`. Default: `'default'`
`$path` string Optional The full file path to the directory containing translation files. Default: `''`
bool True if the text domain was registered, false if not.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function set_translations( $handle, $domain = 'default', $path = '' ) {
if ( ! isset( $this->registered[ $handle ] ) ) {
return false;
}
/** @var \_WP_Dependency $obj */
$obj = $this->registered[ $handle ];
if ( ! in_array( 'wp-i18n', $obj->deps, true ) ) {
$obj->deps[] = 'wp-i18n';
}
return $obj->set_translations( $domain, $path );
}
```
| Used By | Description |
| --- | --- |
| [wp\_set\_script\_translations()](../../functions/wp_set_script_translations) wp-includes/functions.wp-scripts.php | Sets translated strings for a script. |
| Version | Description |
| --- | --- |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | The `$domain` parameter was made optional. |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_Scripts::print_inline_script( string $handle, string $position = 'after', bool $display = true ): string|false WP\_Scripts::print\_inline\_script( string $handle, string $position = 'after', bool $display = true ): string|false
====================================================================================================================
Prints inline scripts registered for a specific handle.
`$handle` string Required Name of the script to add the inline script to.
Must be lowercase. `$position` string Optional Whether to add the inline script before the handle or after. Default `'after'`. Default: `'after'`
`$display` bool Optional Whether to print the script instead of just returning it. Default: `true`
string|false Script on success, false otherwise.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function print_inline_script( $handle, $position = 'after', $display = true ) {
$output = $this->get_data( $handle, $position );
if ( empty( $output ) ) {
return false;
}
$output = trim( implode( "\n", $output ), "\n" );
if ( $display ) {
printf( "<script%s id='%s-js-%s'>\n%s\n</script>\n", $this->type_attr, esc_attr( $handle ), esc_attr( $position ), $output );
}
return $output;
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Used By | Description |
| --- | --- |
| [WP\_Scripts::do\_item()](do_item) wp-includes/class-wp-scripts.php | Processes a script dependency. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Scripts::do_footer_items(): string[] WP\_Scripts::do\_footer\_items(): string[]
==========================================
Processes items and dependencies for the footer group.
* [WP\_Dependencies::do\_items()](../wp_dependencies/do_items)
string[] Handles of items that have been processed.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function do_footer_items() {
$this->do_items( false, 1 );
return $this->done;
}
```
| Used By | Description |
| --- | --- |
| [print\_footer\_scripts()](../../functions/print_footer_scripts) wp-includes/script-loader.php | Prints the scripts that were queued for the footer or too late for the HTML head. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Scripts::do_head_items(): string[] WP\_Scripts::do\_head\_items(): string[]
========================================
Processes items and dependencies for the head group.
* [WP\_Dependencies::do\_items()](../wp_dependencies/do_items)
string[] Handles of items that have been processed.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function do_head_items() {
$this->do_items( false, 0 );
return $this->done;
}
```
| Used By | Description |
| --- | --- |
| [print\_head\_scripts()](../../functions/print_head_scripts) wp-includes/script-loader.php | Prints the script queue in the HTML head on admin pages. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Scripts::__construct() WP\_Scripts::\_\_construct()
============================
Constructor.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function __construct() {
$this->init();
add_action( 'init', array( $this, 'init' ), 0 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Scripts::init()](init) wp-includes/class-wp-scripts.php | Initialize the class. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Used By | Description |
| --- | --- |
| [wp\_scripts()](../../functions/wp_scripts) wp-includes/functions.wp-scripts.php | Initialize $wp\_scripts if it has not been set. |
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress WP_Scripts::print_translations( string $handle, bool $display = true ): string|false WP\_Scripts::print\_translations( string $handle, bool $display = true ): string|false
======================================================================================
Prints translations set for a specific handle.
`$handle` string Required Name of the script to add the inline script to.
Must be lowercase. `$display` bool Optional Whether to print the script instead of just returning it. Default: `true`
string|false Script on success, false otherwise.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function print_translations( $handle, $display = true ) {
if ( ! isset( $this->registered[ $handle ] ) || empty( $this->registered[ $handle ]->textdomain ) ) {
return false;
}
$domain = $this->registered[ $handle ]->textdomain;
$path = '';
if ( isset( $this->registered[ $handle ]->translations_path ) ) {
$path = $this->registered[ $handle ]->translations_path;
}
$json_translations = load_script_textdomain( $handle, $domain, $path );
if ( ! $json_translations ) {
return false;
}
$output = <<<JS
( function( domain, translations ) {
var localeData = translations.locale_data[ domain ] || translations.locale_data.messages;
localeData[""].domain = domain;
wp.i18n.setLocaleData( localeData, domain );
} )( "{$domain}", {$json_translations} );
JS;
if ( $display ) {
printf( "<script%s id='%s-js-translations'>\n%s\n</script>\n", $this->type_attr, esc_attr( $handle ), $output );
}
return $output;
}
```
| Uses | Description |
| --- | --- |
| [load\_script\_textdomain()](../../functions/load_script_textdomain) wp-includes/l10n.php | Loads the script translated strings. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Used By | Description |
| --- | --- |
| [WP\_Scripts::do\_item()](do_item) wp-includes/class-wp-scripts.php | Processes a script dependency. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
| programming_docs |
wordpress WP_Scripts::set_group( string $handle, bool $recursion, int|false $group = false ): bool WP\_Scripts::set\_group( string $handle, bool $recursion, int|false $group = false ): bool
==========================================================================================
Sets handle group.
* [WP\_Dependencies::set\_group()](../wp_dependencies/set_group)
`$handle` string Required Name of the item. Should be unique. `$recursion` bool Required Internal flag that calling function was called recursively. `$group` int|false Optional Group level: level (int), no groups (false).
Default: `false`
bool Not already in the group or a lower group.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function set_group( $handle, $recursion, $group = false ) {
if ( isset( $this->registered[ $handle ]->args ) && 1 === $this->registered[ $handle ]->args ) {
$grp = 1;
} else {
$grp = (int) $this->get_data( $handle, 'group' );
}
if ( false !== $group && $grp > $group ) {
$grp = $group;
}
return parent::set_group( $handle, $recursion, $grp );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Dependencies::set\_group()](../wp_dependencies/set_group) wp-includes/class-wp-dependencies.php | Set item group, unless already in a lower group. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Scripts::localize( string $handle, string $object_name, array $l10n ): bool WP\_Scripts::localize( string $handle, string $object\_name, array $l10n ): bool
================================================================================
Localizes a script, only if the script has already been added.
`$handle` string Required Name of the script to attach data to. `$object_name` string Required Name of the variable that will contain the data. `$l10n` array Required Array of data to localize. bool True on success, false on failure.
File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/)
```
public function localize( $handle, $object_name, $l10n ) {
if ( 'jquery' === $handle ) {
$handle = 'jquery-core';
}
if ( is_array( $l10n ) && isset( $l10n['l10n_print_after'] ) ) { // back compat, preserve the code in 'l10n_print_after' if present.
$after = $l10n['l10n_print_after'];
unset( $l10n['l10n_print_after'] );
}
if ( ! is_array( $l10n ) ) {
_doing_it_wrong(
__METHOD__,
sprintf(
/* translators: 1: $l10n, 2: wp_add_inline_script() */
__( 'The %1$s parameter must be an array. To pass arbitrary data to scripts, use the %2$s function instead.' ),
'<code>$l10n</code>',
'<code>wp_add_inline_script()</code>'
),
'5.7.0'
);
if ( false === $l10n ) {
// This should really not be needed, but is necessary for backward compatibility.
$l10n = array( $l10n );
}
}
if ( is_string( $l10n ) ) {
$l10n = html_entity_decode( $l10n, ENT_QUOTES, 'UTF-8' );
} elseif ( is_array( $l10n ) ) {
foreach ( $l10n as $key => $value ) {
if ( ! is_scalar( $value ) ) {
continue;
}
$l10n[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
}
}
$script = "var $object_name = " . wp_json_encode( $l10n ) . ';';
if ( ! empty( $after ) ) {
$script .= "\n$after;";
}
$data = $this->get_data( $handle, 'data' );
if ( ! empty( $data ) ) {
$script = "$data\n$script";
}
return $this->add_data( $handle, 'data', $script );
}
```
| Uses | Description |
| --- | --- |
| [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. |
| [\_doing\_it\_wrong()](../../functions/_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Used By | Description |
| --- | --- |
| [wp\_localize\_script()](../../functions/wp_localize_script) wp-includes/functions.wp-scripts.php | Localize a script. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Customize_Cropped_Image_Control::to_json() WP\_Customize\_Cropped\_Image\_Control::to\_json()
==================================================
Refresh the parameters passed to the JavaScript via JSON.
* [WP\_Customize\_Control::to\_json()](../wp_customize_control/to_json)
File: `wp-includes/customize/class-wp-customize-cropped-image-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-cropped-image-control.php/)
```
public function to_json() {
parent::to_json();
$this->json['width'] = absint( $this->width );
$this->json['height'] = absint( $this->height );
$this->json['flex_width'] = absint( $this->flex_width );
$this->json['flex_height'] = absint( $this->flex_height );
}
```
| Uses | Description |
| --- | --- |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Cropped_Image_Control::enqueue() WP\_Customize\_Cropped\_Image\_Control::enqueue()
=================================================
Enqueue control related scripts/styles.
File: `wp-includes/customize/class-wp-customize-cropped-image-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-cropped-image-control.php/)
```
public function enqueue() {
wp_enqueue_script( 'customize-views' );
parent::enqueue();
}
```
| Uses | Description |
| --- | --- |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Widget_Media::get_instance_schema(): array WP\_Widget\_Media::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.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
public function get_instance_schema() {
$schema = array(
'attachment_id' => array(
'type' => 'integer',
'default' => 0,
'minimum' => 0,
'description' => __( 'Attachment post ID' ),
'media_prop' => 'id',
),
'url' => array(
'type' => 'string',
'default' => '',
'format' => 'uri',
'description' => __( 'URL to the media file' ),
),
'title' => array(
'type' => 'string',
'default' => '',
'sanitize_callback' => 'sanitize_text_field',
'description' => __( 'Title for the widget' ),
'should_preview_update' => false,
),
);
/**
* Filters the media widget instance schema to add additional properties.
*
* @since 4.9.0
*
* @param array $schema Instance schema.
* @param WP_Widget_Media $widget Widget object.
*/
$schema = apply_filters( "widget_{$this->id_base}_instance_schema", $schema, $this );
return $schema;
}
```
[apply\_filters( "widget\_{$this->id\_base}\_instance\_schema", array $schema, WP\_Widget\_Media $widget )](../../hooks/widget_this-id_base_instance_schema)
Filters the media widget instance schema to add additional properties.
| Uses | Description |
| --- | --- |
| [\_\_()](../../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\_Widget\_Media\_Audio::get\_instance\_schema()](../wp_widget_media_audio/get_instance_schema) wp-includes/widgets/class-wp-widget-media-audio.php | Get schema for properties of a widget instance (item). |
| [WP\_Widget\_Media\_Video::get\_instance\_schema()](../wp_widget_media_video/get_instance_schema) wp-includes/widgets/class-wp-widget-media-video.php | Get schema for properties of a widget instance (item). |
| [WP\_Widget\_Media::form()](form) wp-includes/widgets/class-wp-widget-media.php | Outputs the settings update form. |
| [WP\_Widget\_Media::widget()](widget) wp-includes/widgets/class-wp-widget-media.php | Displays the widget on the front-end. |
| [WP\_Widget\_Media::update()](update) wp-includes/widgets/class-wp-widget-media.php | Sanitizes the widget form values as they are saved. |
| [WP\_Widget\_Media\_Image::get\_instance\_schema()](../wp_widget_media_image/get_instance_schema) wp-includes/widgets/class-wp-widget-media-image.php | Get schema for properties of a widget instance (item). |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media::has_content( array $instance ): bool WP\_Widget\_Media::has\_content( array $instance ): bool
========================================================
Whether the widget has content to show.
`$instance` array Required Widget instance props. bool Whether widget has content.
File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
protected function has_content( $instance ) {
return ( $instance['attachment_id'] && 'attachment' === get_post_type( $instance['attachment_id'] ) ) || $instance['url'];
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_type()](../../functions/get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Media::widget()](widget) wp-includes/widgets/class-wp-widget-media.php | Displays the widget on the front-end. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media::form( array $instance ) WP\_Widget\_Media::form( array $instance )
==========================================
Outputs the settings update form.
Note that the widget UI itself is rendered with JavaScript via `MediaWidgetControl#render()`.
* [WP\_Widget\_Media::render\_control\_template\_scripts()](../wp_widget_media/render_control_template_scripts): Where the JS template is located.
`$instance` array Required Current settings. File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
final public function form( $instance ) {
$instance_schema = $this->get_instance_schema();
$instance = wp_array_slice_assoc(
wp_parse_args( (array) $instance, wp_list_pluck( $instance_schema, 'default' ) ),
array_keys( $instance_schema )
);
foreach ( $instance as $name => $value ) : ?>
<input
type="hidden"
data-property="<?php echo esc_attr( $name ); ?>"
class="media-widget-instance-property"
name="<?php echo esc_attr( $this->get_field_name( $name ) ); ?>"
id="<?php echo esc_attr( $this->get_field_id( $name ) ); // Needed specifically by wpWidgets.appendTitle(). ?>"
value="<?php echo esc_attr( is_array( $value ) ? implode( ',', $value ) : (string) $value ); ?>"
/>
<?php
endforeach;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Media::get\_instance\_schema()](get_instance_schema) wp-includes/widgets/class-wp-widget-media.php | Get schema for properties of a widget instance (item). |
| [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\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [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 |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media::update( array $new_instance, array $old_instance ): array WP\_Widget\_Media::update( array $new\_instance, array $old\_instance ): array
==============================================================================
Sanitizes the widget form values as they are saved.
* [WP\_Widget::update()](../wp_widget/update)
* [WP\_REST\_Request::has\_valid\_params()](../wp_rest_request/has_valid_params)
* [WP\_REST\_Request::sanitize\_params()](../wp_rest_request/sanitize_params)
`$new_instance` array Required Values just sent to be saved. `$old_instance` array Required Previously saved values from database. array Updated safe values to be saved.
File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
public function update( $new_instance, $old_instance ) {
$schema = $this->get_instance_schema();
foreach ( $schema as $field => $field_schema ) {
if ( ! array_key_exists( $field, $new_instance ) ) {
continue;
}
$value = $new_instance[ $field ];
/*
* Workaround for rest_validate_value_from_schema() due to the fact that
* rest_is_boolean( '' ) === false, while rest_is_boolean( '1' ) is true.
*/
if ( 'boolean' === $field_schema['type'] && '' === $value ) {
$value = false;
}
if ( true !== rest_validate_value_from_schema( $value, $field_schema, $field ) ) {
continue;
}
$value = rest_sanitize_value_from_schema( $value, $field_schema );
// @codeCoverageIgnoreStart
if ( is_wp_error( $value ) ) {
continue; // Handle case when rest_sanitize_value_from_schema() ever returns WP_Error as its phpdoc @return tag indicates.
}
// @codeCoverageIgnoreEnd
if ( isset( $field_schema['sanitize_callback'] ) ) {
$value = call_user_func( $field_schema['sanitize_callback'], $value );
}
if ( is_wp_error( $value ) ) {
continue;
}
$old_instance[ $field ] = $value;
}
return $old_instance;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Media::get\_instance\_schema()](get_instance_schema) wp-includes/widgets/class-wp-widget-media.php | Get schema for properties of a widget instance (item). |
| [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 |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$instance` to `$old_instance` to match parent class for PHP 8 named parameter support. |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media::enqueue_admin_scripts() WP\_Widget\_Media::enqueue\_admin\_scripts()
============================================
Loads the required scripts and styles for the widget control.
File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
public function enqueue_admin_scripts() {
wp_enqueue_media();
wp_enqueue_script( 'media-widgets' );
}
```
| Uses | Description |
| --- | --- |
| [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. |
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Media\_Gallery::enqueue\_admin\_scripts()](../wp_widget_media_gallery/enqueue_admin_scripts) wp-includes/widgets/class-wp-widget-media-gallery.php | Loads the required media files for the media manager and scripts for media widgets. |
| [WP\_Widget\_Media\_Audio::enqueue\_admin\_scripts()](../wp_widget_media_audio/enqueue_admin_scripts) wp-includes/widgets/class-wp-widget-media-audio.php | Loads the required media files for the media manager and scripts for media widgets. |
| [WP\_Widget\_Media\_Video::enqueue\_admin\_scripts()](../wp_widget_media_video/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\_Image::enqueue\_admin\_scripts()](../wp_widget_media_image/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::is_attachment_with_mime_type( int|WP_Post $attachment, string $mime_type ): bool WP\_Widget\_Media::is\_attachment\_with\_mime\_type( int|WP\_Post $attachment, string $mime\_type ): bool
=========================================================================================================
Determine if the supplied attachment is for a valid attachment post with the specified MIME type.
`$attachment` int|[WP\_Post](../wp_post) Required Attachment post ID or object. `$mime_type` string Required MIME type. bool Is matching MIME type.
File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
public function is_attachment_with_mime_type( $attachment, $mime_type ) {
if ( empty( $attachment ) ) {
return false;
}
$attachment = get_post( $attachment );
if ( ! $attachment ) {
return false;
}
if ( 'attachment' !== $attachment->post_type ) {
return false;
}
return wp_attachment_is( $mime_type, $attachment );
}
```
| Uses | Description |
| --- | --- |
| [wp\_attachment\_is()](../../functions/wp_attachment_is) wp-includes/post.php | Verifies an attachment is of a given type. |
| [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::reset_default_labels() WP\_Widget\_Media::reset\_default\_labels()
===========================================
Resets the cache for the default labels.
File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
public static function reset_default_labels() {
self::$default_description = '';
self::$l10n_defaults = array();
}
```
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
| programming_docs |
wordpress WP_Widget_Media::render_media( array $instance ) WP\_Widget\_Media::render\_media( array $instance )
===================================================
Render the media on the frontend.
`$instance` array Required Widget instance props. File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
abstract public function render_media( $instance );
```
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Media::widget()](widget) wp-includes/widgets/class-wp-widget-media.php | Displays the widget on the front-end. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media::get_default_description(): string WP\_Widget\_Media::get\_default\_description(): string
======================================================
Returns the default description of the widget.
string
File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
protected static function get_default_description() {
if ( self::$default_description ) {
return self::$default_description;
}
self::$default_description = __( 'A media item.' );
return self::$default_description;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Media::\_\_construct()](__construct) wp-includes/widgets/class-wp-widget-media.php | Constructor. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_Widget_Media::display_media_state( array $states, WP_Post $post = null ): array WP\_Widget\_Media::display\_media\_state( array $states, WP\_Post $post = null ): array
=======================================================================================
Filters the default media display states for items in the Media list table.
`$states` array Required An array of media states. `$post` [WP\_Post](../wp_post) Optional The current attachment object. Default: `null`
array
File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
public function display_media_state( $states, $post = null ) {
if ( ! $post ) {
$post = get_post();
}
// Count how many times this attachment is used in widgets.
$use_count = 0;
foreach ( $this->get_settings() as $instance ) {
if ( isset( $instance['attachment_id'] ) && $instance['attachment_id'] === $post->ID ) {
$use_count++;
}
}
if ( 1 === $use_count ) {
$states[] = $this->l10n['media_library_state_single'];
} elseif ( $use_count > 0 ) {
$states[] = sprintf( translate_nooped_plural( $this->l10n['media_library_state_multi'], $use_count ), number_format_i18n( $use_count ) );
}
return $states;
}
```
| Uses | Description |
| --- | --- |
| [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) . |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| [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::sanitize_token_list( string|array $tokens ): string WP\_Widget\_Media::sanitize\_token\_list( string|array $tokens ): string
========================================================================
Sanitize a token list string, such as used in HTML rel and class attributes.
`$tokens` string|array Required List of tokens separated by spaces, or an array of tokens. string Sanitized token string list.
File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
public function sanitize_token_list( $tokens ) {
if ( is_string( $tokens ) ) {
$tokens = preg_split( '/\s+/', trim( $tokens ) );
}
$tokens = array_map( 'sanitize_html_class', $tokens );
$tokens = array_filter( $tokens );
return implode( ' ', $tokens );
}
```
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media::render_control_template_scripts() WP\_Widget\_Media::render\_control\_template\_scripts()
=======================================================
Render form template scripts.
File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
public function render_control_template_scripts() {
?>
<script type="text/html" id="tmpl-widget-media-<?php echo esc_attr( $this->id_base ); ?>-control">
<# var elementIdPrefix = 'el' + String( Math.random() ) + '_' #>
<p>
<label for="{{ elementIdPrefix }}title"><?php esc_html_e( 'Title:' ); ?></label>
<input id="{{ elementIdPrefix }}title" type="text" class="widefat title">
</p>
<div class="media-widget-preview <?php echo esc_attr( $this->id_base ); ?>">
<div class="attachment-media-view">
<button type="button" class="select-media button-add-media not-selected">
<?php echo esc_html( $this->l10n['add_media'] ); ?>
</button>
</div>
</div>
<p class="media-widget-buttons">
<button type="button" class="button edit-media selected">
<?php echo esc_html( $this->l10n['edit_media'] ); ?>
</button>
<?php if ( ! empty( $this->l10n['replace_media'] ) ) : ?>
<button type="button" class="button change-media select-media selected">
<?php echo esc_html( $this->l10n['replace_media'] ); ?>
</button>
<?php endif; ?>
</p>
<div class="media-widget-fields">
</div>
</script>
<?php
}
```
| Uses | Description |
| --- | --- |
| [esc\_html\_e()](../../functions/esc_html_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in HTML output. |
| [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. |
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Media\_Gallery::render\_control\_template\_scripts()](../wp_widget_media_gallery/render_control_template_scripts) wp-includes/widgets/class-wp-widget-media-gallery.php | Render form template scripts. |
| [WP\_Widget\_Media\_Audio::render\_control\_template\_scripts()](../wp_widget_media_audio/render_control_template_scripts) wp-includes/widgets/class-wp-widget-media-audio.php | Render form template scripts. |
| [WP\_Widget\_Media\_Video::render\_control\_template\_scripts()](../wp_widget_media_video/render_control_template_scripts) wp-includes/widgets/class-wp-widget-media-video.php | Render form template scripts. |
| [WP\_Widget\_Media\_Image::render\_control\_template\_scripts()](../wp_widget_media_image/render_control_template_scripts) wp-includes/widgets/class-wp-widget-media-image.php | Render form template scripts. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media::_register_one( int $number = -1 ) WP\_Widget\_Media::\_register\_one( int $number = -1 )
======================================================
Add hooks while registering all widget instances of this widget class.
`$number` int Optional The unique order number of this widget instance compared to other instances of the same class. Default: `-1`
File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
public function _register_one( $number = -1 ) {
parent::_register_one( $number );
if ( $this->registered ) {
return;
}
$this->registered = true;
// Note that the widgets component in the customizer will also do
// the 'admin_print_scripts-widgets.php' action in WP_Customize_Widgets::print_scripts().
add_action( 'admin_print_scripts-widgets.php', array( $this, 'enqueue_admin_scripts' ) );
if ( $this->is_preview() ) {
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_preview_scripts' ) );
}
// Note that the widgets component in the customizer will also do
// the 'admin_footer-widgets.php' action in WP_Customize_Widgets::print_footer_scripts().
add_action( 'admin_footer-widgets.php', array( $this, 'render_control_template_scripts' ) );
add_filter( 'display_media_states', array( $this, 'display_media_state' ), 10, 2 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget::\_register\_one()](../wp_widget/_register_one) wp-includes/class-wp-widget.php | Registers an instance of the widget class. |
| [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. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media::__construct( string $id_base, string $name, array $widget_options = array(), array $control_options = array() ) WP\_Widget\_Media::\_\_construct( string $id\_base, string $name, array $widget\_options = array(), array $control\_options = array() )
=======================================================================================================================================
Constructor.
`$id_base` string Required Base ID for the widget, lowercase and unique. `$name` string Required Name for the widget displayed on the configuration page. `$widget_options` array Optional Widget options. See [wp\_register\_sidebar\_widget()](../../functions/wp_register_sidebar_widget) for information on accepted arguments. Default: `array()`
`$control_options` array Optional Widget control options. See [wp\_register\_widget\_control()](../../functions/wp_register_widget_control) for information on accepted arguments. Default: `array()`
File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
public function __construct( $id_base, $name, $widget_options = array(), $control_options = array() ) {
$widget_opts = wp_parse_args(
$widget_options,
array(
'description' => self::get_default_description(),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
'mime_type' => '',
)
);
$control_opts = wp_parse_args( $control_options, array() );
$this->l10n = array_merge( self::get_l10n_defaults(), array_filter( $this->l10n ) );
parent::__construct(
$id_base,
$name,
$widget_opts,
$control_opts
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Media::get\_default\_description()](get_default_description) wp-includes/widgets/class-wp-widget-media.php | Returns the default description of the widget. |
| [WP\_Widget\_Media::get\_l10n\_defaults()](get_l10n_defaults) wp-includes/widgets/class-wp-widget-media.php | Returns the default localized strings used by the widget. |
| [WP\_Widget::\_\_construct()](../wp_widget/__construct) wp-includes/class-wp-widget.php | PHP5 constructor. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Media\_Gallery::\_\_construct()](../wp_widget_media_gallery/__construct) wp-includes/widgets/class-wp-widget-media-gallery.php | Constructor. |
| [WP\_Widget\_Media\_Audio::\_\_construct()](../wp_widget_media_audio/__construct) wp-includes/widgets/class-wp-widget-media-audio.php | Constructor. |
| [WP\_Widget\_Media\_Video::\_\_construct()](../wp_widget_media_video/__construct) wp-includes/widgets/class-wp-widget-media-video.php | Constructor. |
| [WP\_Widget\_Media\_Image::\_\_construct()](../wp_widget_media_image/__construct) wp-includes/widgets/class-wp-widget-media-image.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media::get_l10n_defaults(): (string|array)[] WP\_Widget\_Media::get\_l10n\_defaults(): (string|array)[]
==========================================================
Returns the default localized strings used by the widget.
(string|array)[]
File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
protected static function get_l10n_defaults() {
if ( ! empty( self::$l10n_defaults ) ) {
return self::$l10n_defaults;
}
self::$l10n_defaults = array(
'no_media_selected' => __( 'No media selected' ),
'add_media' => _x( 'Add Media', 'label for button in the media widget' ),
'replace_media' => _x( 'Replace Media', 'label for button in the media widget; should preferably not be longer than ~13 characters long' ),
'edit_media' => _x( 'Edit Media', 'label for button in the media widget; should preferably not be longer than ~13 characters long' ),
'add_to_widget' => __( 'Add to Widget' ),
'missing_attachment' => sprintf(
/* translators: %s: URL to media library. */
__( 'That file 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( 'Media Widget (%d)', 'Media Widget (%d)' ),
'media_library_state_single' => __( 'Media Widget' ),
'unsupported_file_type' => __( 'Looks like this is not the correct kind of file. Please link to an appropriate file instead.' ),
);
return self::$l10n_defaults;
}
```
| Uses | Description |
| --- | --- |
| [\_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. |
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Media::\_\_construct()](__construct) wp-includes/widgets/class-wp-widget-media.php | Constructor. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_Widget_Media::widget( array $args, array $instance ) WP\_Widget\_Media::widget( array $args, array $instance )
=========================================================
Displays the widget on the front-end.
* [WP\_Widget::widget()](../wp_widget/widget)
`$args` array Required Display arguments including before\_title, after\_title, before\_widget, and after\_widget. `$instance` array Required Saved setting from the database. File: `wp-includes/widgets/class-wp-widget-media.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
public function widget( $args, $instance ) {
$instance = wp_parse_args( $instance, wp_list_pluck( $this->get_instance_schema(), 'default' ) );
// Short-circuit if no media is selected.
if ( ! $this->has_content( $instance ) ) {
return;
}
echo $args['before_widget'];
/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
$title = apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base );
if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
}
/**
* Filters the media widget instance prior to rendering the media.
*
* @since 4.8.0
*
* @param array $instance Instance data.
* @param array $args Widget args.
* @param WP_Widget_Media $widget Widget object.
*/
$instance = apply_filters( "widget_{$this->id_base}_instance", $instance, $args, $this );
$this->render_media( $instance );
echo $args['after_widget'];
}
```
[apply\_filters( 'widget\_title', string $title, array $instance, mixed $id\_base )](../../hooks/widget_title)
Filters the widget title.
[apply\_filters( "widget\_{$this->id\_base}\_instance", array $instance, array $args, WP\_Widget\_Media $widget )](../../hooks/widget_this-id_base_instance)
Filters the media widget instance prior to rendering the media.
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Media::has\_content()](has_content) wp-includes/widgets/class-wp-widget-media.php | Whether the widget has content to show. |
| [WP\_Widget\_Media::get\_instance\_schema()](get_instance_schema) wp-includes/widgets/class-wp-widget-media.php | Get schema for properties of a widget instance (item). |
| [WP\_Widget\_Media::render\_media()](render_media) wp-includes/widgets/class-wp-widget-media.php | Render the media on the 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. |
| [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. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Media::enqueue_preview_scripts() WP\_Widget\_Media::enqueue\_preview\_scripts()
==============================================
Enqueue preview scripts.
These scripts normally are enqueued just-in-time when a widget is rendered.
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.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media.php/)
```
public function enqueue_preview_scripts() {}
```
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP::remove_query_var( string $name ) WP::remove\_query\_var( string $name )
======================================
Removes a query variable from a list of public query variables.
`$name` string Required Query variable name. File: `wp-includes/class-wp.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp.php/)
```
public function remove_query_var( $name ) {
$this->public_query_vars = array_diff( $this->public_query_vars, array( $name ) );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Taxonomy::remove\_rewrite\_rules()](../wp_taxonomy/remove_rewrite_rules) wp-includes/class-wp-taxonomy.php | Removes any rewrite rules, permastructs, and rules for the taxonomy. |
| [WP\_Post\_Type::remove\_rewrite\_rules()](../wp_post_type/remove_rewrite_rules) wp-includes/class-wp-post-type.php | Removes any rewrite rules, permastructs, and rules for the post type. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
| programming_docs |
wordpress WP::init() WP::init()
==========
Set up the current user.
File: `wp-includes/class-wp.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp.php/)
```
public function init() {
wp_get_current_user();
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_current\_user()](../../functions/wp_get_current_user) wp-includes/pluggable.php | Retrieves the current user object. |
| Used By | Description |
| --- | --- |
| [WP::main()](main) wp-includes/class-wp.php | Sets up all of the variables required by the WordPress environment. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP::set_query_var( string $key, mixed $value ) WP::set\_query\_var( string $key, mixed $value )
================================================
Sets the value of a query variable.
`$key` string Required Query variable name. `$value` mixed Required Query variable value. File: `wp-includes/class-wp.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp.php/)
```
public function set_query_var( $key, $value ) {
$this->query_vars[ $key ] = $value;
}
```
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress WP::build_query_string() WP::build\_query\_string()
==========================
Sets the query string property based off of the query variable property.
The [‘query\_string’](../../hooks/query_string) filter is deprecated, but still works. Plugins should use the [‘request’](../../hooks/request) filter instead.
File: `wp-includes/class-wp.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp.php/)
```
public function build_query_string() {
$this->query_string = '';
foreach ( (array) array_keys( $this->query_vars ) as $wpvar ) {
if ( '' != $this->query_vars[ $wpvar ] ) {
$this->query_string .= ( strlen( $this->query_string ) < 1 ) ? '' : '&';
if ( ! is_scalar( $this->query_vars[ $wpvar ] ) ) { // Discard non-scalars.
continue;
}
$this->query_string .= $wpvar . '=' . rawurlencode( $this->query_vars[ $wpvar ] );
}
}
if ( has_filter( 'query_string' ) ) { // Don't bother filtering and parsing if no plugins are hooked in.
/**
* Filters the query string before parsing.
*
* @since 1.5.0
* @deprecated 2.1.0 Use {@see 'query_vars'} or {@see 'request'} filters instead.
*
* @param string $query_string The query string to modify.
*/
$this->query_string = apply_filters_deprecated(
'query_string',
array( $this->query_string ),
'2.1.0',
'query_vars, request'
);
parse_str( $this->query_string, $this->query_vars );
}
}
```
[apply\_filters\_deprecated( 'query\_string', string $query\_string )](../../hooks/query_string)
Filters the query string before parsing.
| Uses | Description |
| --- | --- |
| [apply\_filters\_deprecated()](../../functions/apply_filters_deprecated) wp-includes/plugin.php | Fires functions attached to a deprecated filter hook. |
| [has\_filter()](../../functions/has_filter) wp-includes/plugin.php | Checks if any filter has been registered for a hook. |
| Used By | Description |
| --- | --- |
| [WP::query\_posts()](query_posts) wp-includes/class-wp.php | Set up the Loop based on the query variables. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP::register_globals() WP::register\_globals()
=======================
Set up the WordPress Globals.
The query\_vars property will be extracted to the GLOBALS. So care should be taken when naming global variables that might interfere with the WordPress environment.
File: `wp-includes/class-wp.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp.php/)
```
public function register_globals() {
global $wp_query;
// Extract updated query vars back into global namespace.
foreach ( (array) $wp_query->query_vars as $key => $value ) {
$GLOBALS[ $key ] = $value;
}
$GLOBALS['query_string'] = $this->query_string;
$GLOBALS['posts'] = & $wp_query->posts;
$GLOBALS['post'] = isset( $wp_query->post ) ? $wp_query->post : null;
$GLOBALS['request'] = $wp_query->request;
if ( $wp_query->is_single() || $wp_query->is_page() ) {
$GLOBALS['more'] = 1;
$GLOBALS['single'] = 1;
}
if ( $wp_query->is_author() ) {
$GLOBALS['authordata'] = get_userdata( get_queried_object_id() );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Query::is\_page()](../wp_query/is_page) wp-includes/class-wp-query.php | Is the query for an existing single page? |
| [WP\_Query::is\_single()](../wp_query/is_single) wp-includes/class-wp-query.php | Is the query for an existing single post? |
| [WP\_Query::is\_author()](../wp_query/is_author) wp-includes/class-wp-query.php | Is the query for an existing author archive page? |
| [get\_queried\_object\_id()](../../functions/get_queried_object_id) wp-includes/query.php | Retrieves the ID of the currently queried object. |
| [get\_userdata()](../../functions/get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| Used By | Description |
| --- | --- |
| [WP::main()](main) wp-includes/class-wp.php | Sets up all of the variables required by the WordPress environment. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP::handle_404() WP::handle\_404()
=================
Set the Headers for 404, if nothing is found for requested URL.
Issue a 404 if a request doesn’t match any posts and doesn’t match any object (e.g. an existing-but-empty category, tag, author) and a 404 was not already issued, and if the request was not a search or the homepage.
Otherwise, issue a 200.
This sets headers after posts have been queried. handle\_404() really means "handle status".
By inspecting the result of querying posts, seemingly successful requests can be switched to a 404 so that canonical redirection logic can kick in.
File: `wp-includes/class-wp.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp.php/)
```
public function handle_404() {
global $wp_query;
/**
* Filters whether to short-circuit default header status handling.
*
* Returning a non-false value from the filter will short-circuit the handling
* and return early.
*
* @since 4.5.0
*
* @param bool $preempt Whether to short-circuit default header status handling. Default false.
* @param WP_Query $wp_query WordPress Query object.
*/
if ( false !== apply_filters( 'pre_handle_404', false, $wp_query ) ) {
return;
}
// If we've already issued a 404, bail.
if ( is_404() ) {
return;
}
$set_404 = true;
// Never 404 for the admin, robots, or favicon.
if ( is_admin() || is_robots() || is_favicon() ) {
$set_404 = false;
// If posts were found, check for paged content.
} elseif ( $wp_query->posts ) {
$content_found = true;
if ( is_singular() ) {
$post = isset( $wp_query->post ) ? $wp_query->post : null;
$next = '<!--nextpage-->';
// Check for paged content that exceeds the max number of pages.
if ( $post && ! empty( $this->query_vars['page'] ) ) {
// Check if content is actually intended to be paged.
if ( false !== strpos( $post->post_content, $next ) ) {
$page = trim( $this->query_vars['page'], '/' );
$content_found = (int) $page <= ( substr_count( $post->post_content, $next ) + 1 );
} else {
$content_found = false;
}
}
}
// The posts page does not support the <!--nextpage--> pagination.
if ( $wp_query->is_posts_page && ! empty( $this->query_vars['page'] ) ) {
$content_found = false;
}
if ( $content_found ) {
$set_404 = false;
}
// We will 404 for paged queries, as no posts were found.
} elseif ( ! is_paged() ) {
$author = get_query_var( 'author' );
// Don't 404 for authors without posts as long as they matched an author on this site.
if ( is_author() && is_numeric( $author ) && $author > 0 && is_user_member_of_blog( $author )
// Don't 404 for these queries if they matched an object.
|| ( is_tag() || is_category() || is_tax() || is_post_type_archive() ) && get_queried_object()
// Don't 404 for these queries either.
|| is_home() || is_search() || is_feed()
) {
$set_404 = false;
}
}
if ( $set_404 ) {
// Guess it's time to 404.
$wp_query->set_404();
status_header( 404 );
nocache_headers();
} else {
status_header( 200 );
}
}
```
[apply\_filters( 'pre\_handle\_404', bool $preempt, WP\_Query $wp\_query )](../../hooks/pre_handle_404)
Filters whether to short-circuit default header status handling.
| Uses | Description |
| --- | --- |
| [is\_favicon()](../../functions/is_favicon) wp-includes/query.php | Is the query for the favicon.ico file? |
| [WP\_Query::set\_404()](../wp_query/set_404) wp-includes/class-wp-query.php | Sets the 404 property and saves whether query is feed. |
| [nocache\_headers()](../../functions/nocache_headers) wp-includes/functions.php | Sets the headers to prevent caching for the different browsers. |
| [status\_header()](../../functions/status_header) wp-includes/functions.php | Sets HTTP status header. |
| [get\_queried\_object()](../../functions/get_queried_object) wp-includes/query.php | Retrieves the currently queried object. |
| [is\_post\_type\_archive()](../../functions/is_post_type_archive) wp-includes/query.php | Determines whether the query is for an existing post type archive page. |
| [get\_query\_var()](../../functions/get_query_var) wp-includes/query.php | Retrieves the value of a query variable in the [WP\_Query](../wp_query) class. |
| [is\_feed()](../../functions/is_feed) wp-includes/query.php | Determines whether the query is for a feed. |
| [is\_home()](../../functions/is_home) wp-includes/query.php | Determines whether the query is for the blog homepage. |
| [is\_tax()](../../functions/is_tax) wp-includes/query.php | Determines whether the query is for an existing custom taxonomy archive page. |
| [is\_category()](../../functions/is_category) wp-includes/query.php | Determines whether the query is for an existing category archive page. |
| [is\_tag()](../../functions/is_tag) wp-includes/query.php | Determines whether the query is for an existing tag archive page. |
| [is\_author()](../../functions/is_author) wp-includes/query.php | Determines whether the query is for an existing author archive page. |
| [is\_paged()](../../functions/is_paged) wp-includes/query.php | Determines whether the query is for a paged result and not for the first page. |
| [is\_search()](../../functions/is_search) wp-includes/query.php | Determines whether the query is for a search. |
| [is\_singular()](../../functions/is_singular) wp-includes/query.php | Determines whether the query is for an existing single post of any post type (post, attachment, page, custom post types). |
| [is\_robots()](../../functions/is_robots) wp-includes/query.php | Is the query for the robots.txt file? |
| [is\_404()](../../functions/is_404) wp-includes/query.php | Determines whether the query has resulted in a 404 (returns no results). |
| [is\_user\_member\_of\_blog()](../../functions/is_user_member_of_blog) wp-includes/user.php | Finds out whether a user is a member of a given blog. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| [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::main()](main) wp-includes/class-wp.php | Sets up all of the variables required by the WordPress environment. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP::add_query_var( string $qv ) WP::add\_query\_var( string $qv )
=================================
Adds a query variable to the list of public query variables.
`$qv` string Required Query variable name. File: `wp-includes/class-wp.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp.php/)
```
public function add_query_var( $qv ) {
if ( ! in_array( $qv, $this->public_query_vars, true ) ) {
$this->public_query_vars[] = $qv;
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Taxonomy::add\_rewrite\_rules()](../wp_taxonomy/add_rewrite_rules) wp-includes/class-wp-taxonomy.php | Adds the necessary rewrite rules for the taxonomy. |
| [WP\_Post\_Type::add\_rewrite\_rules()](../wp_post_type/add_rewrite_rules) wp-includes/class-wp-post-type.php | Adds the necessary rewrite rules for the post type. |
| [rest\_api\_init()](../../functions/rest_api_init) wp-includes/rest-api.php | Registers rewrite rules for the REST API. |
| [WP\_Rewrite::add\_endpoint()](../wp_rewrite/add_endpoint) wp-includes/class-wp-rewrite.php | Adds an endpoint, like /trackback/. |
| [add\_rewrite\_tag()](../../functions/add_rewrite_tag) wp-includes/rewrite.php | Adds a new rewrite tag (like %postname%). |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP::parse_request( array|string $extra_query_vars = '' ): bool WP::parse\_request( array|string $extra\_query\_vars = '' ): bool
=================================================================
Parses the request to find the correct WordPress query.
Sets up the query variables based on the request. There are also many filters and actions that can be used to further manipulate the result.
`$extra_query_vars` array|string Optional Set the extra query variables. Default: `''`
bool Whether the request was parsed.
File: `wp-includes/class-wp.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp.php/)
```
public function parse_request( $extra_query_vars = '' ) {
global $wp_rewrite;
/**
* Filters whether to parse the request.
*
* @since 3.5.0
*
* @param bool $bool Whether or not to parse the request. Default true.
* @param WP $wp Current WordPress environment instance.
* @param array|string $extra_query_vars Extra passed query variables.
*/
if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) ) {
return false;
}
$this->query_vars = array();
$post_type_query_vars = array();
if ( is_array( $extra_query_vars ) ) {
$this->extra_query_vars = & $extra_query_vars;
} elseif ( ! empty( $extra_query_vars ) ) {
parse_str( $extra_query_vars, $this->extra_query_vars );
}
// Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
// Fetch the rewrite rules.
$rewrite = $wp_rewrite->wp_rewrite_rules();
if ( ! empty( $rewrite ) ) {
// If we match a rewrite rule, this will be cleared.
$error = '404';
$this->did_permalink = true;
$pathinfo = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : '';
list( $pathinfo ) = explode( '?', $pathinfo );
$pathinfo = str_replace( '%', '%25', $pathinfo );
list( $req_uri ) = explode( '?', $_SERVER['REQUEST_URI'] );
$self = $_SERVER['PHP_SELF'];
$home_path = parse_url( home_url(), PHP_URL_PATH );
$home_path_regex = '';
if ( is_string( $home_path ) && '' !== $home_path ) {
$home_path = trim( $home_path, '/' );
$home_path_regex = sprintf( '|^%s|i', preg_quote( $home_path, '|' ) );
}
/*
* Trim path info from the end and the leading home path from the front.
* For path info requests, this leaves us with the requesting filename, if any.
* For 404 requests, this leaves us with the requested permalink.
*/
$req_uri = str_replace( $pathinfo, '', $req_uri );
$req_uri = trim( $req_uri, '/' );
$pathinfo = trim( $pathinfo, '/' );
$self = trim( $self, '/' );
if ( ! empty( $home_path_regex ) ) {
$req_uri = preg_replace( $home_path_regex, '', $req_uri );
$req_uri = trim( $req_uri, '/' );
$pathinfo = preg_replace( $home_path_regex, '', $pathinfo );
$pathinfo = trim( $pathinfo, '/' );
$self = preg_replace( $home_path_regex, '', $self );
$self = trim( $self, '/' );
}
// The requested permalink is in $pathinfo for path info requests and
// $req_uri for other requests.
if ( ! empty( $pathinfo ) && ! preg_match( '|^.*' . $wp_rewrite->index . '$|', $pathinfo ) ) {
$requested_path = $pathinfo;
} else {
// If the request uri is the index, blank it out so that we don't try to match it against a rule.
if ( $req_uri == $wp_rewrite->index ) {
$req_uri = '';
}
$requested_path = $req_uri;
}
$requested_file = $req_uri;
$this->request = $requested_path;
// Look for matches.
$request_match = $requested_path;
if ( empty( $request_match ) ) {
// An empty request could only match against ^$ regex.
if ( isset( $rewrite['$'] ) ) {
$this->matched_rule = '$';
$query = $rewrite['$'];
$matches = array( '' );
}
} else {
foreach ( (array) $rewrite as $match => $query ) {
// If the requested file is the anchor of the match, prepend it to the path info.
if ( ! empty( $requested_file ) && strpos( $match, $requested_file ) === 0 && $requested_file != $requested_path ) {
$request_match = $requested_file . '/' . $requested_path;
}
if ( preg_match( "#^$match#", $request_match, $matches ) ||
preg_match( "#^$match#", urldecode( $request_match ), $matches ) ) {
if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
// This is a verbose page match, let's check to be sure about it.
$page = get_page_by_path( $matches[ $varmatch[1] ] );
if ( ! $page ) {
continue;
}
$post_status_obj = get_post_status_object( $page->post_status );
if ( ! $post_status_obj->public && ! $post_status_obj->protected
&& ! $post_status_obj->private && $post_status_obj->exclude_from_search ) {
continue;
}
}
// Got a match.
$this->matched_rule = $match;
break;
}
}
}
if ( ! empty( $this->matched_rule ) ) {
// Trim the query of everything up to the '?'.
$query = preg_replace( '!^.+\?!', '', $query );
// Substitute the substring matches into the query.
$query = addslashes( WP_MatchesMapRegex::apply( $query, $matches ) );
$this->matched_query = $query;
// Parse the query.
parse_str( $query, $perma_query_vars );
// If we're processing a 404 request, clear the error var since we found something.
if ( '404' == $error ) {
unset( $error, $_GET['error'] );
}
}
// If req_uri is empty or if it is a request for ourself, unset error.
if ( empty( $requested_path ) || $requested_file == $self || strpos( $_SERVER['PHP_SELF'], 'wp-admin/' ) !== false ) {
unset( $error, $_GET['error'] );
if ( isset( $perma_query_vars ) && strpos( $_SERVER['PHP_SELF'], 'wp-admin/' ) !== false ) {
unset( $perma_query_vars );
}
$this->did_permalink = false;
}
}
/**
* Filters the query variables allowed before processing.
*
* Allows (publicly allowed) query vars to be added, removed, or changed prior
* to executing the query. Needed to allow custom rewrite rules using your own arguments
* to work, or any other custom query variables you want to be publicly available.
*
* @since 1.5.0
*
* @param string[] $public_query_vars The array of allowed query variable names.
*/
$this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );
foreach ( get_post_types( array(), 'objects' ) as $post_type => $t ) {
if ( is_post_type_viewable( $t ) && $t->query_var ) {
$post_type_query_vars[ $t->query_var ] = $post_type;
}
}
foreach ( $this->public_query_vars as $wpvar ) {
if ( isset( $this->extra_query_vars[ $wpvar ] ) ) {
$this->query_vars[ $wpvar ] = $this->extra_query_vars[ $wpvar ];
} elseif ( isset( $_GET[ $wpvar ] ) && isset( $_POST[ $wpvar ] ) && $_GET[ $wpvar ] !== $_POST[ $wpvar ] ) {
wp_die( __( 'A variable mismatch has been detected.' ), __( 'Sorry, you are not allowed to view this item.' ), 400 );
} elseif ( isset( $_POST[ $wpvar ] ) ) {
$this->query_vars[ $wpvar ] = $_POST[ $wpvar ];
} elseif ( isset( $_GET[ $wpvar ] ) ) {
$this->query_vars[ $wpvar ] = $_GET[ $wpvar ];
} elseif ( isset( $perma_query_vars[ $wpvar ] ) ) {
$this->query_vars[ $wpvar ] = $perma_query_vars[ $wpvar ];
}
if ( ! empty( $this->query_vars[ $wpvar ] ) ) {
if ( ! is_array( $this->query_vars[ $wpvar ] ) ) {
$this->query_vars[ $wpvar ] = (string) $this->query_vars[ $wpvar ];
} else {
foreach ( $this->query_vars[ $wpvar ] as $vkey => $v ) {
if ( is_scalar( $v ) ) {
$this->query_vars[ $wpvar ][ $vkey ] = (string) $v;
}
}
}
if ( isset( $post_type_query_vars[ $wpvar ] ) ) {
$this->query_vars['post_type'] = $post_type_query_vars[ $wpvar ];
$this->query_vars['name'] = $this->query_vars[ $wpvar ];
}
}
}
// Convert urldecoded spaces back into '+'.
foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy => $t ) {
if ( $t->query_var && isset( $this->query_vars[ $t->query_var ] ) ) {
$this->query_vars[ $t->query_var ] = str_replace( ' ', '+', $this->query_vars[ $t->query_var ] );
}
}
// Don't allow non-publicly queryable taxonomies to be queried from the front end.
if ( ! is_admin() ) {
foreach ( get_taxonomies( array( 'publicly_queryable' => false ), 'objects' ) as $taxonomy => $t ) {
/*
* Disallow when set to the 'taxonomy' query var.
* Non-publicly queryable taxonomies cannot register custom query vars. See register_taxonomy().
*/
if ( isset( $this->query_vars['taxonomy'] ) && $taxonomy === $this->query_vars['taxonomy'] ) {
unset( $this->query_vars['taxonomy'], $this->query_vars['term'] );
}
}
}
// Limit publicly queried post_types to those that are 'publicly_queryable'.
if ( isset( $this->query_vars['post_type'] ) ) {
$queryable_post_types = get_post_types( array( 'publicly_queryable' => true ) );
if ( ! is_array( $this->query_vars['post_type'] ) ) {
if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types, true ) ) {
unset( $this->query_vars['post_type'] );
}
} else {
$this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types );
}
}
// Resolve conflicts between posts with numeric slugs and date archive queries.
$this->query_vars = wp_resolve_numeric_slug_conflicts( $this->query_vars );
foreach ( (array) $this->private_query_vars as $var ) {
if ( isset( $this->extra_query_vars[ $var ] ) ) {
$this->query_vars[ $var ] = $this->extra_query_vars[ $var ];
}
}
if ( isset( $error ) ) {
$this->query_vars['error'] = $error;
}
/**
* Filters the array of parsed query variables.
*
* @since 2.1.0
*
* @param array $query_vars The array of requested query variables.
*/
$this->query_vars = apply_filters( 'request', $this->query_vars );
/**
* Fires once all query variables for the current request have been parsed.
*
* @since 2.1.0
*
* @param WP $wp Current WordPress environment instance (passed by reference).
*/
do_action_ref_array( 'parse_request', array( &$this ) );
return true;
}
```
[apply\_filters( 'do\_parse\_request', bool $bool, WP $wp, array|string $extra\_query\_vars )](../../hooks/do_parse_request)
Filters whether to parse the request.
[do\_action\_ref\_array( 'parse\_request', WP $wp )](../../hooks/parse_request)
Fires once all query variables for the current request have been parsed.
[apply\_filters( 'query\_vars', string[] $public\_query\_vars )](../../hooks/query_vars)
Filters the query variables allowed before processing.
[apply\_filters( 'request', array $query\_vars )](../../hooks/request)
Filters the array of parsed query variables.
| Uses | Description |
| --- | --- |
| [is\_post\_type\_viewable()](../../functions/is_post_type_viewable) wp-includes/post.php | Determines whether a post type is considered “viewable”. |
| [wp\_resolve\_numeric\_slug\_conflicts()](../../functions/wp_resolve_numeric_slug_conflicts) wp-includes/rewrite.php | Resolves numeric slugs that collide with date permalinks. |
| [WP\_MatchesMapRegex::apply()](../wp_matchesmapregex/apply) wp-includes/class-wp-matchesmapregex.php | Substitute substring matches in subject. |
| [get\_taxonomies()](../../functions/get_taxonomies) wp-includes/taxonomy.php | Retrieves a list of registered taxonomy names or objects. |
| [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. |
| [get\_page\_by\_path()](../../functions/get_page_by_path) wp-includes/post.php | Retrieves a page given its path. |
| [get\_post\_status\_object()](../../functions/get_post_status_object) wp-includes/post.php | Retrieves a post status object by name. |
| [WP\_Rewrite::wp\_rewrite\_rules()](../wp_rewrite/wp_rewrite_rules) wp-includes/class-wp-rewrite.php | Retrieves the rewrite rules. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [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\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| Used By | Description |
| --- | --- |
| [WP::main()](main) wp-includes/class-wp.php | Sets up all of the variables required by the WordPress environment. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | A return value was added. |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
| programming_docs |
wordpress WP::main( string|array $query_args = '' ) WP::main( string|array $query\_args = '' )
==========================================
Sets up all of the variables required by the WordPress environment.
The action [‘wp’](../../hooks/wp) has one parameter that references the WP object. It allows for accessing the properties and methods to further manipulate the object.
`$query_args` string|array Optional Passed to parse\_request(). Default: `''`
File: `wp-includes/class-wp.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp.php/)
```
public function main( $query_args = '' ) {
$this->init();
$parsed = $this->parse_request( $query_args );
if ( $parsed ) {
$this->query_posts();
$this->handle_404();
$this->register_globals();
}
$this->send_headers();
/**
* Fires once the WordPress environment has been set up.
*
* @since 2.1.0
*
* @param WP $wp Current WordPress environment instance (passed by reference).
*/
do_action_ref_array( 'wp', array( &$this ) );
}
```
[do\_action\_ref\_array( 'wp', WP $wp )](../../hooks/wp)
Fires once the WordPress environment has been set up.
| Uses | Description |
| --- | --- |
| [WP::init()](init) wp-includes/class-wp.php | Set up the current user. |
| [WP::query\_posts()](query_posts) wp-includes/class-wp.php | Set up the Loop based on the query variables. |
| [WP::handle\_404()](handle_404) wp-includes/class-wp.php | Set the Headers for 404, if nothing is found for requested URL. |
| [WP::register\_globals()](register_globals) wp-includes/class-wp.php | Set up the WordPress Globals. |
| [WP::parse\_request()](parse_request) wp-includes/class-wp.php | Parses the request to find the correct WordPress query. |
| [WP::send\_headers()](send_headers) wp-includes/class-wp.php | Sends additional HTTP headers for caching, content type, etc. |
| [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. |
| Used By | Description |
| --- | --- |
| [wp()](../../functions/wp) wp-includes/functions.php | Sets up the WordPress query. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP::send_headers() WP::send\_headers()
===================
Sends additional HTTP headers for caching, content type, etc.
Sets the Content-Type header. Sets the ‘error’ status (if passed) and optionally exits.
If showing a feed, it will also send Last-Modified, ETag, and 304 status if needed.
File: `wp-includes/class-wp.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp.php/)
```
public function send_headers() {
global $wp_query;
$headers = array();
$status = null;
$exit_required = false;
$date_format = 'D, d M Y H:i:s';
if ( is_user_logged_in() ) {
$headers = array_merge( $headers, wp_get_nocache_headers() );
} elseif ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) {
// Unmoderated comments are only visible for 10 minutes via the moderation hash.
$expires = 10 * MINUTE_IN_SECONDS;
$headers['Expires'] = gmdate( $date_format, time() + $expires );
$headers['Cache-Control'] = sprintf(
'max-age=%d, must-revalidate',
$expires
);
}
if ( ! empty( $this->query_vars['error'] ) ) {
$status = (int) $this->query_vars['error'];
if ( 404 === $status ) {
if ( ! is_user_logged_in() ) {
$headers = array_merge( $headers, wp_get_nocache_headers() );
}
$headers['Content-Type'] = get_option( 'html_type' ) . '; charset=' . get_option( 'blog_charset' );
} elseif ( in_array( $status, array( 403, 500, 502, 503 ), true ) ) {
$exit_required = true;
}
} elseif ( empty( $this->query_vars['feed'] ) ) {
$headers['Content-Type'] = get_option( 'html_type' ) . '; charset=' . get_option( 'blog_charset' );
} else {
// Set the correct content type for feeds.
$type = $this->query_vars['feed'];
if ( 'feed' === $this->query_vars['feed'] ) {
$type = get_default_feed();
}
$headers['Content-Type'] = feed_content_type( $type ) . '; charset=' . get_option( 'blog_charset' );
// We're showing a feed, so WP is indeed the only thing that last changed.
if ( ! empty( $this->query_vars['withcomments'] )
|| false !== strpos( $this->query_vars['feed'], 'comments-' )
|| ( empty( $this->query_vars['withoutcomments'] )
&& ( ! empty( $this->query_vars['p'] )
|| ! empty( $this->query_vars['name'] )
|| ! empty( $this->query_vars['page_id'] )
|| ! empty( $this->query_vars['pagename'] )
|| ! empty( $this->query_vars['attachment'] )
|| ! empty( $this->query_vars['attachment_id'] )
)
)
) {
$wp_last_modified_post = mysql2date( $date_format, get_lastpostmodified( 'GMT' ), false );
$wp_last_modified_comment = mysql2date( $date_format, get_lastcommentmodified( 'GMT' ), false );
if ( strtotime( $wp_last_modified_post ) > strtotime( $wp_last_modified_comment ) ) {
$wp_last_modified = $wp_last_modified_post;
} else {
$wp_last_modified = $wp_last_modified_comment;
}
} else {
$wp_last_modified = mysql2date( $date_format, get_lastpostmodified( 'GMT' ), false );
}
if ( ! $wp_last_modified ) {
$wp_last_modified = gmdate( $date_format );
}
$wp_last_modified .= ' GMT';
$wp_etag = '"' . md5( $wp_last_modified ) . '"';
$headers['Last-Modified'] = $wp_last_modified;
$headers['ETag'] = $wp_etag;
// Support for conditional GET.
if ( isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ) {
$client_etag = wp_unslash( $_SERVER['HTTP_IF_NONE_MATCH'] );
} else {
$client_etag = false;
}
$client_last_modified = empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ? '' : trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
// If string is empty, return 0. If not, attempt to parse into a timestamp.
$client_modified_timestamp = $client_last_modified ? strtotime( $client_last_modified ) : 0;
// Make a timestamp for our most recent modification..
$wp_modified_timestamp = strtotime( $wp_last_modified );
if ( ( $client_last_modified && $client_etag ) ?
( ( $client_modified_timestamp >= $wp_modified_timestamp ) && ( $client_etag == $wp_etag ) ) :
( ( $client_modified_timestamp >= $wp_modified_timestamp ) || ( $client_etag == $wp_etag ) ) ) {
$status = 304;
$exit_required = true;
}
}
if ( is_singular() ) {
$post = isset( $wp_query->post ) ? $wp_query->post : null;
// Only set X-Pingback for single posts that allow pings.
if ( $post && pings_open( $post ) ) {
$headers['X-Pingback'] = get_bloginfo( 'pingback_url', 'display' );
}
}
/**
* Filters the HTTP headers before they're sent to the browser.
*
* @since 2.8.0
*
* @param string[] $headers Associative array of headers to be sent.
* @param WP $wp Current WordPress environment instance.
*/
$headers = apply_filters( 'wp_headers', $headers, $this );
if ( ! empty( $status ) ) {
status_header( $status );
}
// If Last-Modified is set to false, it should not be sent (no-cache situation).
if ( isset( $headers['Last-Modified'] ) && false === $headers['Last-Modified'] ) {
unset( $headers['Last-Modified'] );
if ( ! headers_sent() ) {
header_remove( 'Last-Modified' );
}
}
if ( ! headers_sent() ) {
foreach ( (array) $headers as $name => $field_value ) {
header( "{$name}: {$field_value}" );
}
}
if ( $exit_required ) {
exit;
}
/**
* Fires once the requested HTTP headers for caching, content type, etc. have been sent.
*
* @since 2.1.0
*
* @param WP $wp Current WordPress environment instance (passed by reference).
*/
do_action_ref_array( 'send_headers', array( &$this ) );
}
```
[do\_action\_ref\_array( 'send\_headers', WP $wp )](../../hooks/send_headers)
Fires once the requested HTTP headers for caching, content type, etc. have been sent.
[apply\_filters( 'wp\_headers', string[] $headers, WP $wp )](../../hooks/wp_headers)
Filters the HTTP headers before they’re sent to the browser.
| Uses | Description |
| --- | --- |
| [is\_singular()](../../functions/is_singular) wp-includes/query.php | Determines whether the query is for an existing single post of any post type (post, attachment, page, custom post types). |
| [wp\_get\_nocache\_headers()](../../functions/wp_get_nocache_headers) wp-includes/functions.php | Gets the header information to prevent caching. |
| [status\_header()](../../functions/status_header) wp-includes/functions.php | Sets HTTP status header. |
| [mysql2date()](../../functions/mysql2date) wp-includes/functions.php | Converts given MySQL date string into a different format. |
| [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. |
| [feed\_content\_type()](../../functions/feed_content_type) wp-includes/feed.php | Returns the content type for specified feed type. |
| [get\_default\_feed()](../../functions/get_default_feed) wp-includes/feed.php | Retrieves the default feed. |
| [get\_lastpostmodified()](../../functions/get_lastpostmodified) wp-includes/post.php | Gets the most recent time that a post on the site was modified. |
| [pings\_open()](../../functions/pings_open) wp-includes/comment-template.php | Determines whether the current post is open for pings. |
| [get\_lastcommentmodified()](../../functions/get_lastcommentmodified) wp-includes/comment.php | Retrieves the date the last comment was modified. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [is\_user\_logged\_in()](../../functions/is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| [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::main()](main) wp-includes/class-wp.php | Sets up all of the variables required by the WordPress environment. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Runs after posts have been queried. |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | `X-Pingback` header is added conditionally for single posts that allow pings. |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP::query_posts() WP::query\_posts()
==================
Set up the Loop based on the query variables.
File: `wp-includes/class-wp.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp.php/)
```
public function query_posts() {
global $wp_the_query;
$this->build_query_string();
$wp_the_query->query( $this->query_vars );
}
```
| Uses | Description |
| --- | --- |
| [WP::build\_query\_string()](build_query_string) wp-includes/class-wp.php | Sets the query string property based off of the query variable property. |
| Used By | Description |
| --- | --- |
| [WP::main()](main) wp-includes/class-wp.php | Sets up all of the variables required by the WordPress environment. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress _WP_Dependency::add_data( string $name, mixed $data ): bool \_WP\_Dependency::add\_data( string $name, mixed $data ): bool
==============================================================
Add handle data.
`$name` string Required The data key to add. `$data` mixed Required The data value to add. bool False if not scalar, true otherwise.
File: `wp-includes/class-wp-dependency.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-dependency.php/)
```
public function add_data( $name, $data ) {
if ( ! is_scalar( $name ) ) {
return false;
}
$this->extra[ $name ] = $data;
return true;
}
```
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress _WP_Dependency::set_translations( string $domain, string $path = '' ): bool \_WP\_Dependency::set\_translations( string $domain, string $path = '' ): bool
==============================================================================
Sets the translation domain for this dependency.
`$domain` string Required The translation textdomain. `$path` string Optional The full file path to the directory containing translation files. Default: `''`
bool False if $domain is not a string, true otherwise.
File: `wp-includes/class-wp-dependency.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-dependency.php/)
```
public function set_translations( $domain, $path = '' ) {
if ( ! is_string( $domain ) ) {
return false;
}
$this->textdomain = $domain;
$this->translations_path = $path;
return true;
}
```
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress _WP_Dependency::__construct( mixed $args ) \_WP\_Dependency::\_\_construct( mixed $args )
==============================================
Setup dependencies.
`$args` mixed Required Dependency information. File: `wp-includes/class-wp-dependency.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-dependency.php/)
```
public function __construct( ...$args ) {
list( $this->handle, $this->src, $this->deps, $this->ver, $this->args ) = $args;
if ( ! is_array( $this->deps ) ) {
$this->deps = array();
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Dependencies::add()](../wp_dependencies/add) wp-includes/class-wp-dependencies.php | Register an item. |
| 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.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress WP_Widget_Block::form( array $instance ) WP\_Widget\_Block::form( array $instance )
==========================================
Outputs the Block widget settings form.
* [WP\_Widget\_Custom\_HTML::render\_control\_template\_scripts()](../wp_widget_custom_html/render_control_template_scripts)
`$instance` array Required Current instance. File: `wp-includes/widgets/class-wp-widget-block.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-block.php/)
```
public function form( $instance ) {
$instance = wp_parse_args( (array) $instance, $this->default_instance );
?>
<p>
<label for="<?php echo $this->get_field_id( 'content' ); ?>">
<?php
/* translators: HTML code of the block, not an option that blocks HTML. */
_e( 'Block HTML:' );
?>
</label>
<textarea id="<?php echo $this->get_field_id( 'content' ); ?>" name="<?php echo $this->get_field_name( 'content' ); ?>" rows="6" cols="50" class="widefat code"><?php echo esc_textarea( $instance['content'] ); ?></textarea>
</p>
<?php
}
```
| Uses | Description |
| --- | --- |
| [esc\_textarea()](../../functions/esc_textarea) wp-includes/formatting.php | Escaping for textarea values. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_Widget_Block::update( array $new_instance, array $old_instance ): array WP\_Widget\_Block::update( array $new\_instance, array $old\_instance ): array
==============================================================================
Handles updating settings for the current Block 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 Settings to save or bool false to cancel saving.
File: `wp-includes/widgets/class-wp-widget-block.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-block.php/)
```
public function update( $new_instance, $old_instance ) {
$instance = array_merge( $this->default_instance, $old_instance );
if ( current_user_can( 'unfiltered_html' ) ) {
$instance['content'] = $new_instance['content'];
} else {
$instance['content'] = wp_kses_post( $new_instance['content'] );
}
return $instance;
}
```
| Uses | Description |
| --- | --- |
| [wp\_kses\_post()](../../functions/wp_kses_post) wp-includes/kses.php | Sanitizes content for allowed HTML tags for post content. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_Widget_Block::set_is_wide_widget_in_customizer( bool $is_wide, string $widget_id ): bool WP\_Widget\_Block::set\_is\_wide\_widget\_in\_customizer( bool $is\_wide, string $widget\_id ): bool
====================================================================================================
Makes sure no block widget is considered to be wide.
`$is_wide` bool Required Whether the widget is considered wide. `$widget_id` string Required Widget ID. bool Updated `is_wide` value.
File: `wp-includes/widgets/class-wp-widget-block.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-block.php/)
```
public function set_is_wide_widget_in_customizer( $is_wide, $widget_id ) {
if ( strpos( $widget_id, 'block-' ) === 0 ) {
return false;
}
return $is_wide;
}
```
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_Widget_Block::__construct() WP\_Widget\_Block::\_\_construct()
==================================
Sets up a new Block widget instance.
File: `wp-includes/widgets/class-wp-widget-block.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-block.php/)
```
public function __construct() {
$widget_ops = array(
'classname' => 'widget_block',
'description' => __( 'A widget containing a block.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
$control_ops = array(
'width' => 400,
'height' => 350,
);
parent::__construct( 'block', __( 'Block' ), $widget_ops, $control_ops );
add_filter( 'is_wide_widget_in_customizer', array( $this, 'set_is_wide_widget_in_customizer' ), 10, 2 );
}
```
| 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. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Widget_Block::get_dynamic_classname( string $content ): string WP\_Widget\_Block::get\_dynamic\_classname( string $content ): 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.
Calculates the classname to use in the block widget’s container HTML.
Usually this is set to `$this->widget_options['classname']` by [dynamic\_sidebar()](../../functions/dynamic_sidebar) . In this case, however, we want to set the classname dynamically depending on the block contained by this block widget.
If a block widget contains a block that has an equivalent legacy widget, we display that legacy widget’s class name. This helps with theme backwards compatibility.
`$content` string Required The HTML content of the current block widget. string The classname to use in the block widget's container HTML.
File: `wp-includes/widgets/class-wp-widget-block.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-block.php/)
```
private function get_dynamic_classname( $content ) {
$blocks = parse_blocks( $content );
$block_name = isset( $blocks[0] ) ? $blocks[0]['blockName'] : null;
switch ( $block_name ) {
case 'core/paragraph':
$classname = 'widget_block widget_text';
break;
case 'core/calendar':
$classname = 'widget_block widget_calendar';
break;
case 'core/search':
$classname = 'widget_block widget_search';
break;
case 'core/html':
$classname = 'widget_block widget_custom_html';
break;
case 'core/archives':
$classname = 'widget_block widget_archive';
break;
case 'core/latest-posts':
$classname = 'widget_block widget_recent_entries';
break;
case 'core/latest-comments':
$classname = 'widget_block widget_recent_comments';
break;
case 'core/tag-cloud':
$classname = 'widget_block widget_tag_cloud';
break;
case 'core/categories':
$classname = 'widget_block widget_categories';
break;
case 'core/audio':
$classname = 'widget_block widget_media_audio';
break;
case 'core/video':
$classname = 'widget_block widget_media_video';
break;
case 'core/image':
$classname = 'widget_block widget_media_image';
break;
case 'core/gallery':
$classname = 'widget_block widget_media_gallery';
break;
case 'core/rss':
$classname = 'widget_block widget_rss';
break;
default:
$classname = 'widget_block';
}
/**
* The classname used in the block widget's container HTML.
*
* This can be set according to the name of the block contained by the block widget.
*
* @since 5.8.0
*
* @param string $classname The classname to be used in the block widget's container HTML,
* e.g. 'widget_block widget_text'.
* @param string $block_name The name of the block contained by the block widget,
* e.g. 'core/paragraph'.
*/
return apply_filters( 'widget_block_dynamic_classname', $classname, $block_name );
}
```
[apply\_filters( 'widget\_block\_dynamic\_classname', string $classname, string $block\_name )](../../hooks/widget_block_dynamic_classname)
The classname used in the block widget’s container HTML.
| Uses | Description |
| --- | --- |
| [parse\_blocks()](../../functions/parse_blocks) wp-includes/blocks.php | Parses blocks out of a content 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\_Widget\_Block::widget()](widget) wp-includes/widgets/class-wp-widget-block.php | Outputs the content for the current Block widget instance. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_Widget_Block::widget( array $args, array $instance ) WP\_Widget\_Block::widget( array $args, array $instance )
=========================================================
Outputs the content for the current Block widget instance.
`$args` array Required Display arguments including `'before_title'`, `'after_title'`, `'before_widget'`, and `'after_widget'`. `$instance` array Required Settings for the current Block widget instance. File: `wp-includes/widgets/class-wp-widget-block.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-block.php/)
```
public function widget( $args, $instance ) {
$instance = wp_parse_args( $instance, $this->default_instance );
echo str_replace(
'widget_block',
$this->get_dynamic_classname( $instance['content'] ),
$args['before_widget']
);
/**
* Filters the content of the Block widget before output.
*
* @since 5.8.0
*
* @param string $content The widget content.
* @param array $instance Array of settings for the current widget.
* @param WP_Widget_Block $widget Current Block widget instance.
*/
echo apply_filters(
'widget_block_content',
$instance['content'],
$instance,
$this
);
echo $args['after_widget'];
}
```
[apply\_filters( 'widget\_block\_content', string $content, array $instance, WP\_Widget\_Block $widget )](../../hooks/widget_block_content)
Filters the content of the Block widget before output.
| Uses | Description |
| --- | --- |
| [WP\_Widget\_Block::get\_dynamic\_classname()](get_dynamic_classname) wp-includes/widgets/class-wp-widget-block.php | Calculates the classname to use in the block widget’s container HTML. |
| [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. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress Walker_CategoryDropdown::start_el( string $output, WP_Term $data_object, int $depth, array $args = array(), int $current_object_id ) Walker\_CategoryDropdown::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 Required Depth of category. Used for padding. `$args` array Optional Uses `'selected'`, `'show_count'`, and `'value_field'` keys, if they exist.
See [wp\_dropdown\_categories()](../../functions/wp_dropdown_categories) . More Arguments from wp\_dropdown\_categories( ... $args ) Array or query string of term query parameters.
* `taxonomy`string|string[]Taxonomy name, or array of taxonomy names, to which results should be limited.
* `object_ids`int|int[]Object ID, or array of object IDs. Results will be limited to terms associated with these objects.
* `orderby`stringField(s) to order terms by. Accepts:
+ Term fields (`'name'`, `'slug'`, `'term_group'`, `'term_id'`, `'id'`, `'description'`, `'parent'`, `'term_order'`). Unless `$object_ids` is not empty, `'term_order'` is treated the same as `'term_id'`.
+ `'count'` to use the number of objects associated with the term.
+ `'include'` to match the `'order'` of the `$include` param.
+ `'slug__in'` to match the `'order'` of the `$slug` param.
+ `'meta_value'`
+ `'meta_value_num'`.
+ The value of `$meta_key`.
+ The array keys of `$meta_query`.
+ `'none'` to omit the ORDER BY clause. Default `'name'`.
* `order`stringWhether to order terms in ascending or descending order.
Accepts `'ASC'` (ascending) or `'DESC'` (descending).
Default `'ASC'`.
* `hide_empty`bool|intWhether to hide terms not assigned to any posts. Accepts `1|true` or `0|false`. Default `1|true`.
* `include`int[]|stringArray or comma/space-separated string of term IDs to include.
Default empty array.
* `exclude`int[]|stringArray or comma/space-separated string of term IDs to exclude.
If `$include` is non-empty, `$exclude` is ignored.
Default empty array.
* `exclude_tree`int[]|stringArray or comma/space-separated string of term IDs to exclude along with all of their descendant terms. If `$include` is non-empty, `$exclude_tree` is ignored. Default empty array.
* `number`int|stringMaximum number of terms to return. Accepts ``''`|0` (all) or any positive number. Default ``''`|0` (all). Note that `$number` may not return accurate results when coupled with `$object_ids`.
See #41796 for details.
* `offset`intThe number by which to offset the terms query.
* `fields`stringTerm fields to query for. Accepts:
+ `'all'` Returns an array of complete term objects (`WP_Term[]`).
+ `'all_with_object_id'` Returns an array of term objects with the `'object_id'` param (`WP_Term[]`). Works only when the `$object_ids` parameter is populated.
+ `'ids'` Returns an array of term IDs (`int[]`).
+ `'tt_ids'` Returns an array of term taxonomy IDs (`int[]`).
+ `'names'` Returns an array of term names (`string[]`).
+ `'slugs'` Returns an array of term slugs (`string[]`).
+ `'count'` Returns the number of matching terms (`int`).
+ `'id=>parent'` Returns an associative array of parent term IDs, keyed by term ID (`int[]`).
+ `'id=>name'` Returns an associative array of term names, keyed by term ID (`string[]`).
+ `'id=>slug'` Returns an associative array of term slugs, keyed by term ID (`string[]`). Default `'all'`.
* `count`boolWhether to return a term count. If true, will take precedence over `$fields`. Default false.
* `name`string|string[]Name or array of names to return term(s) for.
* `slug`string|string[]Slug or array of slugs to return term(s) for.
* `term_taxonomy_id`int|int[]Term taxonomy ID, or array of term taxonomy IDs, to match when querying terms.
* `hierarchical`boolWhether to include terms that have non-empty descendants (even if `$hide_empty` is set to true). Default true.
* `search`stringSearch criteria to match terms. Will be SQL-formatted with wildcards before and after.
* `name__like`stringRetrieve terms with criteria by which a term is LIKE `$name__like`.
* `description__like`stringRetrieve terms where the description is LIKE `$description__like`.
* `pad_counts`boolWhether to pad the quantity of a term's children in the quantity of each term's "count" object variable. Default false.
* `get`stringWhether to return terms regardless of ancestry or whether the terms are empty. Accepts `'all'` or `''` (disabled). Default `''`.
* `child_of`intTerm ID to retrieve child terms of. If multiple taxonomies are passed, `$child_of` is ignored. Default 0.
* `parent`intParent term ID to retrieve direct-child terms of.
* `childless`boolTrue to limit results to terms that have no children.
This parameter has no effect on non-hierarchical taxonomies.
Default false.
* `cache_domain`stringUnique cache key to be produced when this query is stored in an object cache. Default `'core'`.
* `update_term_meta_cache`boolWhether to prime meta caches for matched terms. Default true.
* `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.
Default: `array()`
`$current_object_id` int Optional ID of the current category. Default 0. File: `wp-includes/class-walker-category-dropdown.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-category-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.
$category = $data_object;
$pad = str_repeat( ' ', $depth * 3 );
/** This filter is documented in wp-includes/category-template.php */
$cat_name = apply_filters( 'list_cats', $category->name, $category );
if ( isset( $args['value_field'] ) && isset( $category->{$args['value_field']} ) ) {
$value_field = $args['value_field'];
} else {
$value_field = 'term_id';
}
$output .= "\t<option class=\"level-$depth\" value=\"" . esc_attr( $category->{$value_field} ) . '"';
// Type-juggling causes false matches, so we force everything to a string.
if ( (string) $category->{$value_field} === (string) $args['selected'] ) {
$output .= ' selected="selected"';
}
$output .= '>';
$output .= $pad . $cat_name;
if ( $args['show_count'] ) {
$output .= ' (' . number_format_i18n( $category->count ) . ')';
}
$output .= "</option>\n";
}
```
[apply\_filters( 'list\_cats', string $element, WP\_Term|null $category )](../../hooks/list_cats)
Filters a taxonomy drop-down display element.
| Uses | Description |
| --- | --- |
| [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. |
| [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 WP_Http_Streams::verify_ssl_certificate( resource $stream, string $host ): bool WP\_Http\_Streams::verify\_ssl\_certificate( resource $stream, string $host ): bool
===================================================================================
Verifies the received SSL certificate against its Common Names and subjectAltName fields.
PHP’s SSL verifications only verify that it’s a valid Certificate, it doesn’t verify if the certificate is valid for the hostname which was requested.
This function verifies the requested hostname against certificate’s subjectAltName field, if that is empty, or contains no DNS entries, a fallback to the Common Name field is used.
IP Address support is included if the request is being made to an IP address.
`$stream` resource Required The PHP Stream which the SSL request is being made over `$host` string Required The hostname being requested bool If the certificate presented in $stream is valid for $host
File: `wp-includes/class-wp-http-streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-streams.php/)
```
public static function verify_ssl_certificate( $stream, $host ) {
$context_options = stream_context_get_options( $stream );
if ( empty( $context_options['ssl']['peer_certificate'] ) ) {
return false;
}
$cert = openssl_x509_parse( $context_options['ssl']['peer_certificate'] );
if ( ! $cert ) {
return false;
}
/*
* If the request is being made to an IP address, we'll validate against IP fields
* in the cert (if they exist)
*/
$host_type = ( WP_Http::is_ip_address( $host ) ? 'ip' : 'dns' );
$certificate_hostnames = array();
if ( ! empty( $cert['extensions']['subjectAltName'] ) ) {
$match_against = preg_split( '/,\s*/', $cert['extensions']['subjectAltName'] );
foreach ( $match_against as $match ) {
list( $match_type, $match_host ) = explode( ':', $match );
if ( strtolower( trim( $match_type ) ) === $host_type ) { // IP: or DNS:
$certificate_hostnames[] = strtolower( trim( $match_host ) );
}
}
} elseif ( ! empty( $cert['subject']['CN'] ) ) {
// Only use the CN when the certificate includes no subjectAltName extension.
$certificate_hostnames[] = strtolower( $cert['subject']['CN'] );
}
// Exact hostname/IP matches.
if ( in_array( strtolower( $host ), $certificate_hostnames, true ) ) {
return true;
}
// IP's can't be wildcards, Stop processing.
if ( 'ip' === $host_type ) {
return false;
}
// Test to see if the domain is at least 2 deep for wildcard support.
if ( substr_count( $host, '.' ) < 2 ) {
return false;
}
// Wildcard subdomains certs (*.example.com) are valid for a.example.com but not a.b.example.com.
$wildcard_host = preg_replace( '/^[^.]+\./', '*.', $host );
return in_array( strtolower( $wildcard_host ), $certificate_hostnames, true );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Http::is\_ip\_address()](../wp_http/is_ip_address) wp-includes/class-wp-http.php | Determines if a specified string represents an IP address or not. |
| Used By | Description |
| --- | --- |
| [WP\_Http\_Streams::request()](request) wp-includes/class-wp-http-streams.php | Send a HTTP request to a URI using PHP Streams. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_Http_Streams::test( array $args = array() ): bool WP\_Http\_Streams::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-streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-streams.php/)
```
public static function test( $args = array() ) {
if ( ! function_exists( 'stream_socket_client' ) ) {
return false;
}
$is_ssl = isset( $args['ssl'] ) && $args['ssl'];
if ( $is_ssl ) {
if ( ! extension_loaded( 'openssl' ) ) {
return false;
}
if ( ! function_exists( 'openssl_x509_parse' ) ) {
return false;
}
}
/**
* Filters whether streams 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 Request arguments.
*/
return apply_filters( 'use_streams_transport', true, $args );
}
```
[apply\_filters( 'use\_streams\_transport', bool $use\_class, array $args )](../../hooks/use_streams_transport)
Filters whether streams 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 |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Combined with the fsockopen transport and switched to stream\_socket\_client(). |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Http_Streams::request( string $url, string|array $args = array() ): array|WP_Error WP\_Http\_Streams::request( string $url, string|array $args = array() ): array|WP\_Error
========================================================================================
Send a HTTP request to a URI using PHP Streams.
* [WP\_Http::request()](../wp_http/request): For default options descriptions.
`$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-streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-streams.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 );
$parsed_url = parse_url( $url );
$connect_host = $parsed_url['host'];
$secure_transport = ( 'ssl' === $parsed_url['scheme'] || 'https' === $parsed_url['scheme'] );
if ( ! isset( $parsed_url['port'] ) ) {
if ( 'ssl' === $parsed_url['scheme'] || 'https' === $parsed_url['scheme'] ) {
$parsed_url['port'] = 443;
$secure_transport = true;
} else {
$parsed_url['port'] = 80;
}
}
// Always pass a path, defaulting to the root in cases such as http://example.com.
if ( ! isset( $parsed_url['path'] ) ) {
$parsed_url['path'] = '/';
}
if ( isset( $parsed_args['headers']['Host'] ) || isset( $parsed_args['headers']['host'] ) ) {
if ( isset( $parsed_args['headers']['Host'] ) ) {
$parsed_url['host'] = $parsed_args['headers']['Host'];
} else {
$parsed_url['host'] = $parsed_args['headers']['host'];
}
unset( $parsed_args['headers']['Host'], $parsed_args['headers']['host'] );
}
/*
* Certain versions of PHP have issues with 'localhost' and IPv6, It attempts to connect
* to ::1, which fails when the server is not set up for it. For compatibility, always
* connect to the IPv4 address.
*/
if ( 'localhost' === strtolower( $connect_host ) ) {
$connect_host = '127.0.0.1';
}
$connect_host = $secure_transport ? 'ssl://' . $connect_host : 'tcp://' . $connect_host;
$is_local = isset( $parsed_args['local'] ) && $parsed_args['local'];
$ssl_verify = isset( $parsed_args['sslverify'] ) && $parsed_args['sslverify'];
if ( $is_local ) {
/**
* Filters whether SSL should be verified for local HTTP API 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.
*/
$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 );
}
$proxy = new WP_HTTP_Proxy();
$context = stream_context_create(
array(
'ssl' => array(
'verify_peer' => $ssl_verify,
// 'CN_match' => $parsed_url['host'], // This is handled by self::verify_ssl_certificate().
'capture_peer_cert' => $ssl_verify,
'SNI_enabled' => true,
'cafile' => $parsed_args['sslcertificates'],
'allow_self_signed' => ! $ssl_verify,
),
)
);
$timeout = (int) floor( $parsed_args['timeout'] );
$utimeout = $timeout == $parsed_args['timeout'] ? 0 : 1000000 * $parsed_args['timeout'] % 1000000;
$connect_timeout = max( $timeout, 1 );
// Store error number.
$connection_error = null;
// Store error string.
$connection_error_str = null;
if ( ! WP_DEBUG ) {
// In the event that the SSL connection fails, silence the many PHP warnings.
if ( $secure_transport ) {
$error_reporting = error_reporting( 0 );
}
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
$handle = @stream_socket_client(
'tcp://' . $proxy->host() . ':' . $proxy->port(),
$connection_error,
$connection_error_str,
$connect_timeout,
STREAM_CLIENT_CONNECT,
$context
);
} else {
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
$handle = @stream_socket_client(
$connect_host . ':' . $parsed_url['port'],
$connection_error,
$connection_error_str,
$connect_timeout,
STREAM_CLIENT_CONNECT,
$context
);
}
if ( $secure_transport ) {
error_reporting( $error_reporting );
}
} else {
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
$handle = stream_socket_client(
'tcp://' . $proxy->host() . ':' . $proxy->port(),
$connection_error,
$connection_error_str,
$connect_timeout,
STREAM_CLIENT_CONNECT,
$context
);
} else {
$handle = stream_socket_client(
$connect_host . ':' . $parsed_url['port'],
$connection_error,
$connection_error_str,
$connect_timeout,
STREAM_CLIENT_CONNECT,
$context
);
}
}
if ( false === $handle ) {
// SSL connection failed due to expired/invalid cert, or, OpenSSL configuration is broken.
if ( $secure_transport && 0 === $connection_error && '' === $connection_error_str ) {
return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
}
return new WP_Error( 'http_request_failed', $connection_error . ': ' . $connection_error_str );
}
// Verify that the SSL certificate is valid for this request.
if ( $secure_transport && $ssl_verify && ! $proxy->is_enabled() ) {
if ( ! self::verify_ssl_certificate( $handle, $parsed_url['host'] ) ) {
return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
}
}
stream_set_timeout( $handle, $timeout, $utimeout );
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) { // Some proxies require full URL in this field.
$request_path = $url;
} else {
$request_path = $parsed_url['path'] . ( isset( $parsed_url['query'] ) ? '?' . $parsed_url['query'] : '' );
}
$headers = strtoupper( $parsed_args['method'] ) . ' ' . $request_path . ' HTTP/' . $parsed_args['httpversion'] . "\r\n";
$include_port_in_host_header = (
( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
|| ( 'http' === $parsed_url['scheme'] && 80 != $parsed_url['port'] )
|| ( 'https' === $parsed_url['scheme'] && 443 != $parsed_url['port'] )
);
if ( $include_port_in_host_header ) {
$headers .= 'Host: ' . $parsed_url['host'] . ':' . $parsed_url['port'] . "\r\n";
} else {
$headers .= 'Host: ' . $parsed_url['host'] . "\r\n";
}
if ( isset( $parsed_args['user-agent'] ) ) {
$headers .= 'User-agent: ' . $parsed_args['user-agent'] . "\r\n";
}
if ( is_array( $parsed_args['headers'] ) ) {
foreach ( (array) $parsed_args['headers'] as $header => $header_value ) {
$headers .= $header . ': ' . $header_value . "\r\n";
}
} else {
$headers .= $parsed_args['headers'];
}
if ( $proxy->use_authentication() ) {
$headers .= $proxy->authentication_header() . "\r\n";
}
$headers .= "\r\n";
if ( ! is_null( $parsed_args['body'] ) ) {
$headers .= $parsed_args['body'];
}
fwrite( $handle, $headers );
if ( ! $parsed_args['blocking'] ) {
stream_set_blocking( $handle, 0 );
fclose( $handle );
return array(
'headers' => array(),
'body' => '',
'response' => array(
'code' => false,
'message' => false,
),
'cookies' => array(),
);
}
$response = '';
$body_started = false;
$keep_reading = true;
$block_size = 4096;
if ( isset( $parsed_args['limit_response_size'] ) ) {
$block_size = min( $block_size, $parsed_args['limit_response_size'] );
}
// If streaming to a file setup the file handle.
if ( $parsed_args['stream'] ) {
if ( ! WP_DEBUG ) {
$stream_handle = @fopen( $parsed_args['filename'], 'w+' );
} else {
$stream_handle = fopen( $parsed_args['filename'], 'w+' );
}
if ( ! $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']
)
);
}
$bytes_written = 0;
while ( ! feof( $handle ) && $keep_reading ) {
$block = fread( $handle, $block_size );
if ( ! $body_started ) {
$response .= $block;
if ( strpos( $response, "\r\n\r\n" ) ) {
$processed_response = WP_Http::processResponse( $response );
$body_started = true;
$block = $processed_response['body'];
unset( $response );
$processed_response['body'] = '';
}
}
$this_block_size = strlen( $block );
if ( isset( $parsed_args['limit_response_size'] )
&& ( $bytes_written + $this_block_size ) > $parsed_args['limit_response_size']
) {
$this_block_size = ( $parsed_args['limit_response_size'] - $bytes_written );
$block = substr( $block, 0, $this_block_size );
}
$bytes_written_to_file = fwrite( $stream_handle, $block );
if ( $bytes_written_to_file != $this_block_size ) {
fclose( $handle );
fclose( $stream_handle );
return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
}
$bytes_written += $bytes_written_to_file;
$keep_reading = (
! isset( $parsed_args['limit_response_size'] )
|| $bytes_written < $parsed_args['limit_response_size']
);
}
fclose( $stream_handle );
} else {
$header_length = 0;
while ( ! feof( $handle ) && $keep_reading ) {
$block = fread( $handle, $block_size );
$response .= $block;
if ( ! $body_started && strpos( $response, "\r\n\r\n" ) ) {
$header_length = strpos( $response, "\r\n\r\n" ) + 4;
$body_started = true;
}
$keep_reading = (
! $body_started
|| ! isset( $parsed_args['limit_response_size'] )
|| strlen( $response ) < ( $header_length + $parsed_args['limit_response_size'] )
);
}
$processed_response = WP_Http::processResponse( $response );
unset( $response );
}
fclose( $handle );
$processed_headers = WP_Http::processHeaders( $processed_response['headers'], $url );
$response = array(
'headers' => $processed_headers['headers'],
// Not yet processed.
'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 the body was chunk encoded, then decode it.
if ( ! empty( $processed_response['body'] )
&& isset( $processed_headers['headers']['transfer-encoding'] )
&& 'chunked' === $processed_headers['headers']['transfer-encoding']
) {
$processed_response['body'] = WP_Http::chunkTransferDecode( $processed_response['body'] );
}
if ( true === $parsed_args['decompress']
&& true === WP_Http_Encoding::should_decode( $processed_headers['headers'] )
) {
$processed_response['body'] = WP_Http_Encoding::decompress( $processed_response['body'] );
}
if ( isset( $parsed_args['limit_response_size'] )
&& strlen( $processed_response['body'] ) > $parsed_args['limit_response_size']
) {
$processed_response['body'] = substr( $processed_response['body'], 0, $parsed_args['limit_response_size'] );
}
$response['body'] = $processed_response['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.
| 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\_Streams::verify\_ssl\_certificate()](verify_ssl_certificate) wp-includes/class-wp-http-streams.php | Verifies the received SSL certificate against its Common Names and subjectAltName fields. |
| [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::processResponse()](../wp_http/processresponse) wp-includes/class-wp-http.php | Parses the responses and splits the parts into headers and body. |
| [WP\_Http::processHeaders()](../wp_http/processheaders) wp-includes/class-wp-http.php | Transforms header string into an array. |
| [WP\_Http::chunkTransferDecode()](../wp_http/chunktransferdecode) wp-includes/class-wp-http.php | Decodes chunk transfer-encoding, based off the HTTP 1.1 specification. |
| [\_\_()](../../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 |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Combined with the fsockopen transport and switched to stream\_socket\_client(). |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress WP_REST_Autosaves_Controller::get_item( WP_REST_Request $request ): WP_Post|WP_Error WP\_REST\_Autosaves\_Controller::get\_item( WP\_REST\_Request $request ): WP\_Post|WP\_Error
============================================================================================
Get the autosave, if the ID is valid.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_Post](../wp_post)|[WP\_Error](../wp_error) Revision post object if ID is valid, [WP\_Error](../wp_error) otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php/)
```
public function get_item( $request ) {
$parent_id = (int) $request->get_param( 'parent' );
if ( $parent_id <= 0 ) {
return new WP_Error(
'rest_post_invalid_id',
__( 'Invalid post parent ID.' ),
array( 'status' => 404 )
);
}
$autosave = wp_get_post_autosave( $parent_id );
if ( ! $autosave ) {
return new WP_Error(
'rest_post_no_autosave',
__( 'There is no autosave revision for this post.' ),
array( 'status' => 404 )
);
}
$response = $this->prepare_item_for_response( $autosave, $request );
return $response;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Autosaves\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Prepares the revision for the REST response. |
| [wp\_get\_post\_autosave()](../../functions/wp_get_post_autosave) wp-includes/revision.php | Retrieves the autosaved data of the specified post. |
| [\_\_()](../../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.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Autosaves_Controller::prepare_item_for_response( WP_Post $item, WP_REST_Request $request ): WP_REST_Response WP\_REST\_Autosaves\_Controller::prepare\_item\_for\_response( WP\_Post $item, WP\_REST\_Request $request ): WP\_REST\_Response
===============================================================================================================================
Prepares the revision for the REST response.
`$item` [WP\_Post](../wp_post) Required Post revision 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-autosaves-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php/)
```
public function prepare_item_for_response( $item, $request ) {
// Restores the more descriptive, specific name for use within this method.
$post = $item;
$response = $this->revisions_controller->prepare_item_for_response( $post, $request );
$fields = $this->get_fields_for_response( $request );
if ( in_array( 'preview_link', $fields, true ) ) {
$parent_id = wp_is_post_autosave( $post );
$preview_post_id = false === $parent_id ? $post->ID : $parent_id;
$preview_query_args = array();
if ( false !== $parent_id ) {
$preview_query_args['preview_id'] = $parent_id;
$preview_query_args['preview_nonce'] = wp_create_nonce( 'post_preview_' . $parent_id );
}
$response->data['preview_link'] = get_preview_post_link( $preview_post_id, $preview_query_args );
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$response->data = $this->add_additional_fields_to_object( $response->data, $request );
$response->data = $this->filter_response_by_context( $response->data, $context );
/**
* Filters a revision returned from the REST API.
*
* Allows modification of the revision right before it is returned.
*
* @since 5.0.0
*
* @param WP_REST_Response $response The response object.
* @param WP_Post $post The original revision object.
* @param WP_REST_Request $request Request used to generate the response.
*/
return apply_filters( 'rest_prepare_autosave', $response, $post, $request );
}
```
[apply\_filters( 'rest\_prepare\_autosave', WP\_REST\_Response $response, WP\_Post $post, WP\_REST\_Request $request )](../../hooks/rest_prepare_autosave)
Filters a revision returned from the REST API.
| Uses | Description |
| --- | --- |
| [get\_preview\_post\_link()](../../functions/get_preview_post_link) wp-includes/link-template.php | Retrieves the URL used for the post preview. |
| [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\_is\_post\_autosave()](../../functions/wp_is_post_autosave) wp-includes/revision.php | Determines if the specified post is an autosave. |
| [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\_Autosaves\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Creates, updates or deletes an autosave revision. |
| [WP\_REST\_Autosaves\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Get the autosave, if the ID is valid. |
| [WP\_REST\_Autosaves\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Gets a collection of autosaves using wp\_get\_post\_autosave. |
| 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. |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Autosaves_Controller::get_items( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Autosaves\_Controller::get\_items( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=======================================================================================================
Gets a collection of autosaves using wp\_get\_post\_autosave.
Contains the user’s autosave, for empty if it doesn’t exist.
`$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-autosaves-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php/)
```
public function get_items( $request ) {
$parent = $this->get_parent( $request['id'] );
if ( is_wp_error( $parent ) ) {
return $parent;
}
$response = array();
$parent_id = $parent->ID;
$revisions = wp_get_post_revisions( $parent_id, array( 'check_enabled' => false ) );
foreach ( $revisions as $revision ) {
if ( false !== strpos( $revision->post_name, "{$parent_id}-autosave" ) ) {
$data = $this->prepare_item_for_response( $revision, $request );
$response[] = $this->prepare_response_for_collection( $data );
}
}
return rest_ensure_response( $response );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Autosaves\_Controller::get\_parent()](get_parent) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Get the parent post. |
| [WP\_REST\_Autosaves\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Prepares the revision for the REST response. |
| [wp\_get\_post\_revisions()](../../functions/wp_get_post_revisions) wp-includes/revision.php | Returns all revisions of specified post. |
| [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.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Autosaves_Controller::create_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Autosaves\_Controller::create\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=========================================================================================================
Creates, updates or deletes an autosave revision.
`$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-autosaves-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php/)
```
public function create_item( $request ) {
if ( ! defined( 'DOING_AUTOSAVE' ) ) {
define( 'DOING_AUTOSAVE', true );
}
$post = get_post( $request['id'] );
if ( is_wp_error( $post ) ) {
return $post;
}
$prepared_post = $this->parent_controller->prepare_item_for_database( $request );
$prepared_post->ID = $post->ID;
$user_id = get_current_user_id();
// We need to check post lock to ensure the original author didn't leave their browser tab open.
if ( ! function_exists( 'wp_check_post_lock' ) ) {
require_once ABSPATH . 'wp-admin/includes/post.php';
}
$post_lock = wp_check_post_lock( $post->ID );
$is_draft = 'draft' === $post->post_status || 'auto-draft' === $post->post_status;
if ( $is_draft && (int) $post->post_author === $user_id && ! $post_lock ) {
// Draft posts for the same author: autosaving updates the post and does not create a revision.
// Convert the post object to an array and add slashes, wp_update_post() expects escaped array.
$autosave_id = wp_update_post( wp_slash( (array) $prepared_post ), true );
} else {
// Non-draft posts: create or update the post autosave.
$autosave_id = $this->create_post_autosave( (array) $prepared_post );
}
if ( is_wp_error( $autosave_id ) ) {
return $autosave_id;
}
$autosave = get_post( $autosave_id );
$request->set_param( 'context', 'edit' );
$response = $this->prepare_item_for_response( $autosave, $request );
$response = rest_ensure_response( $response );
return $response;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Autosaves\_Controller::create\_post\_autosave()](create_post_autosave) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Creates autosave for the specified post. |
| [WP\_REST\_Autosaves\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Prepares the revision for the REST response. |
| [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. |
| [wp\_update\_post()](../../functions/wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [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. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Autosaves_Controller::create_post_autosave( array $post_data ): mixed WP\_REST\_Autosaves\_Controller::create\_post\_autosave( array $post\_data ): mixed
===================================================================================
Creates autosave for the specified post.
From wp-admin/post.php.
`$post_data` array Required Associative array containing the post data. mixed The autosave revision ID or [WP\_Error](../wp_error).
File: `wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php/)
```
public function create_post_autosave( $post_data ) {
$post_id = (int) $post_data['ID'];
$post = get_post( $post_id );
if ( is_wp_error( $post ) ) {
return $post;
}
$user_id = get_current_user_id();
// Store one autosave per author. If there is already an autosave, overwrite it.
$old_autosave = wp_get_post_autosave( $post_id, $user_id );
if ( $old_autosave ) {
$new_autosave = _wp_post_revision_data( $post_data, true );
$new_autosave['ID'] = $old_autosave->ID;
$new_autosave['post_author'] = $user_id;
// If the new autosave has the same content as the post, delete the autosave.
$autosave_is_different = false;
foreach ( array_intersect( array_keys( $new_autosave ), array_keys( _wp_post_revision_fields( $post ) ) ) as $field ) {
if ( normalize_whitespace( $new_autosave[ $field ] ) !== normalize_whitespace( $post->$field ) ) {
$autosave_is_different = true;
break;
}
}
if ( ! $autosave_is_different ) {
wp_delete_post_revision( $old_autosave->ID );
return new WP_Error(
'rest_autosave_no_changes',
__( 'There is nothing to save. The autosave and the post content are the same.' ),
array( 'status' => 400 )
);
}
/** This filter is documented in wp-admin/post.php */
do_action( 'wp_creating_autosave', $new_autosave );
// wp_update_post() expects escaped array.
return wp_update_post( wp_slash( $new_autosave ) );
}
// Create the new autosave as a special post revision.
return _wp_put_post_revision( $post_data, true );
}
```
[do\_action( 'wp\_creating\_autosave', array $new\_autosave )](../../hooks/wp_creating_autosave)
Fires before an autosave is stored.
| Uses | Description |
| --- | --- |
| [\_wp\_post\_revision\_data()](../../functions/_wp_post_revision_data) wp-includes/revision.php | Returns a post array ready to be inserted into the posts table as a post revision. |
| [normalize\_whitespace()](../../functions/normalize_whitespace) wp-includes/formatting.php | Normalizes EOL characters and strips duplicate whitespace. |
| [wp\_update\_post()](../../functions/wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [wp\_delete\_post\_revision()](../../functions/wp_delete_post_revision) wp-includes/revision.php | Deletes a revision. |
| [\_wp\_put\_post\_revision()](../../functions/_wp_put_post_revision) wp-includes/revision.php | Inserts post data into the posts table as a post revision. |
| [wp\_get\_post\_autosave()](../../functions/wp_get_post_autosave) wp-includes/revision.php | Retrieves the autosaved data of the specified post. |
| [\_wp\_post\_revision\_fields()](../../functions/_wp_post_revision_fields) wp-includes/revision.php | Determines which fields of posts are to be saved in revisions. |
| [\_\_()](../../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. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [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. |
| [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\_Autosaves\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Creates, updates or deletes an autosave revision. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Autosaves_Controller::get_parent( int $parent_id ): WP_Post|WP_Error WP\_REST\_Autosaves\_Controller::get\_parent( int $parent\_id ): WP\_Post|WP\_Error
===================================================================================
Get the parent post.
`$parent_id` int Required Supplied ID. [WP\_Post](../wp_post)|[WP\_Error](../wp_error) Post object if ID is valid, [WP\_Error](../wp_error) otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php/)
```
protected function get_parent( $parent_id ) {
return $this->revisions_controller->get_parent( $parent_id );
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Autosaves\_Controller::get\_items\_permissions\_check()](get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Checks if a given request has access to get autosaves. |
| [WP\_REST\_Autosaves\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Gets a collection of autosaves using wp\_get\_post\_autosave. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Autosaves_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Autosaves\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=============================================================================================================
Checks if a given request has access to get autosaves.
`$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-autosaves-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php/)
```
public function get_items_permissions_check( $request ) {
$parent = $this->get_parent( $request['id'] );
if ( is_wp_error( $parent ) ) {
return $parent;
}
if ( ! current_user_can( 'edit_post', $parent->ID ) ) {
return new WP_Error(
'rest_cannot_read',
__( 'Sorry, you are not allowed to view autosaves of this post.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Autosaves\_Controller::get\_parent()](get_parent) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Get the parent post. |
| [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.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Autosaves_Controller::register_routes() WP\_REST\_Autosaves\_Controller::register\_routes()
===================================================
Registers the routes for autosaves.
* [register\_rest\_route()](../../functions/register_rest_route)
File: `wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php/)
```
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->parent_base . '/(?P<id>[\d]+)/' . $this->rest_base,
array(
'args' => array(
'parent' => array(
'description' => __( 'The ID for the parent of the autosave.' ),
'type' => 'integer',
),
),
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' => $this->parent_controller->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
register_rest_route(
$this->namespace,
'/' . $this->parent_base . '/(?P<parent>[\d]+)/' . $this->rest_base . '/(?P<id>[\d]+)',
array(
'args' => array(
'parent' => array(
'description' => __( 'The ID for the parent of the autosave.' ),
'type' => 'integer',
),
'id' => array(
'description' => __( 'The ID for the autosave.' ),
'type' => 'integer',
),
),
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this->revisions_controller, '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\_Autosaves\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Retrieves the query params for the autosaves collection. |
| [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.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Autosaves_Controller::get_collection_params(): array WP\_REST\_Autosaves\_Controller::get\_collection\_params(): array
=================================================================
Retrieves the query params for the autosaves collection.
array Collection parameters.
File: `wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php/)
```
public function get_collection_params() {
return array(
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
);
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Autosaves\_Controller::register\_routes()](register_routes) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Registers the routes for autosaves. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Autosaves_Controller::__construct( string $parent_post_type ) WP\_REST\_Autosaves\_Controller::\_\_construct( string $parent\_post\_type )
============================================================================
Constructor.
`$parent_post_type` string Required Post type of the parent. File: `wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php/)
```
public function __construct( $parent_post_type ) {
$this->parent_post_type = $parent_post_type;
$post_type_object = get_post_type_object( $parent_post_type );
$parent_controller = $post_type_object->get_rest_controller();
if ( ! $parent_controller ) {
$parent_controller = new WP_REST_Posts_Controller( $parent_post_type );
}
$this->parent_controller = $parent_controller;
$this->revisions_controller = new WP_REST_Revisions_Controller( $parent_post_type );
$this->rest_base = 'autosaves';
$this->namespace = ! empty( $post_type_object->rest_namespace ) ? $post_type_object->rest_namespace : 'wp/v2';
$this->parent_base = ! empty( $post_type_object->rest_base ) ? $post_type_object->rest_base : $post_type_object->name;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Revisions\_Controller::\_\_construct()](../wp_rest_revisions_controller/__construct) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Constructor. |
| [WP\_REST\_Posts\_Controller::\_\_construct()](../wp_rest_posts_controller/__construct) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Constructor. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| 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.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Autosaves_Controller::create_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Autosaves\_Controller::create\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
===============================================================================================================
Checks if a given request has access to create an autosave revision.
Autosave revisions inherit permissions from the parent post, check if the current user has permission to edit the post.
`$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 the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php/)
```
public function create_item_permissions_check( $request ) {
$id = $request->get_param( 'id' );
if ( empty( $id ) ) {
return new WP_Error(
'rest_post_invalid_id',
__( 'Invalid item ID.' ),
array( 'status' => 404 )
);
}
return $this->parent_controller->update_item_permissions_check( $request );
}
```
| 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. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Autosaves_Controller::get_item_schema(): array WP\_REST\_Autosaves\_Controller::get\_item\_schema(): array
===========================================================
Retrieves the autosave’s schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php/)
```
public function get_item_schema() {
if ( $this->schema ) {
return $this->add_additional_fields_schema( $this->schema );
}
$schema = $this->revisions_controller->get_item_schema();
$schema['properties']['preview_link'] = array(
'description' => __( 'Preview link for the post.' ),
'type' => 'string',
'format' => 'uri',
'context' => array( 'edit' ),
'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 |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_Ajax_Response::add( string|array $args = '' ): string WP\_Ajax\_Response::add( string|array $args = '' ): string
==========================================================
Appends data to an XML response based on given arguments.
With `$args` defaults, extra data output would be:
```
<response action='{$action}_$id'>
<$what id='$id' position='$position'>
<response_data><![CDATA[$data]]></response_data>
</$what>
</response>
```
`$args` string|array Optional An array or string of XML response arguments.
* `what`stringXML-RPC response type. Used as a child element of `<response>`.
Default `'object'` (`<object>`).
* `action`string|falseValue to use for the `action` attribute in `<response>`. Will be appended with `_$id` on output. If false, `$action` will default to the value of `$_POST['action']`. Default false.
* `id`int|[WP\_Error](../wp_error)The response ID, used as the response type `id` attribute. Also accepts a `WP_Error` object if the ID does not exist. Default 0.
* `old_id`int|falseThe previous response ID. Used as the value for the response type `old_id` attribute. False hides the attribute. Default false.
* `position`stringValue of the response type `position` attribute. Accepts 1 (bottom), -1 (top), HTML ID (after), or -HTML ID (before). Default 1 (bottom).
* `data`string|[WP\_Error](../wp_error)The response content/message. Also accepts a [WP\_Error](../wp_error) object if the ID does not exist.
* `supplemental`arrayAn array of extra strings that will be output within a `<supplemental>` element as CDATA. Default empty array.
Default: `''`
string XML response.
File: `wp-includes/class-wp-ajax-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-ajax-response.php/)
```
public function add( $args = '' ) {
$defaults = array(
'what' => 'object',
'action' => false,
'id' => '0',
'old_id' => false,
'position' => 1,
'data' => '',
'supplemental' => array(),
);
$parsed_args = wp_parse_args( $args, $defaults );
$position = preg_replace( '/[^a-z0-9:_-]/i', '', $parsed_args['position'] );
$id = $parsed_args['id'];
$what = $parsed_args['what'];
$action = $parsed_args['action'];
$old_id = $parsed_args['old_id'];
$data = $parsed_args['data'];
if ( is_wp_error( $id ) ) {
$data = $id;
$id = 0;
}
$response = '';
if ( is_wp_error( $data ) ) {
foreach ( (array) $data->get_error_codes() as $code ) {
$response .= "<wp_error code='$code'><![CDATA[" . $data->get_error_message( $code ) . ']]></wp_error>';
$error_data = $data->get_error_data( $code );
if ( ! $error_data ) {
continue;
}
$class = '';
if ( is_object( $error_data ) ) {
$class = ' class="' . get_class( $error_data ) . '"';
$error_data = get_object_vars( $error_data );
}
$response .= "<wp_error_data code='$code'$class>";
if ( is_scalar( $error_data ) ) {
$response .= "<![CDATA[$error_data]]>";
} elseif ( is_array( $error_data ) ) {
foreach ( $error_data as $k => $v ) {
$response .= "<$k><![CDATA[$v]]></$k>";
}
}
$response .= '</wp_error_data>';
}
} else {
$response = "<response_data><![CDATA[$data]]></response_data>";
}
$s = '';
if ( is_array( $parsed_args['supplemental'] ) ) {
foreach ( $parsed_args['supplemental'] as $k => $v ) {
$s .= "<$k><![CDATA[$v]]></$k>";
}
$s = "<supplemental>$s</supplemental>";
}
if ( false === $action ) {
$action = $_POST['action'];
}
$x = '';
$x .= "<response action='{$action}_$id'>"; // The action attribute in the xml output is formatted like a nonce action.
$x .= "<$what id='$id' " . ( false === $old_id ? '' : "old_id='$old_id' " ) . "position='$position'>";
$x .= $response;
$x .= $s;
$x .= "</$what>";
$x .= '</response>';
$this->responses[] = $x;
return $x;
}
```
| Uses | Description |
| --- | --- |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Ajax\_Response::\_\_construct()](__construct) wp-includes/class-wp-ajax-response.php | Constructor – Passes args to [WP\_Ajax\_Response::add()](add). |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Ajax_Response::send() WP\_Ajax\_Response::send()
==========================
Display XML formatted responses.
Sets the content type header to text/xml.
This will set the correct content type for the header, output the response xml, then die – ensuring a proper XML response.
File: `wp-includes/class-wp-ajax-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-ajax-response.php/)
```
public function send() {
header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ) );
echo "<?xml version='1.0' encoding='" . get_option( 'blog_charset' ) . "' standalone='yes'?><wp_ajax>";
foreach ( (array) $this->responses as $response ) {
echo $response;
}
echo '</wp_ajax>';
if ( wp_doing_ajax() ) {
wp_die();
} else {
die();
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_doing\_ajax()](../../functions/wp_doing_ajax) wp-includes/load.php | Determines whether the current request is a WordPress Ajax request. |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Ajax_Response::__construct( string|array $args = '' ) WP\_Ajax\_Response::\_\_construct( string|array $args = '' )
============================================================
Constructor – Passes args to [WP\_Ajax\_Response::add()](add).
* [WP\_Ajax\_Response::add()](../wp_ajax_response/add)
`$args` string|array Optional Will be passed to add() method. Default: `''`
File: `wp-includes/class-wp-ajax-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-ajax-response.php/)
```
public function __construct( $args = '' ) {
if ( ! empty( $args ) ) {
$this->add( $args );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Ajax\_Response::add()](add) wp-includes/class-wp-ajax-response.php | Appends data to an XML response based on given arguments. |
| Used By | Description |
| --- | --- |
| [wp\_ajax\_add\_meta()](../../functions/wp_ajax_add_meta) wp-admin/includes/ajax-actions.php | Ajax handler for adding meta. |
| [wp\_ajax\_add\_user()](../../functions/wp_ajax_add_user) wp-admin/includes/ajax-actions.php | Ajax handler for adding a user. |
| [\_wp\_ajax\_delete\_comment\_response()](../../functions/_wp_ajax_delete_comment_response) wp-admin/includes/ajax-actions.php | Sends back current comment total and new page links if they need to be updated. |
| [\_wp\_ajax\_add\_hierarchical\_term()](../../functions/_wp_ajax_add_hierarchical_term) wp-admin/includes/ajax-actions.php | Ajax handler for adding a hierarchical term. |
| [wp\_ajax\_dim\_comment()](../../functions/wp_ajax_dim_comment) wp-admin/includes/ajax-actions.php | Ajax handler to dim a comment. |
| [wp\_ajax\_add\_link\_category()](../../functions/wp_ajax_add_link_category) wp-admin/includes/ajax-actions.php | Ajax handler for adding a link category. |
| [wp\_ajax\_add\_tag()](../../functions/wp_ajax_add_tag) wp-admin/includes/ajax-actions.php | Ajax handler to add a tag. |
| [wp\_ajax\_get\_comments()](../../functions/wp_ajax_get_comments) wp-admin/includes/ajax-actions.php | Ajax handler for getting comments. |
| [wp\_ajax\_replyto\_comment()](../../functions/wp_ajax_replyto_comment) wp-admin/includes/ajax-actions.php | Ajax handler for replying to a comment. |
| [wp\_ajax\_edit\_comment()](../../functions/wp_ajax_edit_comment) wp-admin/includes/ajax-actions.php | Ajax handler for editing a comment. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress POMO_CachedFileReader::POMO_CachedFileReader( $filename ) POMO\_CachedFileReader::POMO\_CachedFileReader( $filename )
===========================================================
This method has been deprecated. Use [POMO\_CachedFileReader::\_\_construct()](../pomo_cachedfilereader/__construct) instead.
PHP4 constructor.
* [POMO\_CachedFileReader::\_\_construct()](../pomo_cachedfilereader/__construct)
File: `wp-includes/pomo/streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/streams.php/)
```
public function POMO_CachedFileReader( $filename ) {
_deprecated_constructor( self::class, '5.4.0', static::class );
self::__construct( $filename );
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_constructor()](../../functions/_deprecated_constructor) wp-includes/functions.php | Marks a constructor as deprecated and informs when it has been used. |
| [POMO\_CachedFileReader::\_\_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 POMO_CachedFileReader::__construct( $filename ) POMO\_CachedFileReader::\_\_construct( $filename )
==================================================
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( $filename ) {
parent::__construct();
$this->_str = file_get_contents( $filename );
if ( false === $this->_str ) {
return false;
}
$this->_pos = 0;
}
```
| Uses | Description |
| --- | --- |
| [POMO\_StringReader::\_\_construct()](../pomo_stringreader/__construct) wp-includes/pomo/streams.php | PHP5 constructor. |
| Used By | Description |
| --- | --- |
| [POMO\_CachedIntFileReader::\_\_construct()](../pomo_cachedintfilereader/__construct) wp-includes/pomo/streams.php | PHP5 constructor. |
| [POMO\_CachedFileReader::POMO\_CachedFileReader()](../pomo_cachedfilereader/pomo_cachedfilereader) wp-includes/pomo/streams.php | PHP4 constructor. |
wordpress WP_Textdomain_Registry::has( string $domain ): bool WP\_Textdomain\_Registry::has( string $domain ): bool
=====================================================
Determines whether any MO file paths are available for the domain.
This is the case if a path has been set for the current locale, or if there is no information stored yet, in which case [\_load\_textdomain\_just\_in\_time()](../../functions/_load_textdomain_just_in_time) will fetch the information first.
`$domain` string Required Text domain. bool Whether any MO file paths are available for the domain.
File: `wp-includes/class-wp-textdomain-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-textdomain-registry.php/)
```
public function has( $domain ) {
return ! empty( $this->current[ $domain ] ) || empty( $this->all[ $domain ] );
}
```
| Used By | Description |
| --- | --- |
| [\_load\_textdomain\_just\_in\_time()](../../functions/_load_textdomain_just_in_time) wp-includes/l10n.php | Loads plugin and theme text domains just-in-time. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Textdomain_Registry::set_cached_mo_files( string $path ) WP\_Textdomain\_Registry::set\_cached\_mo\_files( string $path )
================================================================
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.
Reads and caches all available MO files from a given directory.
`$path` string Required Language directory path. File: `wp-includes/class-wp-textdomain-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-textdomain-registry.php/)
```
private function set_cached_mo_files( $path ) {
$this->cached_mo_files[ $path ] = array();
$mo_files = glob( $path . '/*.mo' );
if ( $mo_files ) {
$this->cached_mo_files[ $path ] = $mo_files;
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Textdomain\_Registry::get\_path\_from\_lang\_dir()](get_path_from_lang_dir) wp-includes/class-wp-textdomain-registry.php | Gets the path to the language directory for the current locale. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Textdomain_Registry::set_custom_path( string $domain, string $path ) WP\_Textdomain\_Registry::set\_custom\_path( string $domain, string $path )
===========================================================================
Sets the custom path to the plugin’s/theme’s languages directory.
Used by [load\_plugin\_textdomain()](../../functions/load_plugin_textdomain) and [load\_theme\_textdomain()](../../functions/load_theme_textdomain) .
`$domain` string Required Text domain. `$path` string Required Language directory path. File: `wp-includes/class-wp-textdomain-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-textdomain-registry.php/)
```
public function set_custom_path( $domain, $path ) {
$this->custom_paths[ $domain ] = untrailingslashit( $path );
}
```
| Uses | Description |
| --- | --- |
| [untrailingslashit()](../../functions/untrailingslashit) wp-includes/formatting.php | Removes trailing forward slashes and backslashes if they exist. |
| Used By | Description |
| --- | --- |
| [load\_plugin\_textdomain()](../../functions/load_plugin_textdomain) wp-includes/l10n.php | Loads a plugin’s translated strings. |
| [load\_muplugin\_textdomain()](../../functions/load_muplugin_textdomain) wp-includes/l10n.php | Loads the translated strings for a plugin residing in the mu-plugins directory. |
| [load\_theme\_textdomain()](../../functions/load_theme_textdomain) wp-includes/l10n.php | Loads the theme’s translated strings. |
wordpress WP_Textdomain_Registry::set( string $domain, string $locale, string|false $path ) WP\_Textdomain\_Registry::set( string $domain, string $locale, string|false $path )
===================================================================================
Sets the language directory path for a specific domain and locale.
Also sets the ‘current’ property for direct access to the path for the current (most recent) locale.
`$domain` string Required Text domain. `$locale` string Required Locale. `$path` string|false Required Language directory path or false if there is none available. File: `wp-includes/class-wp-textdomain-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-textdomain-registry.php/)
```
public function set( $domain, $locale, $path ) {
$this->all[ $domain ][ $locale ] = $path ? trailingslashit( $path ) : false;
$this->current[ $domain ] = $this->all[ $domain ][ $locale ];
}
```
| Uses | Description |
| --- | --- |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| Used By | Description |
| --- | --- |
| [WP\_Textdomain\_Registry::get\_path\_from\_lang\_dir()](get_path_from_lang_dir) wp-includes/class-wp-textdomain-registry.php | Gets the path to the language directory for the current locale. |
| [load\_textdomain()](../../functions/load_textdomain) wp-includes/l10n.php | Loads a .mo file into the text domain $domain. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Textdomain_Registry::get( string $domain, string $locale ): string|false WP\_Textdomain\_Registry::get( string $domain, string $locale ): string|false
=============================================================================
Returns the languages directory path for a specific domain and locale.
`$domain` string Required Text domain. `$locale` string Required Locale. string|false MO file path or false if there is none available.
File: `wp-includes/class-wp-textdomain-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-textdomain-registry.php/)
```
public function get( $domain, $locale ) {
if ( isset( $this->all[ $domain ][ $locale ] ) ) {
return $this->all[ $domain ][ $locale ];
}
return $this->get_path_from_lang_dir( $domain, $locale );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Textdomain\_Registry::get\_path\_from\_lang\_dir()](get_path_from_lang_dir) wp-includes/class-wp-textdomain-registry.php | Gets the path to the language directory for the current locale. |
| Used By | Description |
| --- | --- |
| [\_load\_textdomain\_just\_in\_time()](../../functions/_load_textdomain_just_in_time) wp-includes/l10n.php | Loads plugin and theme text domains just-in-time. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Textdomain_Registry::get_path_from_lang_dir( string $domain, string $locale ): string|false WP\_Textdomain\_Registry::get\_path\_from\_lang\_dir( string $domain, string $locale ): 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. Use [\_get\_path\_to\_translation\_from\_lang\_dir()](../../functions/_get_path_to_translation_from_lang_dir) instead.
Gets the path to the language directory for the current locale.
Checks the plugins and themes language directories as well as any custom directory set via [load\_plugin\_textdomain()](../../functions/load_plugin_textdomain) or [load\_theme\_textdomain()](../../functions/load_theme_textdomain) .
* [\_get\_path\_to\_translation\_from\_lang\_dir()](../../functions/_get_path_to_translation_from_lang_dir)
`$domain` string Required Text domain. `$locale` string Required Locale. string|false Language directory path or false if there is none available.
File: `wp-includes/class-wp-textdomain-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-textdomain-registry.php/)
```
private function get_path_from_lang_dir( $domain, $locale ) {
$locations = array(
WP_LANG_DIR . '/plugins',
WP_LANG_DIR . '/themes',
);
if ( isset( $this->custom_paths[ $domain ] ) ) {
$locations[] = $this->custom_paths[ $domain ];
}
$mofile = "$domain-$locale.mo";
foreach ( $locations as $location ) {
if ( ! isset( $this->cached_mo_files[ $location ] ) ) {
$this->set_cached_mo_files( $location );
}
$path = $location . '/' . $mofile;
if ( in_array( $path, $this->cached_mo_files[ $location ], true ) ) {
$this->set( $domain, $locale, $location );
return trailingslashit( $location );
}
}
// If no path is found for the given locale and a custom path has been set
// using load_plugin_textdomain/load_theme_textdomain, use that one.
if ( 'en_US' !== $locale && isset( $this->custom_paths[ $domain ] ) ) {
$path = trailingslashit( $this->custom_paths[ $domain ] );
$this->set( $domain, $locale, $path );
return $path;
}
$this->set( $domain, $locale, false );
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Textdomain\_Registry::set\_cached\_mo\_files()](set_cached_mo_files) wp-includes/class-wp-textdomain-registry.php | Reads and caches all available MO files from a given directory. |
| [WP\_Textdomain\_Registry::set()](set) wp-includes/class-wp-textdomain-registry.php | Sets the language directory path for a specific domain and locale. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| Used By | Description |
| --- | --- |
| [WP\_Textdomain\_Registry::get()](get) wp-includes/class-wp-textdomain-registry.php | Returns the languages directory path for a specific domain and locale. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress Requests::post( $url, $headers = array(), $data = array(), $options = array() ) Requests::post( $url, $headers = array(), $data = array(), $options = array() )
===============================================================================
Send a POST request
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function post($url, $headers = array(), $data = array(), $options = array()) {
return self::request($url, $headers, $data, self::POST, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests::request()](request) wp-includes/class-requests.php | Main interface for HTTP requests |
wordpress Requests::parse_response( string $headers, string $url, array $req_headers, array $req_data, array $options ): Requests_Response Requests::parse\_response( string $headers, string $url, array $req\_headers, array $req\_data, array $options ): Requests\_Response
====================================================================================================================================
HTTP response parser
`$headers` string Required Full response text including headers and body `$url` string Required Original request URL `$req_headers` array Required Original $headers array passed to [request()](../../functions/request), in case we need to follow redirects `$req_data` array Required Original $data array passed to [request()](../../functions/request), in case we need to follow redirects `$options` array Required Original $options array passed to [request()](../../functions/request), in case we need to follow redirects [Requests\_Response](../requests_response)
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
protected static function parse_response($headers, $url, $req_headers, $req_data, $options) {
$return = new Requests_Response();
if (!$options['blocking']) {
return $return;
}
$return->raw = $headers;
$return->url = (string) $url;
$return->body = '';
if (!$options['filename']) {
$pos = strpos($headers, "\r\n\r\n");
if ($pos === false) {
// Crap!
throw new Requests_Exception('Missing header/body separator', 'requests.no_crlf_separator');
}
$headers = substr($return->raw, 0, $pos);
// Headers will always be separated from the body by two new lines - `\n\r\n\r`.
$body = substr($return->raw, $pos + 4);
if (!empty($body)) {
$return->body = $body;
}
}
// Pretend CRLF = LF for compatibility (RFC 2616, section 19.3)
$headers = str_replace("\r\n", "\n", $headers);
// Unfold headers (replace [CRLF] 1*( SP | HT ) with SP) as per RFC 2616 (section 2.2)
$headers = preg_replace('/\n[ \t]/', ' ', $headers);
$headers = explode("\n", $headers);
preg_match('#^HTTP/(1\.\d)[ \t]+(\d+)#i', array_shift($headers), $matches);
if (empty($matches)) {
throw new Requests_Exception('Response could not be parsed', 'noversion', $headers);
}
$return->protocol_version = (float) $matches[1];
$return->status_code = (int) $matches[2];
if ($return->status_code >= 200 && $return->status_code < 300) {
$return->success = true;
}
foreach ($headers as $header) {
list($key, $value) = explode(':', $header, 2);
$value = trim($value);
preg_replace('#(\s+)#i', ' ', $value);
$return->headers[$key] = $value;
}
if (isset($return->headers['transfer-encoding'])) {
$return->body = self::decode_chunked($return->body);
unset($return->headers['transfer-encoding']);
}
if (isset($return->headers['content-encoding'])) {
$return->body = self::decompress($return->body);
}
//fsockopen and cURL compatibility
if (isset($return->headers['connection'])) {
unset($return->headers['connection']);
}
$options['hooks']->dispatch('requests.before_redirect_check', array(&$return, $req_headers, $req_data, $options));
if ($return->is_redirect() && $options['follow_redirects'] === true) {
if (isset($return->headers['location']) && $options['redirected'] < $options['redirects']) {
if ($return->status_code === 303) {
$options['type'] = self::GET;
}
$options['redirected']++;
$location = $return->headers['location'];
if (strpos($location, 'http://') !== 0 && strpos($location, 'https://') !== 0) {
// relative redirect, for compatibility make it absolute
$location = Requests_IRI::absolutize($url, $location);
$location = $location->uri;
}
$hook_args = array(
&$location,
&$req_headers,
&$req_data,
&$options,
$return,
);
$options['hooks']->dispatch('requests.before_redirect', $hook_args);
$redirected = self::request($location, $req_headers, $req_data, $options['type'], $options);
$redirected->history[] = $return;
return $redirected;
}
elseif ($options['redirected'] >= $options['redirects']) {
throw new Requests_Exception('Too many redirects', 'toomanyredirects', $return);
}
}
$return->redirects = $options['redirected'];
$options['hooks']->dispatch('requests.after_request', array(&$return, $req_headers, $req_data, $options));
return $return;
}
```
| Uses | Description |
| --- | --- |
| [Requests::decode\_chunked()](decode_chunked) wp-includes/class-requests.php | Decoded a chunked body as per RFC 2616 |
| [Requests::decompress()](decompress) wp-includes/class-requests.php | Decompress an encoded body |
| [Requests::request()](request) wp-includes/class-requests.php | Main interface for HTTP requests |
| [Requests\_Response::\_\_construct()](../requests_response/__construct) wp-includes/Requests/Response.php | Constructor |
| [Requests\_IRI::absolutize()](../requests_iri/absolutize) wp-includes/Requests/IRI.php | Create a new IRI object by resolving a relative IRI |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
| Used By | Description |
| --- | --- |
| [Requests::parse\_multiple()](parse_multiple) wp-includes/class-requests.php | Callback for `transport.internal.parse_response` |
| [Requests::request()](request) wp-includes/class-requests.php | Main interface for HTTP requests |
wordpress Requests::compatible_gzinflate( string $gz_data ): string|bool Requests::compatible\_gzinflate( string $gz\_data ): string|bool
================================================================
Decompression of deflated string while staying compatible with the majority of servers.
Certain Servers will return deflated data with headers which PHP’s gzinflate() function cannot handle out of the box. The following function has been created from various snippets on the gzinflate() PHP documentation.
Warning: Magic numbers within. Due to the potential different formats that the compressed data may be returned in, some "magic offsets" are needed to ensure proper decompression takes place. For a simple progmatic way to determine the magic offset in use, see: <https://core.trac.wordpress.org/ticket/18273>
`$gz_data` string Required String to decompress. string|bool False on failure.
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function compatible_gzinflate($gz_data) {
// Compressed data might contain a full zlib header, if so strip it for
// gzinflate()
if (substr($gz_data, 0, 3) === "\x1f\x8b\x08") {
$i = 10;
$flg = ord(substr($gz_data, 3, 1));
if ($flg > 0) {
if ($flg & 4) {
list($xlen) = unpack('v', substr($gz_data, $i, 2));
$i += 2 + $xlen;
}
if ($flg & 8) {
$i = strpos($gz_data, "\0", $i) + 1;
}
if ($flg & 16) {
$i = strpos($gz_data, "\0", $i) + 1;
}
if ($flg & 2) {
$i += 2;
}
}
$decompressed = self::compatible_gzinflate(substr($gz_data, $i));
if ($decompressed !== false) {
return $decompressed;
}
}
// If the data is Huffman Encoded, we must first strip the leading 2
// byte Huffman marker for gzinflate()
// The response is Huffman coded by many compressors such as
// java.util.zip.Deflater, Ruby’s Zlib::Deflate, and .NET's
// System.IO.Compression.DeflateStream.
//
// See https://decompres.blogspot.com/ for a quick explanation of this
// data type
$huffman_encoded = false;
// low nibble of first byte should be 0x08
list(, $first_nibble) = unpack('h', $gz_data);
// First 2 bytes should be divisible by 0x1F
list(, $first_two_bytes) = unpack('n', $gz_data);
if ($first_nibble === 0x08 && ($first_two_bytes % 0x1F) === 0) {
$huffman_encoded = true;
}
if ($huffman_encoded) {
$decompressed = @gzinflate(substr($gz_data, 2));
if ($decompressed !== false) {
return $decompressed;
}
}
if (substr($gz_data, 0, 4) === "\x50\x4b\x03\x04") {
// ZIP file format header
// Offset 6: 2 bytes, General-purpose field
// Offset 26: 2 bytes, filename length
// Offset 28: 2 bytes, optional field length
// Offset 30: Filename field, followed by optional field, followed
// immediately by data
list(, $general_purpose_flag) = unpack('v', substr($gz_data, 6, 2));
// If the file has been compressed on the fly, 0x08 bit is set of
// the general purpose field. We can use this to differentiate
// between a compressed document, and a ZIP file
$zip_compressed_on_the_fly = ((0x08 & $general_purpose_flag) === 0x08);
if (!$zip_compressed_on_the_fly) {
// Don't attempt to decode a compressed zip file
return $gz_data;
}
// Determine the first byte of data, based on the above ZIP header
// offsets:
$first_file_start = array_sum(unpack('v2', substr($gz_data, 26, 4)));
$decompressed = @gzinflate(substr($gz_data, 30 + $first_file_start));
if ($decompressed !== false) {
return $decompressed;
}
return false;
}
// Finally fall back to straight gzinflate
$decompressed = @gzinflate($gz_data);
if ($decompressed !== false) {
return $decompressed;
}
// Fallback for all above failing, not expected, but included for
// debugging and preventing regressions and to track stats
$decompressed = @gzinflate(substr($gz_data, 2));
if ($decompressed !== false) {
return $decompressed;
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [Requests::compatible\_gzinflate()](compatible_gzinflate) wp-includes/class-requests.php | Decompression of deflated string while staying compatible with the majority of servers. |
| Used By | Description |
| --- | --- |
| [Requests::compatible\_gzinflate()](compatible_gzinflate) wp-includes/class-requests.php | Decompression of deflated string while staying compatible with the majority of servers. |
| [Requests::decompress()](decompress) wp-includes/class-requests.php | Decompress an encoded body |
| Version | Description |
| --- | --- |
| [2.8.1](https://developer.wordpress.org/reference/since/2.8.1/) | Introduced. |
wordpress Requests::add_transport( string $transport ) Requests::add\_transport( string $transport )
=============================================
Register a transport
`$transport` string Required Transport class to add, must support the Requests\_Transport interface File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function add_transport($transport) {
if (empty(self::$transports)) {
self::$transports = array(
'Requests_Transport_cURL',
'Requests_Transport_fsockopen',
);
}
self::$transports = array_merge(self::$transports, array($transport));
}
```
wordpress Requests::match_domain( $host, $reference ) Requests::match\_domain( $host, $reference )
============================================
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function match_domain($host, $reference) {
// Check for a direct match
if ($host === $reference) {
return true;
}
// Calculate the valid wildcard match if the host is not an IP address
// Also validates that the host has 3 parts or more, as per Firefox's
// ruleset.
$parts = explode('.', $host);
if (ip2long($host) === false && count($parts) >= 3) {
$parts[0] = '*';
$wildcard = implode('.', $parts);
if ($wildcard === $reference) {
return true;
}
}
return false;
}
```
wordpress Requests::patch( $url, $headers, $data = array(), $options = array() ) Requests::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/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function patch($url, $headers, $data = array(), $options = array()) {
return self::request($url, $headers, $data, self::PATCH, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests::request()](request) wp-includes/class-requests.php | Main interface for HTTP requests |
wordpress Requests::decompress( string $data ): string Requests::decompress( string $data ): string
============================================
Decompress an encoded body
Implements gzip, compress and deflate. Guesses which it is by attempting to decode.
`$data` string Required Compressed data in one of the above formats string Decompressed string
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function decompress($data) {
if (substr($data, 0, 2) !== "\x1f\x8b" && substr($data, 0, 2) !== "\x78\x9c") {
// Not actually compressed. Probably cURL ruining this for us.
return $data;
}
if (function_exists('gzdecode')) {
// phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.gzdecodeFound -- Wrapped in function_exists() for PHP 5.2.
$decoded = @gzdecode($data);
if ($decoded !== false) {
return $decoded;
}
}
if (function_exists('gzinflate')) {
$decoded = @gzinflate($data);
if ($decoded !== false) {
return $decoded;
}
}
$decoded = self::compatible_gzinflate($data);
if ($decoded !== false) {
return $decoded;
}
if (function_exists('gzuncompress')) {
$decoded = @gzuncompress($data);
if ($decoded !== false) {
return $decoded;
}
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [Requests::compatible\_gzinflate()](compatible_gzinflate) wp-includes/class-requests.php | Decompression of deflated string while staying compatible with the majority of servers. |
| Used By | Description |
| --- | --- |
| [Requests::parse\_response()](parse_response) wp-includes/class-requests.php | HTTP response parser |
wordpress Requests::autoloader( string $class ) Requests::autoloader( string $class )
=====================================
Autoloader for Requests
Register this with [register\_autoloader()](../../functions/register_autoloader) if you’d like to avoid having to create your own.
(You can also use `spl_autoload_register` directly if you’d prefer.)
`$class` string Required Class name to load File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function autoloader($class) {
// Check that the class starts with "Requests"
if (strpos($class, 'Requests') !== 0) {
return;
}
$file = str_replace('_', '/', $class);
if (file_exists(dirname(__FILE__) . '/' . $file . '.php')) {
require_once dirname(__FILE__) . '/' . $file . '.php';
}
}
```
wordpress Requests::get_transport( $capabilities = array() ): Requests_Transport Requests::get\_transport( $capabilities = array() ): Requests\_Transport
========================================================================
Get a working transport
Requests\_Transport
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
protected static function get_transport($capabilities = array()) {
// Caching code, don't bother testing coverage
// @codeCoverageIgnoreStart
// array of capabilities as a string to be used as an array key
ksort($capabilities);
$cap_string = serialize($capabilities);
// Don't search for a transport if it's already been done for these $capabilities
if (isset(self::$transport[$cap_string]) && self::$transport[$cap_string] !== null) {
$class = self::$transport[$cap_string];
return new $class();
}
// @codeCoverageIgnoreEnd
if (empty(self::$transports)) {
self::$transports = array(
'Requests_Transport_cURL',
'Requests_Transport_fsockopen',
);
}
// Find us a working transport
foreach (self::$transports as $class) {
if (!class_exists($class)) {
continue;
}
$result = call_user_func(array($class, 'test'), $capabilities);
if ($result) {
self::$transport[$cap_string] = $class;
break;
}
}
if (self::$transport[$cap_string] === null) {
throw new Requests_Exception('No working transports found', 'notransport', self::$transports);
}
$class = self::$transport[$cap_string];
return new $class();
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
| Used By | Description |
| --- | --- |
| [Requests::request()](request) wp-includes/class-requests.php | Main interface for HTTP requests |
| [Requests::request\_multiple()](request_multiple) wp-includes/class-requests.php | Send multiple HTTP requests simultaneously |
| programming_docs |
wordpress Requests::request_multiple( array $requests, array $options = array() ): array Requests::request\_multiple( array $requests, array $options = array() ): array
===============================================================================
Send multiple HTTP requests simultaneously
The `$requests` parameter takes an associative or indexed array of request fields. The key of each request can be used to match up the request with the returned data, or with the request passed into your `multiple.request.complete` callback.
The request fields value is an associative array with the following keys:
* `url`: Request URL Same as the `$url` parameter to [Requests::request()](request) (string, required)
* `headers`: Associative array of header fields. Same as the `$headers` parameter to [Requests::request()](request) (array, default: `array()`)
* `data`: Associative array of data fields or a string. Same as the `$data` parameter to [Requests::request()](request) (array|string, default: `array()`)
* `type`: HTTP request type (use Requests constants). Same as the `$type` parameter to [Requests::request()](request) (string, default: `Requests::GET`)
* `cookies`: Associative array of cookie name to value, or cookie jar.
(array|[Requests\_Cookie\_Jar](../requests_cookie_jar))
If the `$options` parameter is specified, individual requests will inherit options from it. This can be used to use a single hooking system, or set all the types to `Requests::POST`, for example.
In addition, the `$options` parameter takes the following global options:
* `complete`: A callback for when a request is complete. Takes two parameters, a [Requests\_Response](../requests_response)/Requests\_Exception reference, and the ID from the request array (Note: this can also be overridden on a per-request basis, although that’s a little silly) (callback)
`$requests` array Required Requests data (see description for more information) `$options` array Optional Global and default options (see [Requests::request()](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/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function request_multiple($requests, $options = array()) {
$options = array_merge(self::get_default_options(true), $options);
if (!empty($options['hooks'])) {
$options['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple'));
if (!empty($options['complete'])) {
$options['hooks']->register('multiple.request.complete', $options['complete']);
}
}
foreach ($requests as $id => &$request) {
if (!isset($request['headers'])) {
$request['headers'] = array();
}
if (!isset($request['data'])) {
$request['data'] = array();
}
if (!isset($request['type'])) {
$request['type'] = self::GET;
}
if (!isset($request['options'])) {
$request['options'] = $options;
$request['options']['type'] = $request['type'];
}
else {
if (empty($request['options']['type'])) {
$request['options']['type'] = $request['type'];
}
$request['options'] = array_merge($options, $request['options']);
}
self::set_defaults($request['url'], $request['headers'], $request['data'], $request['type'], $request['options']);
// Ensure we only hook in once
if ($request['options']['hooks'] !== $options['hooks']) {
$request['options']['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple'));
if (!empty($request['options']['complete'])) {
$request['options']['hooks']->register('multiple.request.complete', $request['options']['complete']);
}
}
}
unset($request);
if (!empty($options['transport'])) {
$transport = $options['transport'];
if (is_string($options['transport'])) {
$transport = new $transport();
}
}
else {
$transport = self::get_transport();
}
$responses = $transport->request_multiple($requests, $options);
foreach ($responses as $id => &$response) {
// If our hook got messed with somehow, ensure we end up with the
// correct response
if (is_string($response)) {
$request = $requests[$id];
self::parse_multiple($response, $request);
$request['options']['hooks']->dispatch('multiple.request.complete', array(&$response, $id));
}
}
return $responses;
}
```
| Uses | Description |
| --- | --- |
| [Requests::set\_defaults()](set_defaults) wp-includes/class-requests.php | Set the default values |
| [Requests::parse\_multiple()](parse_multiple) wp-includes/class-requests.php | Callback for `transport.internal.parse_response` |
| [Requests::get\_default\_options()](get_default_options) wp-includes/class-requests.php | Get the default options |
| [Requests::get\_transport()](get_transport) wp-includes/class-requests.php | Get a working transport |
| Used By | Description |
| --- | --- |
| [Requests\_Session::request\_multiple()](../requests_session/request_multiple) wp-includes/Requests/Session.php | Send multiple HTTP requests simultaneously |
wordpress Requests::flatten( array $array ): array Requests::flatten( array $array ): array
========================================
Convert a key => value array to a ‘key: value’ array for headers
`$array` array Required Dictionary of header values array List of headers
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function flatten($array) {
$return = array();
foreach ($array as $key => $value) {
$return[] = sprintf('%s: %s', $key, $value);
}
return $return;
}
```
| Used By | Description |
| --- | --- |
| [Requests::flattern()](flattern) wp-includes/class-requests.php | Convert a key => value array to a ‘key: value’ array for headers |
| [Requests\_Transport\_cURL::setup\_handle()](../requests_transport_curl/setup_handle) wp-includes/Requests/Transport/cURL.php | Setup the cURL handle for the given data |
| [Requests\_Transport\_fsockopen::request()](../requests_transport_fsockopen/request) wp-includes/Requests/Transport/fsockopen.php | Perform a request |
wordpress Requests::set_certificate_path( string $path ) Requests::set\_certificate\_path( string $path )
================================================
Set default certificate path.
`$path` string Required Certificate path, pointing to a PEM file. File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function set_certificate_path($path) {
self::$certificate_path = $path;
}
```
wordpress Requests::get_default_options( boolean $multirequest = false ): array Requests::get\_default\_options( boolean $multirequest = false ): array
=======================================================================
Get the default options
* [Requests::request()](../requests/request): for values returned by this method
`$multirequest` boolean Optional Is this a multirequest? Default: `false`
array Default option values
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
protected static function get_default_options($multirequest = false) {
$defaults = array(
'timeout' => 10,
'connect_timeout' => 10,
'useragent' => 'php-requests/' . self::VERSION,
'protocol_version' => 1.1,
'redirected' => 0,
'redirects' => 10,
'follow_redirects' => true,
'blocking' => true,
'type' => self::GET,
'filename' => false,
'auth' => false,
'proxy' => false,
'cookies' => false,
'max_bytes' => false,
'idn' => true,
'hooks' => null,
'transport' => null,
'verify' => self::get_certificate_path(),
'verifyname' => true,
);
if ($multirequest !== false) {
$defaults['complete'] = null;
}
return $defaults;
}
```
| Uses | Description |
| --- | --- |
| [Requests::get\_certificate\_path()](get_certificate_path) wp-includes/class-requests.php | Get default certificate path. |
| Used By | Description |
| --- | --- |
| [Requests::request()](request) wp-includes/class-requests.php | Main interface for HTTP requests |
| [Requests::request\_multiple()](request_multiple) wp-includes/class-requests.php | Send multiple HTTP requests simultaneously |
wordpress Requests::parse_multiple( string $response, array $request ): null Requests::parse\_multiple( string $response, array $request ): null
===================================================================
Callback for `transport.internal.parse_response`
Internal use only. Converts a raw HTTP response to a [Requests\_Response](../requests_response) while still executing a multiple request.
`$response` string Required Full response text including headers and body (will be overwritten with Response instance) `$request` array Required Request data as passed into [Requests::request\_multiple()](../requests/request_multiple) null `$response` is either set to a [Requests\_Response](../requests_response) instance, or a [Requests\_Exception](../requests_exception) object
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function parse_multiple(&$response, $request) {
try {
$url = $request['url'];
$headers = $request['headers'];
$data = $request['data'];
$options = $request['options'];
$response = self::parse_response($response, $url, $headers, $data, $options);
}
catch (Requests_Exception $e) {
$response = $e;
}
}
```
| Uses | Description |
| --- | --- |
| [Requests::parse\_response()](parse_response) wp-includes/class-requests.php | HTTP response parser |
| Used By | Description |
| --- | --- |
| [Requests::request\_multiple()](request_multiple) wp-includes/class-requests.php | Send multiple HTTP requests simultaneously |
wordpress Requests::register_autoloader() Requests::register\_autoloader()
================================
Register the built-in autoloader
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function register_autoloader() {
spl_autoload_register(array('Requests', 'autoloader'));
}
```
wordpress Requests::flattern( array $array ): array Requests::flattern( array $array ): array
=========================================
This method has been deprecated. Misspelling of [Requests::flatten()](flatten) instead.
Convert a key => value array to a ‘key: value’ array for headers
`$array` array Required Dictionary of header values array List of headers
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function flattern($array) {
return self::flatten($array);
}
```
| Uses | Description |
| --- | --- |
| [Requests::flatten()](flatten) wp-includes/class-requests.php | Convert a key => value array to a ‘key: value’ array for headers |
wordpress Requests::head( $url, $headers = array(), $options = array() ) Requests::head( $url, $headers = array(), $options = array() )
==============================================================
Send a HEAD request
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function head($url, $headers = array(), $options = array()) {
return self::request($url, $headers, null, self::HEAD, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests::request()](request) wp-includes/class-requests.php | Main interface for HTTP requests |
wordpress Requests::options( $url, $headers = array(), $data = array(), $options = array() ) Requests::options( $url, $headers = array(), $data = array(), $options = array() )
==================================================================================
Send an OPTIONS request
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function options($url, $headers = array(), $data = array(), $options = array()) {
return self::request($url, $headers, $data, self::OPTIONS, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests::request()](request) wp-includes/class-requests.php | Main interface for HTTP requests |
wordpress Requests::put( $url, $headers = array(), $data = array(), $options = array() ) Requests::put( $url, $headers = array(), $data = array(), $options = array() )
==============================================================================
Send a PUT request
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function put($url, $headers = array(), $data = array(), $options = array()) {
return self::request($url, $headers, $data, self::PUT, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests::request()](request) wp-includes/class-requests.php | Main interface for HTTP requests |
wordpress Requests::__construct() Requests::\_\_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.
This is a static class, do not instantiate it
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
private function __construct() {}
```
wordpress Requests::set_defaults( string $url, array $headers, array|null $data, string $type, array $options ): array Requests::set\_defaults( string $url, array $headers, array|null $data, string $type, array $options ): array
=============================================================================================================
Set the default values
`$url` string Required URL to request `$headers` array Required Extra headers to send with the request `$data` array|null Required Data to send either as a query string for GET/HEAD requests, or in the body for POST requests `$type` string Required HTTP request type `$options` array Required Options for the request array $options
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
protected static function set_defaults(&$url, &$headers, &$data, &$type, &$options) {
if (!preg_match('/^http(s)?:\/\//i', $url, $matches)) {
throw new Requests_Exception('Only HTTP(S) requests are handled.', 'nonhttp', $url);
}
if (empty($options['hooks'])) {
$options['hooks'] = new Requests_Hooks();
}
if (is_array($options['auth'])) {
$options['auth'] = new Requests_Auth_Basic($options['auth']);
}
if ($options['auth'] !== false) {
$options['auth']->register($options['hooks']);
}
if (is_string($options['proxy']) || is_array($options['proxy'])) {
$options['proxy'] = new Requests_Proxy_HTTP($options['proxy']);
}
if ($options['proxy'] !== false) {
$options['proxy']->register($options['hooks']);
}
if (is_array($options['cookies'])) {
$options['cookies'] = new Requests_Cookie_Jar($options['cookies']);
}
elseif (empty($options['cookies'])) {
$options['cookies'] = new Requests_Cookie_Jar();
}
if ($options['cookies'] !== false) {
$options['cookies']->register($options['hooks']);
}
if ($options['idn'] !== false) {
$iri = new Requests_IRI($url);
$iri->host = Requests_IDNAEncoder::encode($iri->ihost);
$url = $iri->uri;
}
// Massage the type to ensure we support it.
$type = strtoupper($type);
if (!isset($options['data_format'])) {
if (in_array($type, array(self::HEAD, self::GET, self::DELETE), true)) {
$options['data_format'] = 'query';
}
else {
$options['data_format'] = 'body';
}
}
}
```
| Uses | Description |
| --- | --- |
| [Requests\_IRI::\_\_construct()](../requests_iri/__construct) wp-includes/Requests/IRI.php | Create a new IRI object, from a specified string |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
| [Requests\_Proxy\_HTTP::\_\_construct()](../requests_proxy_http/__construct) wp-includes/Requests/Proxy/HTTP.php | Constructor |
| [Requests\_Auth\_Basic::\_\_construct()](../requests_auth_basic/__construct) wp-includes/Requests/Auth/Basic.php | Constructor |
| [Requests\_Hooks::\_\_construct()](../requests_hooks/__construct) wp-includes/Requests/Hooks.php | Constructor |
| [Requests\_Cookie\_Jar::\_\_construct()](../requests_cookie_jar/__construct) wp-includes/Requests/Cookie/Jar.php | Create a new jar |
| [Requests\_IDNAEncoder::encode()](../requests_idnaencoder/encode) wp-includes/Requests/IDNAEncoder.php | Encode a hostname using Punycode |
| Used By | Description |
| --- | --- |
| [Requests::request()](request) wp-includes/class-requests.php | Main interface for HTTP requests |
| [Requests::request\_multiple()](request_multiple) wp-includes/class-requests.php | Send multiple HTTP requests simultaneously |
wordpress Requests::decode_chunked( string $data ): string Requests::decode\_chunked( string $data ): string
=================================================
Decoded a chunked body as per RFC 2616
* <https://tools.ietf.org/html/rfc2616#section-3.6.1>
`$data` string Required Chunked body string Decoded body
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
protected static function decode_chunked($data) {
if (!preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', trim($data))) {
return $data;
}
$decoded = '';
$encoded = $data;
while (true) {
$is_chunked = (bool) preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', $encoded, $matches);
if (!$is_chunked) {
// Looks like it's not chunked after all
return $data;
}
$length = hexdec(trim($matches[1]));
if ($length === 0) {
// Ignore trailer headers
return $decoded;
}
$chunk_length = strlen($matches[0]);
$decoded .= substr($encoded, $chunk_length, $length);
$encoded = substr($encoded, $chunk_length + $length + 2);
if (trim($encoded) === '0' || empty($encoded)) {
return $decoded;
}
}
// We'll never actually get down here
// @codeCoverageIgnoreStart
}
```
| Used By | Description |
| --- | --- |
| [Requests::parse\_response()](parse_response) wp-includes/class-requests.php | HTTP response parser |
wordpress Requests::delete( $url, $headers = array(), $options = array() ) Requests::delete( $url, $headers = array(), $options = array() )
================================================================
Send a DELETE request
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function delete($url, $headers = array(), $options = array()) {
return self::request($url, $headers, null, self::DELETE, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests::request()](request) wp-includes/class-requests.php | Main interface for HTTP requests |
| programming_docs |
wordpress Requests::get( $url, $headers = array(), $options = array() ) Requests::get( $url, $headers = array(), $options = array() )
=============================================================
Send a GET request
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function get($url, $headers = array(), $options = array()) {
return self::request($url, $headers, null, self::GET, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests::request()](request) wp-includes/class-requests.php | Main interface for HTTP requests |
wordpress Requests::get_certificate_path(): string Requests::get\_certificate\_path(): string
==========================================
Get default certificate path.
string Default certificate path.
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function get_certificate_path() {
if (!empty(self::$certificate_path)) {
return self::$certificate_path;
}
return dirname(__FILE__) . '/Requests/Transport/cacert.pem';
}
```
| Used By | Description |
| --- | --- |
| [Requests::get\_default\_options()](get_default_options) wp-includes/class-requests.php | Get the default options |
wordpress Requests::trace( $url, $headers = array(), $options = array() ) Requests::trace( $url, $headers = array(), $options = array() )
===============================================================
Send a TRACE request
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function trace($url, $headers = array(), $options = array()) {
return self::request($url, $headers, null, self::TRACE, $options);
}
```
| Uses | Description |
| --- | --- |
| [Requests::request()](request) wp-includes/class-requests.php | Main interface for HTTP requests |
wordpress Requests::request( string $url, array $headers = array(), array|null $data = array(), string $type = self::GET, array $options = array() ): Requests_Response Requests::request( string $url, array $headers = array(), array|null $data = array(), string $type = self::GET, array $options = array() ): Requests\_Response
==============================================================================================================================================================
Main interface for HTTP requests
This method initiates a request and sends it via a transport before parsing.
The `$options` parameter takes an associative array with the following options:
* `timeout`: How long should we wait for a response? Note: for cURL, a minimum of 1 second applies, as DNS resolution operates at second-resolution only.
(float, seconds with a millisecond precision, default: 10, example: 0.01)
* `connect_timeout`: How long should we wait while trying to connect? (float, seconds with a millisecond precision, default: 10, example: 0.01)
* `useragent`: Useragent to send to the server (string, default: php-requests/$version)
* `follow_redirects`: Should we follow 3xx redirects? (boolean, default: true)
* `redirects`: How many times should we redirect before erroring? (integer, default: 10)
* `blocking`: Should we block processing on this request? (boolean, default: true)
* `filename`: File to stream the body to instead.
(string|boolean, default: false)
* `auth`: Authentication handler or array of user/password details to use for Basic authentication (Requests\_Auth|array|boolean, default: false)
* `proxy`: Proxy details to use for proxy by-passing and authentication (Requests\_Proxy|array|string|boolean, default: false)
* `max_bytes`: Limit for the response body size.
(integer|boolean, default: false)
* `idn`: Enable IDN parsing (boolean, default: true)
* `transport`: Custom transport. Either a class name, or a transport object. Defaults to the first working transport from [getTransport()](../../functions/gettransport) (string|Requests\_Transport, default: [getTransport()](../../functions/gettransport))
* `hooks`: Hooks handler.
(Requests\_Hooker, default: new [Requests\_Hooks](../requests_hooks)())
* `verify`: Should we verify SSL certificates? Allows passing in a custom certificate file as a string. (Using true uses the system-wide root certificate store instead, but this may have different behaviour across transports.) (string|boolean, default: library/Requests/Transport/cacert.pem)
* `verifyname`: Should we verify the common name in the SSL certificate? (boolean, default: true)
* `data_format`: How should we send the `$data` parameter? (string, one of ‘query’ or ‘body’, default: ‘query’ for HEAD/GET/DELETE, ‘body’ for POST/PUT/OPTIONS/PATCH)
`$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: `self::GET`
`$options` array Optional Options for the request (see description for more information) Default: `array()`
[Requests\_Response](../requests_response)
File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/)
```
public static function request($url, $headers = array(), $data = array(), $type = self::GET, $options = array()) {
if (empty($options['type'])) {
$options['type'] = $type;
}
$options = array_merge(self::get_default_options(), $options);
self::set_defaults($url, $headers, $data, $type, $options);
$options['hooks']->dispatch('requests.before_request', array(&$url, &$headers, &$data, &$type, &$options));
if (!empty($options['transport'])) {
$transport = $options['transport'];
if (is_string($options['transport'])) {
$transport = new $transport();
}
}
else {
$need_ssl = (stripos($url, 'https://') === 0);
$capabilities = array('ssl' => $need_ssl);
$transport = self::get_transport($capabilities);
}
$response = $transport->request($url, $headers, $data, $options);
$options['hooks']->dispatch('requests.before_parse', array(&$response, $url, $headers, $data, $type, $options));
return self::parse_response($response, $url, $headers, $data, $options);
}
```
| Uses | Description |
| --- | --- |
| [stripos()](../../functions/stripos) wp-includes/class-pop3.php | |
| [Requests::set\_defaults()](set_defaults) wp-includes/class-requests.php | Set the default values |
| [Requests::parse\_response()](parse_response) wp-includes/class-requests.php | HTTP response parser |
| [Requests::get\_default\_options()](get_default_options) wp-includes/class-requests.php | Get the default options |
| [Requests::get\_transport()](get_transport) wp-includes/class-requests.php | Get a working transport |
| Used By | Description |
| --- | --- |
| [Requests::parse\_response()](parse_response) wp-includes/class-requests.php | HTTP response parser |
| [Requests::options()](options) wp-includes/class-requests.php | Send an OPTIONS request |
| [Requests::patch()](patch) wp-includes/class-requests.php | Send a PATCH request |
| [Requests::get()](get) wp-includes/class-requests.php | Send a GET request |
| [Requests::head()](head) wp-includes/class-requests.php | Send a HEAD request |
| [Requests::delete()](delete) wp-includes/class-requests.php | Send a DELETE request |
| [Requests::trace()](trace) wp-includes/class-requests.php | Send a TRACE request |
| [Requests::post()](post) wp-includes/class-requests.php | Send a POST request |
| [Requests::put()](put) wp-includes/class-requests.php | Send a PUT request |
| [Requests\_Session::request()](../requests_session/request) wp-includes/Requests/Session.php | Main interface for HTTP requests |
| [WP\_Http::request()](../wp_http/request) wp-includes/class-wp-http.php | Send an HTTP request to a URI. |
wordpress WP_Sitemaps::init() WP\_Sitemaps::init()
====================
Initiates all sitemap functionality.
If sitemaps are disabled, only the rewrite rules will be registered by this method, in order to properly send 404s.
File: `wp-includes/sitemaps/class-wp-sitemaps.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps.php/)
```
public function init() {
// These will all fire on the init hook.
$this->register_rewrites();
add_action( 'template_redirect', array( $this, 'render_sitemaps' ) );
if ( ! $this->sitemaps_enabled() ) {
return;
}
$this->register_sitemaps();
// Add additional action callbacks.
add_filter( 'pre_handle_404', array( $this, 'redirect_sitemapxml' ), 10, 2 );
add_filter( 'robots_txt', array( $this, 'add_robots' ), 0, 2 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Sitemaps::register\_rewrites()](register_rewrites) wp-includes/sitemaps/class-wp-sitemaps.php | Registers sitemap rewrite tags and routing rules. |
| [WP\_Sitemaps::sitemaps\_enabled()](sitemaps_enabled) wp-includes/sitemaps/class-wp-sitemaps.php | Determines whether sitemaps are enabled or not. |
| [WP\_Sitemaps::register\_sitemaps()](register_sitemaps) wp-includes/sitemaps/class-wp-sitemaps.php | Registers and sets up the functionality for all supported sitemaps. |
| [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\_sitemaps\_get\_server()](../../functions/wp_sitemaps_get_server) wp-includes/sitemaps.php | Retrieves the current Sitemaps server instance. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps::add_robots( string $output, bool $public ): string WP\_Sitemaps::add\_robots( string $output, bool $public ): string
=================================================================
Adds the sitemap index to robots.txt.
`$output` string Required robots.txt output. `$public` bool Required Whether the site is public. string The robots.txt output.
File: `wp-includes/sitemaps/class-wp-sitemaps.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps.php/)
```
public function add_robots( $output, $public ) {
if ( $public ) {
$output .= "\nSitemap: " . esc_url( $this->index->get_index_url() ) . "\n";
}
return $output;
}
```
| Uses | Description |
| --- | --- |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps::sitemaps_enabled(): bool WP\_Sitemaps::sitemaps\_enabled(): bool
=======================================
Determines whether sitemaps are enabled or not.
bool Whether sitemaps are enabled.
File: `wp-includes/sitemaps/class-wp-sitemaps.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps.php/)
```
public function sitemaps_enabled() {
$is_enabled = (bool) get_option( 'blog_public' );
/**
* Filters whether XML Sitemaps are enabled or not.
*
* When XML Sitemaps are disabled via this filter, rewrite rules are still
* in place to ensure a 404 is returned.
*
* @see WP_Sitemaps::register_rewrites()
*
* @since 5.5.0
*
* @param bool $is_enabled Whether XML Sitemaps are enabled or not. Defaults
* to true for public sites.
*/
return (bool) apply_filters( 'wp_sitemaps_enabled', $is_enabled );
}
```
[apply\_filters( 'wp\_sitemaps\_enabled', bool $is\_enabled )](../../hooks/wp_sitemaps_enabled)
Filters whether XML Sitemaps are enabled or not.
| 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\_Sitemaps::render\_sitemaps()](render_sitemaps) wp-includes/sitemaps/class-wp-sitemaps.php | Renders sitemap templates based on rewrite rules. |
| [WP\_Sitemaps::init()](init) wp-includes/sitemaps/class-wp-sitemaps.php | Initiates all sitemap functionality. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps::register_rewrites() WP\_Sitemaps::register\_rewrites()
==================================
Registers sitemap rewrite tags and routing rules.
File: `wp-includes/sitemaps/class-wp-sitemaps.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps.php/)
```
public function register_rewrites() {
// Add rewrite tags.
add_rewrite_tag( '%sitemap%', '([^?]+)' );
add_rewrite_tag( '%sitemap-subtype%', '([^?]+)' );
// Register index route.
add_rewrite_rule( '^wp-sitemap\.xml$', 'index.php?sitemap=index', 'top' );
// Register rewrites for the XSL stylesheet.
add_rewrite_tag( '%sitemap-stylesheet%', '([^?]+)' );
add_rewrite_rule( '^wp-sitemap\.xsl$', 'index.php?sitemap-stylesheet=sitemap', 'top' );
add_rewrite_rule( '^wp-sitemap-index\.xsl$', 'index.php?sitemap-stylesheet=index', 'top' );
// Register routes for providers.
add_rewrite_rule(
'^wp-sitemap-([a-z]+?)-([a-z\d_-]+?)-(\d+?)\.xml$',
'index.php?sitemap=$matches[1]&sitemap-subtype=$matches[2]&paged=$matches[3]',
'top'
);
add_rewrite_rule(
'^wp-sitemap-([a-z]+?)-(\d+?)\.xml$',
'index.php?sitemap=$matches[1]&paged=$matches[2]',
'top'
);
}
```
| Uses | Description |
| --- | --- |
| [add\_rewrite\_tag()](../../functions/add_rewrite_tag) wp-includes/rewrite.php | Adds a new rewrite tag (like %postname%). |
| [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. |
| Used By | Description |
| --- | --- |
| [WP\_Sitemaps::init()](init) wp-includes/sitemaps/class-wp-sitemaps.php | Initiates all sitemap functionality. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps::render_sitemaps() WP\_Sitemaps::render\_sitemaps()
================================
Renders sitemap templates based on rewrite rules.
File: `wp-includes/sitemaps/class-wp-sitemaps.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps.php/)
```
public function render_sitemaps() {
global $wp_query;
$sitemap = sanitize_text_field( get_query_var( 'sitemap' ) );
$object_subtype = sanitize_text_field( get_query_var( 'sitemap-subtype' ) );
$stylesheet_type = sanitize_text_field( get_query_var( 'sitemap-stylesheet' ) );
$paged = absint( get_query_var( 'paged' ) );
// Bail early if this isn't a sitemap or stylesheet route.
if ( ! ( $sitemap || $stylesheet_type ) ) {
return;
}
if ( ! $this->sitemaps_enabled() ) {
$wp_query->set_404();
status_header( 404 );
return;
}
// Render stylesheet if this is stylesheet route.
if ( $stylesheet_type ) {
$stylesheet = new WP_Sitemaps_Stylesheet();
$stylesheet->render_stylesheet( $stylesheet_type );
exit;
}
// Render the index.
if ( 'index' === $sitemap ) {
$sitemap_list = $this->index->get_sitemap_list();
$this->renderer->render_index( $sitemap_list );
exit;
}
$provider = $this->registry->get_provider( $sitemap );
if ( ! $provider ) {
return;
}
if ( empty( $paged ) ) {
$paged = 1;
}
$url_list = $provider->get_url_list( $paged, $object_subtype );
// Force a 404 and bail early if no URLs are present.
if ( empty( $url_list ) ) {
$wp_query->set_404();
status_header( 404 );
return;
}
$this->renderer->render_sitemap( $url_list );
exit;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Sitemaps::sitemaps\_enabled()](sitemaps_enabled) wp-includes/sitemaps/class-wp-sitemaps.php | Determines whether sitemaps are enabled or not. |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [WP\_Query::set\_404()](../wp_query/set_404) wp-includes/class-wp-query.php | Sets the 404 property and saves whether query is feed. |
| [get\_query\_var()](../../functions/get_query_var) wp-includes/query.php | Retrieves the value of a query variable in the [WP\_Query](../wp_query) class. |
| [status\_header()](../../functions/status_header) wp-includes/functions.php | Sets HTTP status header. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps::register_sitemaps() WP\_Sitemaps::register\_sitemaps()
==================================
Registers and sets up the functionality for all supported sitemaps.
File: `wp-includes/sitemaps/class-wp-sitemaps.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps.php/)
```
public function register_sitemaps() {
$providers = array(
'posts' => new WP_Sitemaps_Posts(),
'taxonomies' => new WP_Sitemaps_Taxonomies(),
'users' => new WP_Sitemaps_Users(),
);
/* @var WP_Sitemaps_Provider $provider */
foreach ( $providers as $name => $provider ) {
$this->registry->add_provider( $name, $provider );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Sitemaps\_Users::\_\_construct()](../wp_sitemaps_users/__construct) wp-includes/sitemaps/providers/class-wp-sitemaps-users.php | [WP\_Sitemaps\_Users](../wp_sitemaps_users) constructor. |
| [WP\_Sitemaps\_Taxonomies::\_\_construct()](../wp_sitemaps_taxonomies/__construct) wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php | [WP\_Sitemaps\_Taxonomies](../wp_sitemaps_taxonomies) constructor. |
| [WP\_Sitemaps\_Posts::\_\_construct()](../wp_sitemaps_posts/__construct) wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php | [WP\_Sitemaps\_Posts](../wp_sitemaps_posts) constructor. |
| Used By | Description |
| --- | --- |
| [WP\_Sitemaps::init()](init) wp-includes/sitemaps/class-wp-sitemaps.php | Initiates all sitemap functionality. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps::__construct() WP\_Sitemaps::\_\_construct()
=============================
[WP\_Sitemaps](../wp_sitemaps) constructor.
File: `wp-includes/sitemaps/class-wp-sitemaps.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps.php/)
```
public function __construct() {
$this->registry = new WP_Sitemaps_Registry();
$this->renderer = new WP_Sitemaps_Renderer();
$this->index = new WP_Sitemaps_Index( $this->registry );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Sitemaps\_Index::\_\_construct()](../wp_sitemaps_index/__construct) wp-includes/sitemaps/class-wp-sitemaps-index.php | [WP\_Sitemaps\_Index](../wp_sitemaps_index) constructor. |
| [WP\_Sitemaps\_Renderer::\_\_construct()](../wp_sitemaps_renderer/__construct) wp-includes/sitemaps/class-wp-sitemaps-renderer.php | [WP\_Sitemaps\_Renderer](../wp_sitemaps_renderer) constructor. |
| Used By | Description |
| --- | --- |
| [wp\_sitemaps\_get\_server()](../../functions/wp_sitemaps_get_server) wp-includes/sitemaps.php | Retrieves the current Sitemaps server instance. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
| programming_docs |
wordpress WP_Sitemaps::redirect_sitemapxml( bool $bypass, WP_Query $query ): bool WP\_Sitemaps::redirect\_sitemapxml( bool $bypass, WP\_Query $query ): bool
==========================================================================
Redirects a URL to the wp-sitemap.xml
`$bypass` bool Required Pass-through of the pre\_handle\_404 filter value. `$query` [WP\_Query](../wp_query) Required The [WP\_Query](../wp_query) object. bool Bypass value.
File: `wp-includes/sitemaps/class-wp-sitemaps.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps.php/)
```
public function redirect_sitemapxml( $bypass, $query ) {
// If a plugin has already utilized the pre_handle_404 function, return without action to avoid conflicts.
if ( $bypass ) {
return $bypass;
}
// 'pagename' is for most permalink types, name is for when the %postname% is used as a top-level field.
if ( 'sitemap-xml' === $query->get( 'pagename' )
|| 'sitemap-xml' === $query->get( 'name' )
) {
wp_safe_redirect( $this->index->get_index_url() );
exit();
}
return $bypass;
}
```
| Uses | Description |
| --- | --- |
| [wp\_safe\_redirect()](../../functions/wp_safe_redirect) wp-includes/pluggable.php | Performs a safe (local) redirect, using [wp\_redirect()](../../functions/wp_redirect) . |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_MS_Users_List_Table::prepare_items() WP\_MS\_Users\_List\_Table::prepare\_items()
============================================
File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
public function prepare_items() {
global $mode, $usersearch, $role;
if ( ! empty( $_REQUEST['mode'] ) ) {
$mode = 'excerpt' === $_REQUEST['mode'] ? 'excerpt' : 'list';
set_user_setting( 'network_users_list_mode', $mode );
} else {
$mode = get_user_setting( 'network_users_list_mode', 'list' );
}
$usersearch = isset( $_REQUEST['s'] ) ? wp_unslash( trim( $_REQUEST['s'] ) ) : '';
$users_per_page = $this->get_items_per_page( 'users_network_per_page' );
$role = isset( $_REQUEST['role'] ) ? $_REQUEST['role'] : '';
$paged = $this->get_pagenum();
$args = array(
'number' => $users_per_page,
'offset' => ( $paged - 1 ) * $users_per_page,
'search' => $usersearch,
'blog_id' => 0,
'fields' => 'all_with_meta',
);
if ( wp_is_large_network( 'users' ) ) {
$args['search'] = ltrim( $args['search'], '*' );
} elseif ( '' !== $args['search'] ) {
$args['search'] = trim( $args['search'], '*' );
$args['search'] = '*' . $args['search'] . '*';
}
if ( 'super' === $role ) {
$args['login__in'] = get_super_admins();
}
/*
* If the network is large and a search is not being performed,
* show only the latest users with no paging in order to avoid
* expensive count queries.
*/
if ( ! $usersearch && wp_is_large_network( 'users' ) ) {
if ( ! isset( $_REQUEST['orderby'] ) ) {
$_GET['orderby'] = 'id';
$_REQUEST['orderby'] = 'id';
}
if ( ! isset( $_REQUEST['order'] ) ) {
$_GET['order'] = 'DESC';
$_REQUEST['order'] = 'DESC';
}
$args['count_total'] = false;
}
if ( isset( $_REQUEST['orderby'] ) ) {
$args['orderby'] = $_REQUEST['orderby'];
}
if ( isset( $_REQUEST['order'] ) ) {
$args['order'] = $_REQUEST['order'];
}
/** This filter is documented in wp-admin/includes/class-wp-users-list-table.php */
$args = apply_filters( 'users_list_table_query_args', $args );
// Query the user IDs for this page.
$wp_user_search = new WP_User_Query( $args );
$this->items = $wp_user_search->get_results();
$this->set_pagination_args(
array(
'total_items' => $wp_user_search->get_total(),
'per_page' => $users_per_page,
)
);
}
```
[apply\_filters( 'users\_list\_table\_query\_args', array $args )](../../hooks/users_list_table_query_args)
Filters the query arguments used to retrieve users for the current users list table.
| Uses | Description |
| --- | --- |
| [WP\_User\_Search::get\_results()](../wp_user_search/get_results) wp-admin/includes/deprecated.php | Retrieves the user search query results. |
| [get\_super\_admins()](../../functions/get_super_admins) wp-includes/capabilities.php | Retrieves a list of super admins. |
| [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\_User\_Query::\_\_construct()](../wp_user_query/__construct) wp-includes/class-wp-user-query.php | PHP5 constructor. |
| [wp\_is\_large\_network()](../../functions/wp_is_large_network) wp-includes/ms-functions.php | Determines whether or not we have a large network. |
| [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. |
wordpress WP_MS_Users_List_Table::ajax_user_can(): bool WP\_MS\_Users\_List\_Table::ajax\_user\_can(): bool
===================================================
bool
File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
public function ajax_user_can() {
return current_user_can( 'manage_network_users' );
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
wordpress WP_MS_Users_List_Table::display_rows() WP\_MS\_Users\_List\_Table::display\_rows()
===========================================
File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
public function display_rows() {
foreach ( $this->items as $user ) {
$class = '';
$status_list = array(
'spam' => 'site-spammed',
'deleted' => 'site-deleted',
);
foreach ( $status_list as $status => $col ) {
if ( $user->$status ) {
$class .= " $col";
}
}
?>
<tr class="<?php echo trim( $class ); ?>">
<?php $this->single_row_columns( $user ); ?>
</tr>
<?php
}
}
```
wordpress WP_MS_Users_List_Table::column_id( WP_User $user ) WP\_MS\_Users\_List\_Table::column\_id( WP\_User $user )
========================================================
Handles the ID column output.
`$user` [WP\_User](../wp_user) Required The current [WP\_User](../wp_user) object. File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
public function column_id( $user ) {
echo $user->ID;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_MS_Users_List_Table::no_items() WP\_MS\_Users\_List\_Table::no\_items()
=======================================
File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
public function no_items() {
_e( 'No users found.' );
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
wordpress WP_MS_Users_List_Table::pagination( string $which ) WP\_MS\_Users\_List\_Table::pagination( string $which )
=======================================================
`$which` string Required File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
protected function pagination( $which ) {
global $mode;
parent::pagination( $which );
if ( 'top' === $which ) {
$this->view_switcher( $mode );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::pagination()](../wp_list_table/pagination) wp-admin/includes/class-wp-list-table.php | Displays the pagination. |
wordpress WP_MS_Users_List_Table::get_default_primary_column_name(): string WP\_MS\_Users\_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, `'username'`.
File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
protected function get_default_primary_column_name() {
return 'username';
}
```
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_MS_Users_List_Table::handle_row_actions( WP_User $item, string $column_name, string $primary ): string WP\_MS\_Users\_List\_Table::handle\_row\_actions( WP\_User $item, string $column\_name, string $primary ): string
=================================================================================================================
Generates and displays row action links.
`$item` [WP\_User](../wp_user) Required User being acted upon. `$column_name` string Required Current column name. `$primary` string Required Primary column name. string Row actions output for users in Multisite, or an empty string if the current column is not the primary column.
File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-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.
$user = $item;
$super_admins = get_super_admins();
$actions = array();
if ( current_user_can( 'edit_user', $user->ID ) ) {
$edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user->ID ) ) );
$actions['edit'] = '<a href="' . $edit_link . '">' . __( 'Edit' ) . '</a>';
}
if ( current_user_can( 'delete_user', $user->ID ) && ! in_array( $user->user_login, $super_admins, true ) ) {
$actions['delete'] = '<a href="' . esc_url( network_admin_url( add_query_arg( '_wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), wp_nonce_url( 'users.php', 'deleteuser' ) . '&action=deleteuser&id=' . $user->ID ) ) ) . '" class="delete">' . __( 'Delete' ) . '</a>';
}
/**
* Filters the action links displayed under each user in the Network Admin Users list table.
*
* @since 3.2.0
*
* @param string[] $actions An array of action links to be displayed. Default 'Edit', 'Delete'.
* @param WP_User $user WP_User object.
*/
$actions = apply_filters( 'ms_user_row_actions', $actions, $user );
return $this->row_actions( $actions );
}
```
[apply\_filters( 'ms\_user\_row\_actions', string[] $actions, WP\_User $user )](../../hooks/ms_user_row_actions)
Filters the action links displayed under each user in the Network Admin Users list table.
| Uses | Description |
| --- | --- |
| [get\_super\_admins()](../../functions/get_super_admins) wp-includes/capabilities.php | Retrieves a list of super admins. |
| [network\_admin\_url()](../../functions/network_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the network. |
| [get\_edit\_user\_link()](../../functions/get_edit_user_link) wp-includes/link-template.php | Retrieves the edit user link. |
| [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\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [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. |
| [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\_MS\_Users\_List\_Table::\_column\_blogs()](_column_blogs) wp-admin/includes/class-wp-ms-users-list-table.php | |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$user` 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_MS_Users_List_Table::column_username( WP_User $user ) WP\_MS\_Users\_List\_Table::column\_username( WP\_User $user )
==============================================================
Handles the username column output.
`$user` [WP\_User](../wp_user) Required The current [WP\_User](../wp_user) object. File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
public function column_username( $user ) {
$super_admins = get_super_admins();
$avatar = get_avatar( $user->user_email, 32 );
echo $avatar;
if ( current_user_can( 'edit_user', $user->ID ) ) {
$edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user->ID ) ) );
$edit = "<a href=\"{$edit_link}\">{$user->user_login}</a>";
} else {
$edit = $user->user_login;
}
?>
<strong>
<?php
echo $edit;
if ( in_array( $user->user_login, $super_admins, true ) ) {
echo ' — ' . __( 'Super Admin' );
}
?>
</strong>
<?php
}
```
| Uses | Description |
| --- | --- |
| [get\_super\_admins()](../../functions/get_super_admins) wp-includes/capabilities.php | Retrieves a list of super admins. |
| [get\_avatar()](../../functions/get_avatar) wp-includes/pluggable.php | Retrieves the avatar `<img>` tag for a user, email address, MD5 hash, comment, or post. |
| [get\_edit\_user\_link()](../../functions/get_edit_user_link) wp-includes/link-template.php | Retrieves the edit user link. |
| [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\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [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_MS_Users_List_Table::get_views(): array WP\_MS\_Users\_List\_Table::get\_views(): array
===============================================
array
File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
protected function get_views() {
global $role;
$total_users = get_user_count();
$super_admins = get_super_admins();
$total_admins = count( $super_admins );
$role_links = array();
$role_links['all'] = array(
'url' => network_admin_url( 'users.php' ),
'label' => sprintf(
/* translators: Number of users. */
_nx(
'All <span class="count">(%s)</span>',
'All <span class="count">(%s)</span>',
$total_users,
'users'
),
number_format_i18n( $total_users )
),
'current' => 'super' !== $role,
);
$role_links['super'] = array(
'url' => network_admin_url( 'users.php?role=super' ),
'label' => sprintf(
/* translators: Number of users. */
_n(
'Super Admin <span class="count">(%s)</span>',
'Super Admins <span class="count">(%s)</span>',
$total_admins
),
number_format_i18n( $total_admins )
),
'current' => 'super' === $role,
);
return $this->get_views_links( $role_links );
}
```
| Uses | Description |
| --- | --- |
| [get\_super\_admins()](../../functions/get_super_admins) wp-includes/capabilities.php | Retrieves a list of super admins. |
| [\_nx()](../../functions/_nx) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number, with gettext context. |
| [\_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. |
| [get\_user\_count()](../../functions/get_user_count) wp-includes/user.php | Returns the number of active users in your installation. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
wordpress WP_MS_Users_List_Table::get_sortable_columns(): array WP\_MS\_Users\_List\_Table::get\_sortable\_columns(): array
===========================================================
array
File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
protected function get_sortable_columns() {
return array(
'username' => 'login',
'name' => 'name',
'email' => 'email',
'registered' => 'id',
);
}
```
wordpress WP_MS_Users_List_Table::column_email( WP_User $user ) WP\_MS\_Users\_List\_Table::column\_email( WP\_User $user )
===========================================================
Handles the email column output.
`$user` [WP\_User](../wp_user) Required The current [WP\_User](../wp_user) object. File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
public function column_email( $user ) {
echo "<a href='" . esc_url( "mailto:$user->user_email" ) . "'>$user->user_email</a>";
}
```
| Uses | Description |
| --- | --- |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_MS_Users_List_Table::_column_blogs( WP_User $user, string $classes, string $data, string $primary ) WP\_MS\_Users\_List\_Table::\_column\_blogs( WP\_User $user, string $classes, string $data, string $primary )
=============================================================================================================
`$user` [WP\_User](../wp_user) Required `$classes` string Required `$data` string Required `$primary` string Required File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
protected function _column_blogs( $user, $classes, $data, $primary ) {
echo '<td class="', $classes, ' has-row-actions" ', $data, '>';
echo $this->column_blogs( $user );
echo $this->handle_row_actions( $user, 'blogs', $primary );
echo '</td>';
}
```
| Uses | Description |
| --- | --- |
| [WP\_MS\_Users\_List\_Table::handle\_row\_actions()](handle_row_actions) wp-admin/includes/class-wp-ms-users-list-table.php | Generates and displays row action links. |
| [WP\_MS\_Users\_List\_Table::column\_blogs()](column_blogs) wp-admin/includes/class-wp-ms-users-list-table.php | Handles the sites column output. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
| programming_docs |
wordpress WP_MS_Users_List_Table::column_cb( WP_User $item ) WP\_MS\_Users\_List\_Table::column\_cb( WP\_User $item )
========================================================
Handles the checkbox column output.
`$item` [WP\_User](../wp_user) Required The current [WP\_User](../wp_user) object. File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$user = $item;
if ( is_super_admin( $user->ID ) ) {
return;
}
?>
<label class="screen-reader-text" for="blog_<?php echo $user->ID; ?>">
<?php
/* translators: %s: User login. */
printf( __( 'Select %s' ), $user->user_login );
?>
</label>
<input type="checkbox" id="blog_<?php echo $user->ID; ?>" name="allusers[]" value="<?php echo esc_attr( $user->ID ); ?>" />
<?php
}
```
| Uses | Description |
| --- | --- |
| [is\_super\_admin()](../../functions/is_super_admin) wp-includes/capabilities.php | Determines whether user is a site admin. |
| [\_\_()](../../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.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$user` 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_MS_Users_List_Table::get_columns(): array WP\_MS\_Users\_List\_Table::get\_columns(): array
=================================================
array
File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
public function get_columns() {
$users_columns = array(
'cb' => '<input type="checkbox" />',
'username' => __( 'Username' ),
'name' => __( 'Name' ),
'email' => __( 'Email' ),
'registered' => _x( 'Registered', 'user' ),
'blogs' => __( 'Sites' ),
);
/**
* Filters the columns displayed in the Network Admin Users list table.
*
* @since MU (3.0.0)
*
* @param string[] $users_columns An array of user columns. Default 'cb', 'username',
* 'name', 'email', 'registered', 'blogs'.
*/
return apply_filters( 'wpmu_users_columns', $users_columns );
}
```
[apply\_filters( 'wpmu\_users\_columns', string[] $users\_columns )](../../hooks/wpmu_users_columns)
Filters the columns displayed in the Network Admin Users list table.
| 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. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
wordpress WP_MS_Users_List_Table::column_blogs( WP_User $user ) WP\_MS\_Users\_List\_Table::column\_blogs( WP\_User $user )
===========================================================
Handles the sites column output.
`$user` [WP\_User](../wp_user) Required The current [WP\_User](../wp_user) object. File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
public function column_blogs( $user ) {
$blogs = get_blogs_of_user( $user->ID, true );
if ( ! is_array( $blogs ) ) {
return;
}
foreach ( $blogs as $site ) {
if ( ! can_edit_network( $site->site_id ) ) {
continue;
}
$path = ( '/' === $site->path ) ? '' : $site->path;
$site_classes = array( 'site-' . $site->site_id );
/**
* Filters the span class for a site listing on the mulisite user list table.
*
* @since 5.2.0
*
* @param string[] $site_classes Array of class names used within the span tag. Default "site-#" with the site's network ID.
* @param int $site_id Site ID.
* @param int $network_id Network ID.
* @param WP_User $user WP_User object.
*/
$site_classes = apply_filters( 'ms_user_list_site_class', $site_classes, $site->userblog_id, $site->site_id, $user );
if ( is_array( $site_classes ) && ! empty( $site_classes ) ) {
$site_classes = array_map( 'sanitize_html_class', array_unique( $site_classes ) );
echo '<span class="' . esc_attr( implode( ' ', $site_classes ) ) . '">';
} else {
echo '<span>';
}
echo '<a href="' . esc_url( network_admin_url( 'site-info.php?id=' . $site->userblog_id ) ) . '">' . str_replace( '.' . get_network()->domain, '', $site->domain . $path ) . '</a>';
echo ' <small class="row-actions">';
$actions = array();
$actions['edit'] = '<a href="' . esc_url( network_admin_url( 'site-info.php?id=' . $site->userblog_id ) ) . '">' . __( 'Edit' ) . '</a>';
$class = '';
if ( 1 === (int) $site->spam ) {
$class .= 'site-spammed ';
}
if ( 1 === (int) $site->mature ) {
$class .= 'site-mature ';
}
if ( 1 === (int) $site->deleted ) {
$class .= 'site-deleted ';
}
if ( 1 === (int) $site->archived ) {
$class .= 'site-archived ';
}
$actions['view'] = '<a class="' . $class . '" href="' . esc_url( get_home_url( $site->userblog_id ) ) . '">' . __( 'View' ) . '</a>';
/**
* Filters the action links displayed next the sites a user belongs to
* in the Network Admin Users list table.
*
* @since 3.1.0
*
* @param string[] $actions An array of action links to be displayed. Default 'Edit', 'View'.
* @param int $userblog_id The site ID.
*/
$actions = apply_filters( 'ms_user_list_site_actions', $actions, $site->userblog_id );
$action_count = count( $actions );
$i = 0;
foreach ( $actions as $action => $link ) {
++$i;
$separator = ( $i < $action_count ) ? ' | ' : '';
echo "<span class='$action'>{$link}{$separator}</span>";
}
echo '</small></span><br />';
}
}
```
[apply\_filters( 'ms\_user\_list\_site\_actions', string[] $actions, int $userblog\_id )](../../hooks/ms_user_list_site_actions)
Filters the action links displayed next the sites a user belongs to in the Network Admin Users list table.
[apply\_filters( 'ms\_user\_list\_site\_class', string[] $site\_classes, int $site\_id, int $network\_id, WP\_User $user )](../../hooks/ms_user_list_site_class)
Filters the span class for a site listing on the mulisite user list table.
| Uses | Description |
| --- | --- |
| [get\_network()](../../functions/get_network) wp-includes/ms-network.php | Retrieves network data given a network ID or network object. |
| [can\_edit\_network()](../../functions/can_edit_network) wp-admin/includes/ms.php | Whether or not we can edit this network from this page. |
| [network\_admin\_url()](../../functions/network_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the network. |
| [get\_home\_url()](../../functions/get_home_url) wp-includes/link-template.php | Retrieves the URL for a given site where the front end is accessible. |
| [get\_blogs\_of\_user()](../../functions/get_blogs_of_user) wp-includes/user.php | Gets the sites a user belongs to. |
| [\_\_()](../../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. |
| [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\_MS\_Users\_List\_Table::\_column\_blogs()](_column_blogs) wp-admin/includes/class-wp-ms-users-list-table.php | |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_MS_Users_List_Table::get_bulk_actions(): array WP\_MS\_Users\_List\_Table::get\_bulk\_actions(): array
=======================================================
array
File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
protected function get_bulk_actions() {
$actions = array();
if ( current_user_can( 'delete_users' ) ) {
$actions['delete'] = __( 'Delete' );
}
$actions['spam'] = _x( 'Mark as spam', 'user' );
$actions['notspam'] = _x( 'Not spam', 'user' );
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. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
wordpress WP_MS_Users_List_Table::column_name( WP_User $user ) WP\_MS\_Users\_List\_Table::column\_name( WP\_User $user )
==========================================================
Handles the name column output.
`$user` [WP\_User](../wp_user) Required The current [WP\_User](../wp_user) object. File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
public function column_name( $user ) {
if ( $user->first_name && $user->last_name ) {
printf(
/* translators: 1: User's first name, 2: Last name. */
_x( '%1$s %2$s', 'Display name based on first name and last name' ),
$user->first_name,
$user->last_name
);
} elseif ( $user->first_name ) {
echo $user->first_name;
} elseif ( $user->last_name ) {
echo $user->last_name;
} else {
echo '<span aria-hidden="true">—</span><span class="screen-reader-text">' . _x( 'Unknown', 'name' ) . '</span>';
}
}
```
| Uses | Description |
| --- | --- |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_MS_Users_List_Table::column_default( WP_User $item, string $column_name ) WP\_MS\_Users\_List\_Table::column\_default( WP\_User $item, string $column\_name )
===================================================================================
Handles the default column output.
`$item` [WP\_User](../wp_user) Required The current [WP\_User](../wp_user) object. `$column_name` string Required The current column name. File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
public function column_default( $item, $column_name ) {
/** This filter is documented in wp-admin/includes/class-wp-users-list-table.php */
echo apply_filters(
'manage_users_custom_column',
'', // Custom column output. Default empty.
$column_name,
$item->ID // User ID.
);
}
```
[apply\_filters( 'manage\_users\_custom\_column', string $output, string $column\_name, int $user\_id )](../../hooks/manage_users_custom_column)
Filters the display output of custom columns in the Users list table.
| 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 |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$user` 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_MS_Users_List_Table::column_registered( WP_User $user ) WP\_MS\_Users\_List\_Table::column\_registered( WP\_User $user )
================================================================
Handles the registered date column output.
`$user` [WP\_User](../wp_user) Required The current [WP\_User](../wp_user) object. File: `wp-admin/includes/class-wp-ms-users-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-users-list-table.php/)
```
public function column_registered( $user ) {
global $mode;
if ( 'list' === $mode ) {
$date = __( 'Y/m/d' );
} else {
$date = __( 'Y/m/d g:i:s a' );
}
echo mysql2date( $date, $user->user_registered );
}
```
| Uses | Description |
| --- | --- |
| [mysql2date()](../../functions/mysql2date) wp-includes/functions.php | Converts given MySQL date string into a different format. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Taxonomy::reset_default_labels() WP\_Taxonomy::reset\_default\_labels()
======================================
Resets the cache for the default labels.
File: `wp-includes/class-wp-taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-taxonomy.php/)
```
public static function reset_default_labels() {
self::$default_labels = array();
}
```
| Used By | Description |
| --- | --- |
| [create\_initial\_taxonomies()](../../functions/create_initial_taxonomies) wp-includes/taxonomy.php | Creates the initial taxonomies. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_Taxonomy::get_rest_controller(): WP_REST_Controller|null WP\_Taxonomy::get\_rest\_controller(): WP\_REST\_Controller|null
================================================================
Gets the REST API controller for this taxonomy.
Will only instantiate the controller class once per request.
[WP\_REST\_Controller](../wp_rest_controller)|null The controller instance, or null if the taxonomy is set not to show in rest.
File: `wp-includes/class-wp-taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-taxonomy.php/)
```
public function get_rest_controller() {
if ( ! $this->show_in_rest ) {
return null;
}
$class = $this->rest_controller_class ? $this->rest_controller_class : WP_REST_Terms_Controller::class;
if ( ! class_exists( $class ) ) {
return null;
}
if ( ! is_subclass_of( $class, WP_REST_Controller::class ) ) {
return null;
}
if ( ! $this->rest_controller ) {
$this->rest_controller = new $class( $this->name );
}
if ( ! ( $this->rest_controller instanceof $class ) ) {
return null;
}
return $this->rest_controller;
}
```
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Taxonomy::get_default_labels(): (string|null)[][] WP\_Taxonomy::get\_default\_labels(): (string|null)[][]
=======================================================
Returns the default labels for taxonomies.
(string|null)[][] The default labels for taxonomies.
File: `wp-includes/class-wp-taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-taxonomy.php/)
```
public static function get_default_labels() {
if ( ! empty( self::$default_labels ) ) {
return self::$default_labels;
}
$name_field_description = __( 'The name is how it appears on your site.' );
$slug_field_description = __( 'The “slug” is the URL-friendly version of the name. It is usually all lowercase and contains only letters, numbers, and hyphens.' );
$parent_field_description = __( 'Assign a parent term to create a hierarchy. The term Jazz, for example, would be the parent of Bebop and Big Band.' );
$desc_field_description = __( 'The description is not prominent by default; however, some themes may show it.' );
self::$default_labels = array(
'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
'popular_items' => array( __( 'Popular Tags' ), null ),
'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
'parent_item' => array( null, __( 'Parent Category' ) ),
'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
'name_field_description' => array( $name_field_description, $name_field_description ),
'slug_field_description' => array( $slug_field_description, $slug_field_description ),
'parent_field_description' => array( null, $parent_field_description ),
'desc_field_description' => array( $desc_field_description, $desc_field_description ),
'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ),
'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
'not_found' => array( __( 'No tags found.' ), __( 'No categories found.' ) ),
'no_terms' => array( __( 'No tags' ), __( 'No categories' ) ),
'filter_by_item' => array( null, __( 'Filter by category' ) ),
'items_list_navigation' => array( __( 'Tags list navigation' ), __( 'Categories list navigation' ) ),
'items_list' => array( __( 'Tags list' ), __( 'Categories list' ) ),
/* translators: Tab heading when selecting from the most used terms. */
'most_used' => array( _x( 'Most Used', 'tags' ), _x( 'Most Used', 'categories' ) ),
'back_to_items' => array( __( '← Go to Tags' ), __( '← Go to Categories' ) ),
'item_link' => array(
_x( 'Tag Link', 'navigation link block title' ),
_x( 'Category Link', 'navigation link block title' ),
),
'item_link_description' => array(
_x( 'A link to a tag.', 'navigation link block description' ),
_x( 'A link to a category.', 'navigation link block description' ),
),
);
return self::$default_labels;
}
```
| 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. |
| Used By | Description |
| --- | --- |
| [get\_taxonomy\_labels()](../../functions/get_taxonomy_labels) wp-includes/taxonomy.php | Builds an object with all taxonomy labels out of a taxonomy object. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
| programming_docs |
wordpress WP_Taxonomy::add_hooks() WP\_Taxonomy::add\_hooks()
==========================
Registers the ajax callback for the meta box.
File: `wp-includes/class-wp-taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-taxonomy.php/)
```
public function add_hooks() {
add_filter( 'wp_ajax_add-' . $this->name, '_wp_ajax_add_hierarchical_term' );
}
```
| Uses | Description |
| --- | --- |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Taxonomy::add_rewrite_rules() WP\_Taxonomy::add\_rewrite\_rules()
===================================
Adds the necessary rewrite rules for the taxonomy.
File: `wp-includes/class-wp-taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-taxonomy.php/)
```
public function add_rewrite_rules() {
/* @var WP $wp */
global $wp;
// Non-publicly queryable taxonomies should not register query vars, except in the admin.
if ( false !== $this->query_var && $wp ) {
$wp->add_query_var( $this->query_var );
}
if ( false !== $this->rewrite && ( is_admin() || get_option( 'permalink_structure' ) ) ) {
if ( $this->hierarchical && $this->rewrite['hierarchical'] ) {
$tag = '(.+?)';
} else {
$tag = '([^/]+)';
}
add_rewrite_tag( "%$this->name%", $tag, $this->query_var ? "{$this->query_var}=" : "taxonomy=$this->name&term=" );
add_permastruct( $this->name, "{$this->rewrite['slug']}/%$this->name%", $this->rewrite );
}
}
```
| 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. |
| [add\_rewrite\_tag()](../../functions/add_rewrite_tag) wp-includes/rewrite.php | Adds a new rewrite tag (like %postname%). |
| [add\_permastruct()](../../functions/add_permastruct) wp-includes/rewrite.php | Adds a permalink structure. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Taxonomy::remove_hooks() WP\_Taxonomy::remove\_hooks()
=============================
Removes the ajax callback for the meta box.
File: `wp-includes/class-wp-taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-taxonomy.php/)
```
public function remove_hooks() {
remove_filter( 'wp_ajax_add-' . $this->name, '_wp_ajax_add_hierarchical_term' );
}
```
| Uses | Description |
| --- | --- |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Taxonomy::__construct( string $taxonomy, array|string $object_type, array|string $args = array() ) WP\_Taxonomy::\_\_construct( string $taxonomy, array|string $object\_type, array|string $args = array() )
=========================================================================================================
Constructor.
See the [register\_taxonomy()](../../functions/register_taxonomy) function for accepted arguments for `$args`.
`$taxonomy` string Required Taxonomy key, must not exceed 32 characters. `$object_type` array|string Required Name of the object type for the taxonomy object. `$args` array|string Optional Array or query string of arguments for registering a taxonomy.
Default: `array()`
File: `wp-includes/class-wp-taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-taxonomy.php/)
```
public function __construct( $taxonomy, $object_type, $args = array() ) {
$this->name = $taxonomy;
$this->set_props( $object_type, $args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Taxonomy::set\_props()](set_props) wp-includes/class-wp-taxonomy.php | Sets taxonomy properties. |
| Used By | Description |
| --- | --- |
| [register\_taxonomy()](../../functions/register_taxonomy) wp-includes/taxonomy.php | Creates or modifies a taxonomy object. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Taxonomy::set_props( string|string[] $object_type, array|string $args ) WP\_Taxonomy::set\_props( string|string[] $object\_type, array|string $args )
=============================================================================
Sets taxonomy properties.
See the [register\_taxonomy()](../../functions/register_taxonomy) function for accepted arguments for `$args`.
`$object_type` string|string[] Required Name or array of names of the object types for the taxonomy. `$args` array|string Required Array or query string of arguments for registering a taxonomy. File: `wp-includes/class-wp-taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-taxonomy.php/)
```
public function set_props( $object_type, $args ) {
$args = wp_parse_args( $args );
/**
* Filters the arguments for registering a taxonomy.
*
* @since 4.4.0
*
* @param array $args Array of arguments for registering a taxonomy.
* See the register_taxonomy() function for accepted arguments.
* @param string $taxonomy Taxonomy key.
* @param string[] $object_type Array of names of object types for the taxonomy.
*/
$args = apply_filters( 'register_taxonomy_args', $args, $this->name, (array) $object_type );
$taxonomy = $this->name;
/**
* Filters the arguments for registering a specific taxonomy.
*
* The dynamic portion of the filter name, `$taxonomy`, refers to the taxonomy key.
*
* Possible hook names include:
*
* - `register_category_taxonomy_args`
* - `register_post_tag_taxonomy_args`
*
* @since 6.0.0
*
* @param array $args Array of arguments for registering a taxonomy.
* See the register_taxonomy() function for accepted arguments.
* @param string $taxonomy Taxonomy key.
* @param string[] $object_type Array of names of object types for the taxonomy.
*/
$args = apply_filters( "register_{$taxonomy}_taxonomy_args", $args, $this->name, (array) $object_type );
$defaults = array(
'labels' => array(),
'description' => '',
'public' => true,
'publicly_queryable' => null,
'hierarchical' => false,
'show_ui' => null,
'show_in_menu' => null,
'show_in_nav_menus' => null,
'show_tagcloud' => null,
'show_in_quick_edit' => null,
'show_admin_column' => false,
'meta_box_cb' => null,
'meta_box_sanitize_cb' => null,
'capabilities' => array(),
'rewrite' => true,
'query_var' => $this->name,
'update_count_callback' => '',
'show_in_rest' => false,
'rest_base' => false,
'rest_namespace' => false,
'rest_controller_class' => false,
'default_term' => null,
'sort' => null,
'args' => null,
'_builtin' => false,
);
$args = array_merge( $defaults, $args );
// If not set, default to the setting for 'public'.
if ( null === $args['publicly_queryable'] ) {
$args['publicly_queryable'] = $args['public'];
}
if ( false !== $args['query_var'] && ( is_admin() || false !== $args['publicly_queryable'] ) ) {
if ( true === $args['query_var'] ) {
$args['query_var'] = $this->name;
} else {
$args['query_var'] = sanitize_title_with_dashes( $args['query_var'] );
}
} else {
// Force 'query_var' to false for non-public taxonomies.
$args['query_var'] = false;
}
if ( false !== $args['rewrite'] && ( is_admin() || get_option( 'permalink_structure' ) ) ) {
$args['rewrite'] = wp_parse_args(
$args['rewrite'],
array(
'with_front' => true,
'hierarchical' => false,
'ep_mask' => EP_NONE,
)
);
if ( empty( $args['rewrite']['slug'] ) ) {
$args['rewrite']['slug'] = sanitize_title_with_dashes( $this->name );
}
}
// If not set, default to the setting for 'public'.
if ( null === $args['show_ui'] ) {
$args['show_ui'] = $args['public'];
}
// If not set, default to the setting for 'show_ui'.
if ( null === $args['show_in_menu'] || ! $args['show_ui'] ) {
$args['show_in_menu'] = $args['show_ui'];
}
// If not set, default to the setting for 'public'.
if ( null === $args['show_in_nav_menus'] ) {
$args['show_in_nav_menus'] = $args['public'];
}
// If not set, default to the setting for 'show_ui'.
if ( null === $args['show_tagcloud'] ) {
$args['show_tagcloud'] = $args['show_ui'];
}
// If not set, default to the setting for 'show_ui'.
if ( null === $args['show_in_quick_edit'] ) {
$args['show_in_quick_edit'] = $args['show_ui'];
}
// If not set, default rest_namespace to wp/v2 if show_in_rest is true.
if ( false === $args['rest_namespace'] && ! empty( $args['show_in_rest'] ) ) {
$args['rest_namespace'] = 'wp/v2';
}
$default_caps = array(
'manage_terms' => 'manage_categories',
'edit_terms' => 'manage_categories',
'delete_terms' => 'manage_categories',
'assign_terms' => 'edit_posts',
);
$args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
unset( $args['capabilities'] );
$args['object_type'] = array_unique( (array) $object_type );
// If not set, use the default meta box.
if ( null === $args['meta_box_cb'] ) {
if ( $args['hierarchical'] ) {
$args['meta_box_cb'] = 'post_categories_meta_box';
} else {
$args['meta_box_cb'] = 'post_tags_meta_box';
}
}
$args['name'] = $this->name;
// Default meta box sanitization callback depends on the value of 'meta_box_cb'.
if ( null === $args['meta_box_sanitize_cb'] ) {
switch ( $args['meta_box_cb'] ) {
case 'post_categories_meta_box':
$args['meta_box_sanitize_cb'] = 'taxonomy_meta_box_sanitize_cb_checkboxes';
break;
case 'post_tags_meta_box':
default:
$args['meta_box_sanitize_cb'] = 'taxonomy_meta_box_sanitize_cb_input';
break;
}
}
// Default taxonomy term.
if ( ! empty( $args['default_term'] ) ) {
if ( ! is_array( $args['default_term'] ) ) {
$args['default_term'] = array( 'name' => $args['default_term'] );
}
$args['default_term'] = wp_parse_args(
$args['default_term'],
array(
'name' => '',
'slug' => '',
'description' => '',
)
);
}
foreach ( $args as $property_name => $property_value ) {
$this->$property_name = $property_value;
}
$this->labels = get_taxonomy_labels( $this );
$this->label = $this->labels->name;
}
```
[apply\_filters( 'register\_taxonomy\_args', array $args, string $taxonomy, string[] $object\_type )](../../hooks/register_taxonomy_args)
Filters the arguments for registering a taxonomy.
[apply\_filters( "register\_{$taxonomy}\_taxonomy\_args", array $args, string $taxonomy, string[] $object\_type )](../../hooks/register_taxonomy_taxonomy_args)
Filters the arguments for registering a specific taxonomy.
| Uses | Description |
| --- | --- |
| [sanitize\_title\_with\_dashes()](../../functions/sanitize_title_with_dashes) wp-includes/formatting.php | Sanitizes a title, replacing whitespace and a few other characters with dashes. |
| [get\_taxonomy\_labels()](../../functions/get_taxonomy_labels) wp-includes/taxonomy.php | Builds an object with all taxonomy labels out of a taxonomy object. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| [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\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Taxonomy::\_\_construct()](__construct) wp-includes/class-wp-taxonomy.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Taxonomy::remove_rewrite_rules() WP\_Taxonomy::remove\_rewrite\_rules()
======================================
Removes any rewrite rules, permastructs, and rules for the taxonomy.
File: `wp-includes/class-wp-taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-taxonomy.php/)
```
public function remove_rewrite_rules() {
/* @var WP $wp */
global $wp;
// Remove query var.
if ( false !== $this->query_var ) {
$wp->remove_query_var( $this->query_var );
}
// Remove rewrite tags and permastructs.
if ( false !== $this->rewrite ) {
remove_rewrite_tag( "%$this->name%" );
remove_permastruct( $this->name );
}
}
```
| Uses | Description |
| --- | --- |
| [WP::remove\_query\_var()](../wp/remove_query_var) wp-includes/class-wp.php | Removes a query variable from a list of public query variables. |
| [remove\_rewrite\_tag()](../../functions/remove_rewrite_tag) wp-includes/rewrite.php | Removes an existing rewrite tag (like %postname%). |
| [remove\_permastruct()](../../functions/remove_permastruct) wp-includes/rewrite.php | Removes a permalink structure. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Network::__set( string $key, mixed $value ) WP\_Network::\_\_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-network.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-network.php/)
```
public function __set( $key, $value ) {
switch ( $key ) {
case 'id':
$this->id = (int) $value;
break;
case 'blog_id':
case 'site_id':
$this->blog_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_Network::__get( string $key ): mixed WP\_Network::\_\_get( string $key ): mixed
==========================================
Getter.
Allows current multisite naming conventions when getting properties.
`$key` string Required Property to get. mixed Value of the property. Null if not available.
File: `wp-includes/class-wp-network.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-network.php/)
```
public function __get( $key ) {
switch ( $key ) {
case 'id':
return (int) $this->id;
case 'blog_id':
return (string) $this->get_main_site_id();
case 'site_id':
return $this->get_main_site_id();
}
return null;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Network::get\_main\_site\_id()](get_main_site_id) wp-includes/class-wp-network.php | Returns the main site ID for the network. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Network::get_by_path( string $domain = '', string $path = '', int|null $segments = null ): WP_Network|false WP\_Network::get\_by\_path( string $domain = '', string $path = '', int|null $segments = null ): WP\_Network|false
==================================================================================================================
Retrieves the closest matching network for a domain and path.
This will not necessarily return an exact match for a domain and path. Instead, it breaks the domain and path into pieces that are then used to match the closest possibility from a query.
The intent of this method is to match a network during bootstrap for a requested site address.
`$domain` string Optional Domain to check. Default: `''`
`$path` string Optional Path to check. Default: `''`
`$segments` int|null Optional Path segments to use. Defaults to null, or the full path. Default: `null`
[WP\_Network](../wp_network)|false Network object if successful. False when no network is found.
File: `wp-includes/class-wp-network.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-network.php/)
```
public static function get_by_path( $domain = '', $path = '', $segments = null ) {
$domains = array( $domain );
$pieces = explode( '.', $domain );
/*
* It's possible one domain to search is 'com', but it might as well
* be 'localhost' or some other locally mapped domain.
*/
while ( array_shift( $pieces ) ) {
if ( ! empty( $pieces ) ) {
$domains[] = implode( '.', $pieces );
}
}
/*
* If we've gotten to this function during normal execution, there is
* more than one network installed. At this point, who knows how many
* we have. Attempt to optimize for the situation where networks are
* only domains, thus meaning paths never need to be considered.
*
* This is a very basic optimization; anything further could have
* drawbacks depending on the setup, so this is best done per-installation.
*/
$using_paths = true;
if ( wp_using_ext_object_cache() ) {
$using_paths = get_networks(
array(
'number' => 1,
'count' => true,
'path__not_in' => '/',
)
);
}
$paths = array();
if ( $using_paths ) {
$path_segments = array_filter( explode( '/', trim( $path, '/' ) ) );
/**
* Filters the number of path segments to consider when searching for a site.
*
* @since 3.9.0
*
* @param int|null $segments The number of path segments to consider. WordPress by default looks at
* one path segment. The function default of null only makes sense when you
* know the requested path should match a network.
* @param string $domain The requested domain.
* @param string $path The requested path, in full.
*/
$segments = apply_filters( 'network_by_path_segments_count', $segments, $domain, $path );
if ( ( null !== $segments ) && count( $path_segments ) > $segments ) {
$path_segments = array_slice( $path_segments, 0, $segments );
}
while ( count( $path_segments ) ) {
$paths[] = '/' . implode( '/', $path_segments ) . '/';
array_pop( $path_segments );
}
$paths[] = '/';
}
/**
* Determines a network by its domain and path.
*
* This allows one to short-circuit the default logic, perhaps by
* replacing it with a routine that is more optimal for your setup.
*
* Return null to avoid the short-circuit. Return false if no network
* can be found at the requested domain and path. Otherwise, return
* an object from wp_get_network().
*
* @since 3.9.0
*
* @param null|false|WP_Network $network Network value to return by path. Default null
* to continue retrieving the network.
* @param string $domain The requested domain.
* @param string $path The requested path, in full.
* @param int|null $segments The suggested number of paths to consult.
* Default null, meaning the entire path was to be consulted.
* @param string[] $paths Array of paths to search for, based on `$path` and `$segments`.
*/
$pre = apply_filters( 'pre_get_network_by_path', null, $domain, $path, $segments, $paths );
if ( null !== $pre ) {
return $pre;
}
if ( ! $using_paths ) {
$networks = get_networks(
array(
'number' => 1,
'orderby' => array(
'domain_length' => 'DESC',
),
'domain__in' => $domains,
)
);
if ( ! empty( $networks ) ) {
return array_shift( $networks );
}
return false;
}
$networks = get_networks(
array(
'orderby' => array(
'domain_length' => 'DESC',
'path_length' => 'DESC',
),
'domain__in' => $domains,
'path__in' => $paths,
)
);
/*
* Domains are sorted by length of domain, then by length of path.
* The domain must match for the path to be considered. Otherwise,
* a network with the path of / will suffice.
*/
$found = false;
foreach ( $networks as $network ) {
if ( ( $network->domain === $domain ) || ( "www.{$network->domain}" === $domain ) ) {
if ( in_array( $network->path, $paths, true ) ) {
$found = true;
break;
}
}
if ( '/' === $network->path ) {
$found = true;
break;
}
}
if ( true === $found ) {
return $network;
}
return false;
}
```
[apply\_filters( 'network\_by\_path\_segments\_count', int|null $segments, string $domain, string $path )](../../hooks/network_by_path_segments_count)
Filters the number of path segments to consider when searching for a site.
[apply\_filters( 'pre\_get\_network\_by\_path', null|false|WP\_Network $network, string $domain, string $path, int|null $segments, string[] $paths )](../../hooks/pre_get_network_by_path)
Determines a network by its domain and path.
| Uses | Description |
| --- | --- |
| [get\_networks()](../../functions/get_networks) wp-includes/ms-network.php | Retrieves a list of networks. |
| [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. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [ms\_load\_current\_site\_and\_network()](../../functions/ms_load_current_site_and_network) wp-includes/ms-load.php | Identifies the network and site of a requested domain and path and populates the corresponding network and site global objects as part of the multisite bootstrap process. |
| [get\_network\_by\_path()](../../functions/get_network_by_path) wp-includes/ms-load.php | Retrieves the closest matching network for a domain and path. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress WP_Network::__isset( string $key ): bool WP\_Network::\_\_isset( string $key ): bool
===========================================
Isset-er.
Allows current multisite naming conventions when checking for properties.
`$key` string Required Property to check if set. bool Whether the property is set.
File: `wp-includes/class-wp-network.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-network.php/)
```
public function __isset( $key ) {
switch ( $key ) {
case 'id':
case 'blog_id':
case 'site_id':
return true;
}
return false;
}
```
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Network::__construct( WP_Network|object $network ) WP\_Network::\_\_construct( WP\_Network|object $network )
=========================================================
Creates a new [WP\_Network](../wp_network) object.
Will populate object properties from the object provided and assign other default properties based on that information.
`$network` [WP\_Network](../wp_network)|object Required A network object. File: `wp-includes/class-wp-network.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-network.php/)
```
public function __construct( $network ) {
foreach ( get_object_vars( $network ) as $key => $value ) {
$this->$key = $value;
}
$this->_set_site_name();
$this->_set_cookie_domain();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Network::\_set\_site\_name()](_set_site_name) wp-includes/class-wp-network.php | Sets the site name assigned to the network if one has not been populated. |
| [WP\_Network::\_set\_cookie\_domain()](_set_cookie_domain) wp-includes/class-wp-network.php | Sets the cookie domain based on the network domain if one has not been populated. |
| Used By | Description |
| --- | --- |
| [get\_network()](../../functions/get_network) wp-includes/ms-network.php | Retrieves network data given a network ID or network object. |
| [WP\_Network::get\_instance()](get_instance) wp-includes/class-wp-network.php | Retrieves a network from the database by its ID. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Network::get_instance( int $network_id ): WP_Network|false WP\_Network::get\_instance( int $network\_id ): WP\_Network|false
=================================================================
Retrieves a network from the database by its ID.
`$network_id` int Required The ID of the network to retrieve. [WP\_Network](../wp_network)|false The network's object if found. False if not.
File: `wp-includes/class-wp-network.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-network.php/)
```
public static function get_instance( $network_id ) {
global $wpdb;
$network_id = (int) $network_id;
if ( ! $network_id ) {
return false;
}
$_network = wp_cache_get( $network_id, 'networks' );
if ( false === $_network ) {
$_network = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->site} WHERE id = %d LIMIT 1", $network_id ) );
if ( empty( $_network ) || is_wp_error( $_network ) ) {
$_network = -1;
}
wp_cache_add( $network_id, $_network, 'networks' );
}
if ( is_numeric( $_network ) ) {
return false;
}
return new WP_Network( $_network );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Network::\_\_construct()](__construct) wp-includes/class-wp-network.php | Creates a new [WP\_Network](../wp_network) 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 |
| --- | --- |
| [get\_network()](../../functions/get_network) wp-includes/ms-network.php | Retrieves network data given a network ID or network object. |
| [ms\_load\_current\_site\_and\_network()](../../functions/ms_load_current_site_and_network) wp-includes/ms-load.php | Identifies the network and site of a requested domain and path and populates the corresponding network and site global objects as part of the multisite bootstrap process. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Network::get_main_site_id(): int WP\_Network::get\_main\_site\_id(): 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.
Returns the main site ID for the network.
Internal method used by the magic getter for the ‘blog\_id’ and ‘site\_id’ properties.
int The ID of the main site.
File: `wp-includes/class-wp-network.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-network.php/)
```
private function get_main_site_id() {
/**
* Filters the main site ID.
*
* Returning a positive integer will effectively short-circuit the function.
*
* @since 4.9.0
*
* @param int|null $main_site_id If a positive integer is returned, it is interpreted as the main site ID.
* @param WP_Network $network The network object for which the main site was detected.
*/
$main_site_id = (int) apply_filters( 'pre_get_main_site_id', null, $this );
if ( 0 < $main_site_id ) {
return $main_site_id;
}
if ( 0 < (int) $this->blog_id ) {
return (int) $this->blog_id;
}
if ( ( defined( 'DOMAIN_CURRENT_SITE' ) && defined( 'PATH_CURRENT_SITE' ) && DOMAIN_CURRENT_SITE === $this->domain && PATH_CURRENT_SITE === $this->path )
|| ( defined( 'SITE_ID_CURRENT_SITE' ) && SITE_ID_CURRENT_SITE == $this->id ) ) {
if ( defined( 'BLOG_ID_CURRENT_SITE' ) ) {
$this->blog_id = (string) BLOG_ID_CURRENT_SITE;
return (int) $this->blog_id;
}
if ( defined( 'BLOGID_CURRENT_SITE' ) ) { // Deprecated.
$this->blog_id = (string) BLOGID_CURRENT_SITE;
return (int) $this->blog_id;
}
}
$site = get_site();
if ( $site->domain === $this->domain && $site->path === $this->path ) {
$main_site_id = (int) $site->id;
} else {
$main_site_id = get_network_option( $this->id, 'main_site' );
if ( false === $main_site_id ) {
$_sites = get_sites(
array(
'fields' => 'ids',
'number' => 1,
'domain' => $this->domain,
'path' => $this->path,
'network_id' => $this->id,
)
);
$main_site_id = ! empty( $_sites ) ? array_shift( $_sites ) : 0;
update_network_option( $this->id, 'main_site', $main_site_id );
}
}
$this->blog_id = (string) $main_site_id;
return (int) $this->blog_id;
}
```
[apply\_filters( 'pre\_get\_main\_site\_id', int|null $main\_site\_id, WP\_Network $network )](../../hooks/pre_get_main_site_id)
Filters the main site ID.
| Uses | Description |
| --- | --- |
| [get\_sites()](../../functions/get_sites) wp-includes/ms-site.php | Retrieves a list of sites matching requested arguments. |
| [get\_site()](../../functions/get_site) wp-includes/ms-site.php | Retrieves site data given a site ID or site object. |
| [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. |
| [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\_Network::\_\_get()](__get) wp-includes/class-wp-network.php | Getter. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Network::_set_site_name() WP\_Network::\_set\_site\_name()
================================
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.
Sets the site name assigned to the network if one has not been populated.
File: `wp-includes/class-wp-network.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-network.php/)
```
private function _set_site_name() {
if ( ! empty( $this->site_name ) ) {
return;
}
$default = ucfirst( $this->domain );
$this->site_name = get_network_option( $this->id, 'site_name', $default );
}
```
| Uses | Description |
| --- | --- |
| [get\_network\_option()](../../functions/get_network_option) wp-includes/option.php | Retrieves a network’s option value based on the option name. |
| Used By | Description |
| --- | --- |
| [WP\_Network::\_\_construct()](__construct) wp-includes/class-wp-network.php | Creates a new [WP\_Network](../wp_network) object. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Network::_set_cookie_domain() WP\_Network::\_set\_cookie\_domain()
====================================
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.
Sets the cookie domain based on the network domain if one has not been populated.
File: `wp-includes/class-wp-network.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-network.php/)
```
private function _set_cookie_domain() {
if ( ! empty( $this->cookie_domain ) ) {
return;
}
$this->cookie_domain = $this->domain;
if ( 'www.' === substr( $this->cookie_domain, 0, 4 ) ) {
$this->cookie_domain = substr( $this->cookie_domain, 4 );
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Network::\_\_construct()](__construct) wp-includes/class-wp-network.php | Creates a new [WP\_Network](../wp_network) object. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Block_Pattern_Categories_Registry::register( string $category_name, array $category_properties ): bool WP\_Block\_Pattern\_Categories\_Registry::register( string $category\_name, array $category\_properties ): bool
===============================================================================================================
Registers a pattern category.
`$category_name` string Required Pattern category name including namespace. `$category_properties` array Required List of properties for the block pattern category.
* `label`stringRequired. A human-readable label for the pattern category.
bool True if the pattern was registered with success and false otherwise.
File: `wp-includes/class-wp-block-pattern-categories-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-pattern-categories-registry.php/)
```
public function register( $category_name, $category_properties ) {
if ( ! isset( $category_name ) || ! is_string( $category_name ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Block pattern category name must be a string.' ),
'5.5.0'
);
return false;
}
$category = array_merge(
array( 'name' => $category_name ),
$category_properties
);
$this->registered_categories[ $category_name ] = $category;
// If the category is registered inside an action other than `init`, store it
// also to a dedicated array. Used to detect deprecated registrations inside
// `admin_init` or `current_screen`.
if ( current_action() && 'init' !== current_action() ) {
$this->registered_categories_outside_init[ $category_name ] = $category;
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [current\_action()](../../functions/current_action) wp-includes/plugin.php | Retrieves the name of the current action hook. |
| [\_\_()](../../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.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Block_Pattern_Categories_Registry::unregister( string $category_name ): bool WP\_Block\_Pattern\_Categories\_Registry::unregister( string $category\_name ): bool
====================================================================================
Unregisters a pattern category.
`$category_name` string Required Pattern category name including namespace. bool True if the pattern was unregistered with success and false otherwise.
File: `wp-includes/class-wp-block-pattern-categories-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-pattern-categories-registry.php/)
```
public function unregister( $category_name ) {
if ( ! $this->is_registered( $category_name ) ) {
_doing_it_wrong(
__METHOD__,
/* translators: %s: Block pattern name. */
sprintf( __( 'Block pattern category "%s" not found.' ), $category_name ),
'5.5.0'
);
return false;
}
unset( $this->registered_categories[ $category_name ] );
unset( $this->registered_categories_outside_init[ $category_name ] );
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_Pattern\_Categories\_Registry::is\_registered()](is_registered) wp-includes/class-wp-block-pattern-categories-registry.php | Checks if a pattern category 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.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Block_Pattern_Categories_Registry::get_registered( string $category_name ): array WP\_Block\_Pattern\_Categories\_Registry::get\_registered( string $category\_name ): array
==========================================================================================
Retrieves an array containing the properties of a registered pattern category.
`$category_name` string Required Pattern category name including namespace. array Registered pattern properties.
File: `wp-includes/class-wp-block-pattern-categories-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-pattern-categories-registry.php/)
```
public function get_registered( $category_name ) {
if ( ! $this->is_registered( $category_name ) ) {
return null;
}
return $this->registered_categories[ $category_name ];
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_Pattern\_Categories\_Registry::is\_registered()](is_registered) wp-includes/class-wp-block-pattern-categories-registry.php | Checks if a pattern category is registered. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Block_Pattern_Categories_Registry::get_all_registered( bool $outside_init_only = false ): array[] WP\_Block\_Pattern\_Categories\_Registry::get\_all\_registered( bool $outside\_init\_only = false ): array[]
============================================================================================================
Retrieves all registered pattern categories.
`$outside_init_only` bool Optional Return only categories registered outside the `init` action. Default: `false`
array[] Array of arrays containing the registered pattern categories properties.
File: `wp-includes/class-wp-block-pattern-categories-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-pattern-categories-registry.php/)
```
public function get_all_registered( $outside_init_only = false ) {
return array_values(
$outside_init_only
? $this->registered_categories_outside_init
: $this->registered_categories
);
}
```
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Block_Pattern_Categories_Registry::get_instance(): WP_Block_Pattern_Categories_Registry WP\_Block\_Pattern\_Categories\_Registry::get\_instance(): WP\_Block\_Pattern\_Categories\_Registry
===================================================================================================
Utility method to retrieve the main instance of the class.
The instance will be created if it does not exist yet.
[WP\_Block\_Pattern\_Categories\_Registry](../wp_block_pattern_categories_registry) The main instance.
File: `wp-includes/class-wp-block-pattern-categories-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-pattern-categories-registry.php/)
```
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Block\_Pattern\_Categories\_Controller::get\_items()](../wp_rest_block_pattern_categories_controller/get_items) wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php | Retrieves all block pattern categories. |
| [register\_block\_pattern\_category()](../../functions/register_block_pattern_category) wp-includes/class-wp-block-pattern-categories-registry.php | Registers a new pattern category. |
| [unregister\_block\_pattern\_category()](../../functions/unregister_block_pattern_category) wp-includes/class-wp-block-pattern-categories-registry.php | Unregisters a pattern category. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Block_Pattern_Categories_Registry::is_registered( string $category_name ): bool WP\_Block\_Pattern\_Categories\_Registry::is\_registered( string $category\_name ): bool
========================================================================================
Checks if a pattern category is registered.
`$category_name` string Required Pattern category name including namespace. bool True if the pattern category is registered, false otherwise.
File: `wp-includes/class-wp-block-pattern-categories-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-pattern-categories-registry.php/)
```
public function is_registered( $category_name ) {
return isset( $this->registered_categories[ $category_name ] );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Block\_Pattern\_Categories\_Registry::unregister()](unregister) wp-includes/class-wp-block-pattern-categories-registry.php | Unregisters a pattern category. |
| [WP\_Block\_Pattern\_Categories\_Registry::get\_registered()](get_registered) wp-includes/class-wp-block-pattern-categories-registry.php | Retrieves an array containing the properties of a registered pattern category. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
| programming_docs |
wordpress IXR_Server::listMethods( $args ) IXR\_Server::listMethods( $args )
=================================
File: `wp-includes/IXR/class-IXR-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-server.php/)
```
function listMethods($args)
{
// Returns a list of methods - uses array_reverse to ensure user defined
// methods are listed before server defined methods
return array_reverse(array_keys($this->callbacks));
}
```
wordpress IXR_Server::multiCall( $methodcalls ) IXR\_Server::multiCall( $methodcalls )
======================================
File: `wp-includes/IXR/class-IXR-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-server.php/)
```
function multiCall($methodcalls)
{
// See http://www.xmlrpc.com/discuss/msgReader$1208
$return = array();
foreach ($methodcalls as $call) {
$method = $call['methodName'];
$params = $call['params'];
if ($method == 'system.multicall') {
$result = new IXR_Error(-32600, 'Recursive calls to system.multicall are forbidden');
} else {
$result = $this->call($method, $params);
}
if (is_a($result, 'IXR_Error')) {
$return[] = array(
'faultCode' => $result->code,
'faultString' => $result->message
);
} else {
$return[] = array($result);
}
}
return $return;
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Server::call()](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_Server::setCallbacks() IXR\_Server::setCallbacks()
===========================
File: `wp-includes/IXR/class-IXR-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-server.php/)
```
function setCallbacks()
{
$this->callbacks['system.getCapabilities'] = 'this:getCapabilities';
$this->callbacks['system.listMethods'] = 'this:listMethods';
$this->callbacks['system.multicall'] = 'this:multiCall';
}
```
| Used By | Description |
| --- | --- |
| [IXR\_Server::\_\_construct()](__construct) wp-includes/IXR/class-IXR-server.php | PHP5 constructor. |
wordpress IXR_Server::call( $methodname, $args ) IXR\_Server::call( $methodname, $args )
=======================================
File: `wp-includes/IXR/class-IXR-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-server.php/)
```
function call($methodname, $args)
{
if (!$this->hasMethod($methodname)) {
return new IXR_Error(-32601, 'server error. requested method '.$methodname.' does not exist.');
}
$method = $this->callbacks[$methodname];
// Perform the callback and send the response
if (count($args) == 1) {
// If only one parameter just send that instead of the whole array
$args = $args[0];
}
// Are we dealing with a function or a method?
if (is_string($method) && substr($method, 0, 5) == 'this:') {
// It's a class method - check it exists
$method = substr($method, 5);
if (!method_exists($this, $method)) {
return new IXR_Error(-32601, 'server error. requested class method "'.$method.'" does not exist.');
}
//Call the method
$result = $this->$method($args);
} else {
// It's a function - does it exist?
if (is_array($method)) {
if (!is_callable(array($method[0], $method[1]))) {
return new IXR_Error(-32601, 'server error. requested object method "'.$method[1].'" does not exist.');
}
} else if (!function_exists($method)) {
return new IXR_Error(-32601, 'server error. requested function "'.$method.'" does not exist.');
}
// Call the function
$result = call_user_func($method, $args);
}
return $result;
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Server::hasMethod()](hasmethod) wp-includes/IXR/class-IXR-server.php | |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| Used By | Description |
| --- | --- |
| [IXR\_IntrospectionServer::call()](../ixr_introspectionserver/call) wp-includes/IXR/class-IXR-introspectionserver.php | |
| [IXR\_Server::multiCall()](multicall) wp-includes/IXR/class-IXR-server.php | |
| [IXR\_Server::serve()](serve) wp-includes/IXR/class-IXR-server.php | |
wordpress IXR_Server::IXR_Server( $callbacks = false, $data = false, $wait = false ) IXR\_Server::IXR\_Server( $callbacks = false, $data = false, $wait = false )
============================================================================
PHP4 constructor.
File: `wp-includes/IXR/class-IXR-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-server.php/)
```
public function IXR_Server( $callbacks = false, $data = false, $wait = false ) {
self::__construct( $callbacks, $data, $wait );
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Server::\_\_construct()](__construct) wp-includes/IXR/class-IXR-server.php | PHP5 constructor. |
wordpress IXR_Server::output( $xml ) IXR\_Server::output( $xml )
===========================
File: `wp-includes/IXR/class-IXR-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-server.php/)
```
function output($xml)
{
$charset = function_exists('get_option') ? get_option('blog_charset') : '';
if ($charset)
$xml = '<?xml version="1.0" encoding="'.$charset.'"?>'."\n".$xml;
else
$xml = '<?xml version="1.0"?>'."\n".$xml;
$length = strlen($xml);
header('Connection: close');
if ($charset)
header('Content-Type: text/xml; charset='.$charset);
else
header('Content-Type: text/xml');
header('Date: '.gmdate('r'));
echo $xml;
exit;
}
```
| Uses | Description |
| --- | --- |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [IXR\_Server::error()](error) wp-includes/IXR/class-IXR-server.php | |
| [IXR\_Server::serve()](serve) wp-includes/IXR/class-IXR-server.php | |
wordpress IXR_Server::serve( $data = false ) IXR\_Server::serve( $data = false )
===================================
File: `wp-includes/IXR/class-IXR-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-server.php/)
```
function serve($data = false)
{
if (!$data) {
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] !== 'POST') {
if ( function_exists( 'status_header' ) ) {
status_header( 405 ); // WP #20986
header( 'Allow: POST' );
}
header('Content-Type: text/plain'); // merged from WP #9093
die('XML-RPC server accepts POST requests only.');
}
$data = file_get_contents('php://input');
}
$this->message = new IXR_Message($data);
if (!$this->message->parse()) {
$this->error(-32700, 'parse error. not well formed');
}
if ($this->message->messageType != 'methodCall') {
$this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
}
$result = $this->call($this->message->methodName, $this->message->params);
// Is the result an error?
if (is_a($result, 'IXR_Error')) {
$this->error($result);
}
// Encode the result
$r = new IXR_Value($result);
$resultxml = $r->getXml();
// Create the XML
$xml = <<<EOD
<methodResponse>
<params>
<param>
<value>
$resultxml
</value>
</param>
</params>
</methodResponse>
EOD;
// Send it
$this->output($xml);
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Server::error()](error) wp-includes/IXR/class-IXR-server.php | |
| [IXR\_Server::output()](output) wp-includes/IXR/class-IXR-server.php | |
| [IXR\_Server::call()](call) wp-includes/IXR/class-IXR-server.php | |
| [IXR\_Value::\_\_construct()](../ixr_value/__construct) wp-includes/IXR/class-IXR-value.php | PHP5 constructor. |
| [IXR\_Message::\_\_construct()](../ixr_message/__construct) wp-includes/IXR/class-IXR-message.php | PHP5 constructor. |
| [status\_header()](../../functions/status_header) wp-includes/functions.php | Sets HTTP status header. |
| Used By | Description |
| --- | --- |
| [IXR\_Server::\_\_construct()](__construct) wp-includes/IXR/class-IXR-server.php | PHP5 constructor. |
wordpress IXR_Server::__construct( $callbacks = false, $data = false, $wait = false ) IXR\_Server::\_\_construct( $callbacks = false, $data = false, $wait = false )
==============================================================================
PHP5 constructor.
File: `wp-includes/IXR/class-IXR-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-server.php/)
```
function __construct( $callbacks = false, $data = false, $wait = false )
{
$this->setCapabilities();
if ($callbacks) {
$this->callbacks = $callbacks;
}
$this->setCallbacks();
if (!$wait) {
$this->serve($data);
}
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Server::setCapabilities()](setcapabilities) wp-includes/IXR/class-IXR-server.php | |
| [IXR\_Server::setCallbacks()](setcallbacks) wp-includes/IXR/class-IXR-server.php | |
| [IXR\_Server::serve()](serve) wp-includes/IXR/class-IXR-server.php | |
| Used By | Description |
| --- | --- |
| [IXR\_Server::IXR\_Server()](ixr_server) wp-includes/IXR/class-IXR-server.php | PHP4 constructor. |
wordpress IXR_Server::setCapabilities() IXR\_Server::setCapabilities()
==============================
File: `wp-includes/IXR/class-IXR-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-server.php/)
```
function setCapabilities()
{
// Initialises capabilities array
$this->capabilities = array(
'xmlrpc' => array(
'specUrl' => 'http://www.xmlrpc.com/spec',
'specVersion' => 1
),
'faults_interop' => array(
'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php',
'specVersion' => 20010516
),
'system.multicall' => array(
'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
'specVersion' => 1
),
);
}
```
| Used By | Description |
| --- | --- |
| [IXR\_Server::\_\_construct()](__construct) wp-includes/IXR/class-IXR-server.php | PHP5 constructor. |
wordpress IXR_Server::error( $error, $message = false ) IXR\_Server::error( $error, $message = false )
==============================================
File: `wp-includes/IXR/class-IXR-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-server.php/)
```
function error($error, $message = false)
{
// Accepts either an error object or an error code and message
if ($message && !is_object($error)) {
$error = new IXR_Error($error, $message);
}
$this->output($error->getXml());
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Server::output()](output) wp-includes/IXR/class-IXR-server.php | |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| Used By | Description |
| --- | --- |
| [IXR\_Server::serve()](serve) wp-includes/IXR/class-IXR-server.php | |
wordpress IXR_Server::getCapabilities( $args ) IXR\_Server::getCapabilities( $args )
=====================================
File: `wp-includes/IXR/class-IXR-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-server.php/)
```
function getCapabilities($args)
{
return $this->capabilities;
}
```
wordpress IXR_Server::hasMethod( $method ) IXR\_Server::hasMethod( $method )
=================================
File: `wp-includes/IXR/class-IXR-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-server.php/)
```
function hasMethod($method)
{
return in_array($method, array_keys($this->callbacks));
}
```
| Used By | Description |
| --- | --- |
| [IXR\_Server::call()](call) wp-includes/IXR/class-IXR-server.php | |
wordpress WP_Sitemaps_Registry::get_provider( string $name ): WP_Sitemaps_Provider|null WP\_Sitemaps\_Registry::get\_provider( string $name ): WP\_Sitemaps\_Provider|null
==================================================================================
Returns a single registered sitemap provider.
`$name` string Required Sitemap provider name. [WP\_Sitemaps\_Provider](../wp_sitemaps_provider)|null Sitemap provider if it exists, null otherwise.
File: `wp-includes/sitemaps/class-wp-sitemaps-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps-registry.php/)
```
public function get_provider( $name ) {
if ( ! is_string( $name ) || ! isset( $this->providers[ $name ] ) ) {
return null;
}
return $this->providers[ $name ];
}
```
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps_Registry::get_providers(): WP_Sitemaps_Provider[] WP\_Sitemaps\_Registry::get\_providers(): WP\_Sitemaps\_Provider[]
==================================================================
Returns all registered sitemap providers.
[WP\_Sitemaps\_Provider](../wp_sitemaps_provider)[] Array of sitemap providers.
File: `wp-includes/sitemaps/class-wp-sitemaps-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps-registry.php/)
```
public function get_providers() {
return $this->providers;
}
```
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps_Registry::add_provider( string $name, WP_Sitemaps_Provider $provider ): bool WP\_Sitemaps\_Registry::add\_provider( string $name, WP\_Sitemaps\_Provider $provider ): bool
=============================================================================================
Adds a new sitemap provider.
`$name` string Required Name of the sitemap provider. `$provider` [WP\_Sitemaps\_Provider](../wp_sitemaps_provider) Required Instance of a [WP\_Sitemaps\_Provider](../wp_sitemaps_provider). bool Whether the provider was added successfully.
File: `wp-includes/sitemaps/class-wp-sitemaps-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps-registry.php/)
```
public function add_provider( $name, WP_Sitemaps_Provider $provider ) {
if ( isset( $this->providers[ $name ] ) ) {
return false;
}
/**
* Filters the sitemap provider before it is added.
*
* @since 5.5.0
*
* @param WP_Sitemaps_Provider $provider Instance of a WP_Sitemaps_Provider.
* @param string $name Name of the sitemap provider.
*/
$provider = apply_filters( 'wp_sitemaps_add_provider', $provider, $name );
if ( ! $provider instanceof WP_Sitemaps_Provider ) {
return false;
}
$this->providers[ $name ] = $provider;
return true;
}
```
[apply\_filters( 'wp\_sitemaps\_add\_provider', WP\_Sitemaps\_Provider $provider, string $name )](../../hooks/wp_sitemaps_add_provider)
Filters the sitemap provider before it is added.
| 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 |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress Requests_Utility_CaseInsensitiveDictionary::getIterator(): ArrayIterator Requests\_Utility\_CaseInsensitiveDictionary::getIterator(): ArrayIterator
==========================================================================
Get an iterator for the data
ArrayIterator
File: `wp-includes/Requests/Utility/CaseInsensitiveDictionary.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/caseinsensitivedictionary.php/)
```
public function getIterator() {
return new ArrayIterator($this->data);
}
```
wordpress Requests_Utility_CaseInsensitiveDictionary::offsetGet( string $key ): string|null Requests\_Utility\_CaseInsensitiveDictionary::offsetGet( string $key ): string|null
===================================================================================
Get the value for the item
`$key` string Required Item key string|null Item value (null if offsetExists is false)
File: `wp-includes/Requests/Utility/CaseInsensitiveDictionary.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/caseinsensitivedictionary.php/)
```
public function offsetGet($key) {
$key = strtolower($key);
if (!isset($this->data[$key])) {
return null;
}
return $this->data[$key];
}
```
wordpress Requests_Utility_CaseInsensitiveDictionary::offsetUnset( string $key ) Requests\_Utility\_CaseInsensitiveDictionary::offsetUnset( string $key )
========================================================================
Unset the given header
`$key` string Required File: `wp-includes/Requests/Utility/CaseInsensitiveDictionary.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/caseinsensitivedictionary.php/)
```
public function offsetUnset($key) {
unset($this->data[strtolower($key)]);
}
```
wordpress Requests_Utility_CaseInsensitiveDictionary::offsetSet( string $key, string $value ) Requests\_Utility\_CaseInsensitiveDictionary::offsetSet( string $key, string $value )
=====================================================================================
Set the given item
`$key` string Required Item name `$value` string Required Item value File: `wp-includes/Requests/Utility/CaseInsensitiveDictionary.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/caseinsensitivedictionary.php/)
```
public function offsetSet($key, $value) {
if ($key === null) {
throw new Requests_Exception('Object is a dictionary, not a list', 'invalidset');
}
$key = strtolower($key);
$this->data[$key] = $value;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception::\_\_construct()](../requests_exception/__construct) wp-includes/Requests/Exception.php | Create a new exception |
| Used By | Description |
| --- | --- |
| [Requests\_Utility\_CaseInsensitiveDictionary::\_\_construct()](__construct) wp-includes/Requests/Utility/CaseInsensitiveDictionary.php | Creates a case insensitive dictionary. |
wordpress Requests_Utility_CaseInsensitiveDictionary::getAll(): array Requests\_Utility\_CaseInsensitiveDictionary::getAll(): array
=============================================================
Get the headers as an array
array Header data
File: `wp-includes/Requests/Utility/CaseInsensitiveDictionary.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/caseinsensitivedictionary.php/)
```
public function getAll() {
return $this->data;
}
```
| programming_docs |
wordpress Requests_Utility_CaseInsensitiveDictionary::offsetExists( string $key ): boolean Requests\_Utility\_CaseInsensitiveDictionary::offsetExists( string $key ): boolean
==================================================================================
Check if the given item exists
`$key` string Required Item key boolean Does the item exist?
File: `wp-includes/Requests/Utility/CaseInsensitiveDictionary.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/caseinsensitivedictionary.php/)
```
public function offsetExists($key) {
$key = strtolower($key);
return isset($this->data[$key]);
}
```
wordpress Requests_Utility_CaseInsensitiveDictionary::__construct( array $data = array() ) Requests\_Utility\_CaseInsensitiveDictionary::\_\_construct( array $data = array() )
====================================================================================
Creates a case insensitive dictionary.
`$data` array Optional Dictionary/map to convert to case-insensitive Default: `array()`
File: `wp-includes/Requests/Utility/CaseInsensitiveDictionary.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/caseinsensitivedictionary.php/)
```
public function __construct(array $data = array()) {
foreach ($data as $key => $value) {
$this->offsetSet($key, $value);
}
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Utility\_CaseInsensitiveDictionary::offsetSet()](offsetset) wp-includes/Requests/Utility/CaseInsensitiveDictionary.php | Set the given item |
| Used By | Description |
| --- | --- |
| [Requests\_Cookie::parse()](../requests_cookie/parse) wp-includes/Requests/Cookie.php | Parse a cookie string into a cookie object |
| [Requests\_Transport\_fsockopen::request()](../requests_transport_fsockopen/request) wp-includes/Requests/Transport/fsockopen.php | Perform a request |
| [WP\_HTTP\_Requests\_Response::get\_headers()](../wp_http_requests_response/get_headers) wp-includes/class-wp-http-requests-response.php | Retrieves headers associated with the response. |
wordpress WP_Hook::apply_filters( mixed $value, array $args ): mixed WP\_Hook::apply\_filters( mixed $value, array $args ): mixed
============================================================
Calls the callback functions that have been added to a filter hook.
`$value` mixed Required The value to filter. `$args` array Required Additional parameters to pass to the callback functions.
This array is expected to include $value at index 0. mixed The filtered value after all hooked functions are applied to it.
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function apply_filters( $value, $args ) {
if ( ! $this->callbacks ) {
return $value;
}
$nesting_level = $this->nesting_level++;
$this->iterations[ $nesting_level ] = array_keys( $this->callbacks );
$num_args = count( $args );
do {
$this->current_priority[ $nesting_level ] = current( $this->iterations[ $nesting_level ] );
$priority = $this->current_priority[ $nesting_level ];
foreach ( $this->callbacks[ $priority ] as $the_ ) {
if ( ! $this->doing_action ) {
$args[0] = $value;
}
// Avoid the array_slice() if possible.
if ( 0 == $the_['accepted_args'] ) {
$value = call_user_func( $the_['function'] );
} elseif ( $the_['accepted_args'] >= $num_args ) {
$value = call_user_func_array( $the_['function'], $args );
} else {
$value = call_user_func_array( $the_['function'], array_slice( $args, 0, (int) $the_['accepted_args'] ) );
}
}
} while ( false !== next( $this->iterations[ $nesting_level ] ) );
unset( $this->iterations[ $nesting_level ] );
unset( $this->current_priority[ $nesting_level ] );
$this->nesting_level--;
return $value;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Hook::do\_action()](do_action) wp-includes/class-wp-hook.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Hook::offsetGet( $offset ) WP\_Hook::offsetGet( $offset )
==============================
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function offsetGet( $offset ) {
return isset( $this->callbacks[ $offset ] ) ? $this->callbacks[ $offset ] : null;
}
```
wordpress WP_Hook::offsetUnset( $offset ) WP\_Hook::offsetUnset( $offset )
================================
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function offsetUnset( $offset ) {
unset( $this->callbacks[ $offset ] );
}
```
wordpress WP_Hook::offsetSet( $offset, $value ) WP\_Hook::offsetSet( $offset, $value )
======================================
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function offsetSet( $offset, $value ) {
if ( is_null( $offset ) ) {
$this->callbacks[] = $value;
} else {
$this->callbacks[ $offset ] = $value;
}
}
```
wordpress WP_Hook::current() WP\_Hook::current()
===================
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function current() {
return current( $this->callbacks );
}
```
wordpress WP_Hook::do_action( array $args ) WP\_Hook::do\_action( array $args )
===================================
Calls the callback functions that have been added to an action hook.
`$args` array Required Parameters to pass to the callback functions. File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function do_action( $args ) {
$this->doing_action = true;
$this->apply_filters( '', $args );
// If there are recursive calls to the current action, we haven't finished it until we get to the last one.
if ( ! $this->nesting_level ) {
$this->doing_action = false;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Hook::apply\_filters()](apply_filters) wp-includes/class-wp-hook.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Hook::remove_filter( string $hook_name, callable|string|array $callback, int $priority ): bool WP\_Hook::remove\_filter( string $hook\_name, callable|string|array $callback, int $priority ): bool
====================================================================================================
Removes a callback function from a filter hook.
`$hook_name` string Required The filter hook to which the function to be removed is hooked. `$callback` callable|string|array Required The callback to be removed from running when the filter is applied.
This method can be called unconditionally to speculatively remove a callback that may or may not exist. `$priority` int Required The exact priority used when adding the original filter callback. bool Whether the callback existed before it was removed.
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function remove_filter( $hook_name, $callback, $priority ) {
$function_key = _wp_filter_build_unique_id( $hook_name, $callback, $priority );
$exists = isset( $this->callbacks[ $priority ][ $function_key ] );
if ( $exists ) {
unset( $this->callbacks[ $priority ][ $function_key ] );
if ( ! $this->callbacks[ $priority ] ) {
unset( $this->callbacks[ $priority ] );
if ( $this->nesting_level > 0 ) {
$this->resort_active_iterations();
}
}
}
return $exists;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Hook::resort\_active\_iterations()](resort_active_iterations) wp-includes/class-wp-hook.php | Handles resetting callback priority keys mid-iteration. |
| [\_wp\_filter\_build\_unique\_id()](../../functions/_wp_filter_build_unique_id) wp-includes/plugin.php | Builds Unique ID for storage and retrieval. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Hook::valid() WP\_Hook::valid()
=================
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function valid() {
return key( $this->callbacks ) !== null;
}
```
wordpress WP_Hook::resort_active_iterations( false|int $new_priority = false, bool $priority_existed = false ) WP\_Hook::resort\_active\_iterations( false|int $new\_priority = false, bool $priority\_existed = 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.
Handles resetting callback priority keys mid-iteration.
`$new_priority` false|int Optional The priority of the new filter being added. Default false, for no priority being added. Default: `false`
`$priority_existed` bool Optional Flag for whether the priority already existed before the new filter was added. Default: `false`
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
private function resort_active_iterations( $new_priority = false, $priority_existed = false ) {
$new_priorities = array_keys( $this->callbacks );
// If there are no remaining hooks, clear out all running iterations.
if ( ! $new_priorities ) {
foreach ( $this->iterations as $index => $iteration ) {
$this->iterations[ $index ] = $new_priorities;
}
return;
}
$min = min( $new_priorities );
foreach ( $this->iterations as $index => &$iteration ) {
$current = current( $iteration );
// If we're already at the end of this iteration, just leave the array pointer where it is.
if ( false === $current ) {
continue;
}
$iteration = $new_priorities;
if ( $current < $min ) {
array_unshift( $iteration, $current );
continue;
}
while ( current( $iteration ) < $current ) {
if ( false === next( $iteration ) ) {
break;
}
}
// If we have a new priority that didn't exist, but ::apply_filters() or ::do_action() thinks it's the current priority...
if ( $new_priority === $this->current_priority[ $index ] && ! $priority_existed ) {
/*
* ...and the new priority is the same as what $this->iterations thinks is the previous
* priority, we need to move back to it.
*/
if ( false === current( $iteration ) ) {
// If we've already moved off the end of the array, go back to the last element.
$prev = end( $iteration );
} else {
// Otherwise, just go back to the previous element.
$prev = prev( $iteration );
}
if ( false === $prev ) {
// Start of the array. Reset, and go about our day.
reset( $iteration );
} elseif ( $new_priority !== $prev ) {
// Previous wasn't the same. Move forward again.
next( $iteration );
}
}
}
unset( $iteration );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Hook::remove\_all\_filters()](remove_all_filters) wp-includes/class-wp-hook.php | Removes all callbacks from the current filter. |
| [WP\_Hook::add\_filter()](add_filter) wp-includes/class-wp-hook.php | Adds a callback function to a filter hook. |
| [WP\_Hook::remove\_filter()](remove_filter) wp-includes/class-wp-hook.php | Removes a callback function from a filter hook. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Hook::next() WP\_Hook::next()
================
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function next() {
return next( $this->callbacks );
}
```
wordpress WP_Hook::do_all_hook( array $args ) WP\_Hook::do\_all\_hook( array $args )
======================================
Processes the functions hooked into the ‘all’ hook.
`$args` array Required Arguments to pass to the hook callbacks. Passed by reference. File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function do_all_hook( &$args ) {
$nesting_level = $this->nesting_level++;
$this->iterations[ $nesting_level ] = array_keys( $this->callbacks );
do {
$priority = current( $this->iterations[ $nesting_level ] );
foreach ( $this->callbacks[ $priority ] as $the_ ) {
call_user_func_array( $the_['function'], $args );
}
} while ( false !== next( $this->iterations[ $nesting_level ] ) );
unset( $this->iterations[ $nesting_level ] );
$this->nesting_level--;
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Hook::has_filters(): bool WP\_Hook::has\_filters(): bool
==============================
Checks if any callbacks have been registered for this hook.
bool True if callbacks have been registered for the current hook, otherwise false.
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function has_filters() {
foreach ( $this->callbacks as $callbacks ) {
if ( $callbacks ) {
return true;
}
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Hook::has\_filter()](has_filter) wp-includes/class-wp-hook.php | Checks if a specific callback has been registered for this hook. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Hook::offsetExists( $offset ) WP\_Hook::offsetExists( $offset )
=================================
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function offsetExists( $offset ) {
return isset( $this->callbacks[ $offset ] );
}
```
wordpress WP_Hook::remove_all_filters( int|false $priority = false ) WP\_Hook::remove\_all\_filters( int|false $priority = false )
=============================================================
Removes all callbacks from the current filter.
`$priority` int|false Optional The priority number to remove. Default: `false`
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function remove_all_filters( $priority = false ) {
if ( ! $this->callbacks ) {
return;
}
if ( false === $priority ) {
$this->callbacks = array();
} elseif ( isset( $this->callbacks[ $priority ] ) ) {
unset( $this->callbacks[ $priority ] );
}
if ( $this->nesting_level > 0 ) {
$this->resort_active_iterations();
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Hook::resort\_active\_iterations()](resort_active_iterations) wp-includes/class-wp-hook.php | Handles resetting callback priority keys mid-iteration. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Hook::key() WP\_Hook::key()
===============
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function key() {
return key( $this->callbacks );
}
```
wordpress WP_Hook::add_filter( string $hook_name, callable $callback, int $priority, int $accepted_args ) WP\_Hook::add\_filter( string $hook\_name, callable $callback, int $priority, int $accepted\_args )
===================================================================================================
Adds a callback function to a filter hook.
`$hook_name` string Required The name of the filter to add the callback to. `$callback` callable Required The callback to be run when the filter is applied. `$priority` int Required The order in which the functions associated with a particular filter are executed. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the filter. `$accepted_args` int Required The number of arguments the function accepts. File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function add_filter( $hook_name, $callback, $priority, $accepted_args ) {
$idx = _wp_filter_build_unique_id( $hook_name, $callback, $priority );
$priority_existed = isset( $this->callbacks[ $priority ] );
$this->callbacks[ $priority ][ $idx ] = array(
'function' => $callback,
'accepted_args' => $accepted_args,
);
// If we're adding a new priority to the list, put them back in sorted order.
if ( ! $priority_existed && count( $this->callbacks ) > 1 ) {
ksort( $this->callbacks, SORT_NUMERIC );
}
if ( $this->nesting_level > 0 ) {
$this->resort_active_iterations( $priority, $priority_existed );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Hook::resort\_active\_iterations()](resort_active_iterations) wp-includes/class-wp-hook.php | Handles resetting callback priority keys mid-iteration. |
| [\_wp\_filter\_build\_unique\_id()](../../functions/_wp_filter_build_unique_id) wp-includes/plugin.php | Builds Unique ID for storage and retrieval. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Hook::has_filter( string $hook_name = '', callable|string|array|false $callback = false ): bool|int WP\_Hook::has\_filter( string $hook\_name = '', callable|string|array|false $callback = false ): bool|int
=========================================================================================================
Checks if a specific callback has been registered for this hook.
When using the `$callback` argument, this function may return a non-boolean value that evaluates to false (e.g. 0), so use the `===` operator for testing the return value.
`$hook_name` string Optional The name of the filter hook. Default: `''`
`$callback` callable|string|array|false Optional The callback to check for.
This method can be called unconditionally to speculatively check a callback that may or may not exist. Default: `false`
bool|int If `$callback` is omitted, returns boolean for whether the hook has anything registered. When checking a specific function, the priority of that hook is returned, or false if the function is not attached.
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function has_filter( $hook_name = '', $callback = false ) {
if ( false === $callback ) {
return $this->has_filters();
}
$function_key = _wp_filter_build_unique_id( $hook_name, $callback, false );
if ( ! $function_key ) {
return false;
}
foreach ( $this->callbacks as $priority => $callbacks ) {
if ( isset( $callbacks[ $function_key ] ) ) {
return $priority;
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Hook::has\_filters()](has_filters) wp-includes/class-wp-hook.php | Checks if any callbacks have been registered for this hook. |
| [\_wp\_filter\_build\_unique\_id()](../../functions/_wp_filter_build_unique_id) wp-includes/plugin.php | Builds Unique ID for storage and retrieval. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Hook::rewind() WP\_Hook::rewind()
==================
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function rewind() {
reset( $this->callbacks );
}
```
wordpress WP_Hook::current_priority(): int|false WP\_Hook::current\_priority(): int|false
========================================
Return the current priority level of the currently running iteration of the hook.
int|false If the hook is running, return the current priority level.
If it isn't running, return false.
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public function current_priority() {
if ( false === current( $this->iterations ) ) {
return false;
}
return current( current( $this->iterations ) );
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Hook::build_preinitialized_hooks( array $filters ): WP_Hook[] WP\_Hook::build\_preinitialized\_hooks( array $filters ): WP\_Hook[]
====================================================================
Normalizes filters set up before WordPress has initialized to [WP\_Hook](../wp_hook) objects.
The `$filters` parameter should be an array keyed by hook name, with values containing either:
* A `WP_Hook` instance
* An array of callbacks keyed by their priorities
Examples:
```
$filters = array(
'wp_fatal_error_handler_enabled' => array(
10 => array(
array(
'accepted_args' => 0,
'function' => function() {
return false;
},
),
),
),
);
```
`$filters` array Required Filters to normalize. See documentation above for details. [WP\_Hook](../wp_hook)[] Array of normalized filters.
File: `wp-includes/class-wp-hook.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-hook.php/)
```
public static function build_preinitialized_hooks( $filters ) {
/** @var WP_Hook[] $normalized */
$normalized = array();
foreach ( $filters as $hook_name => $callback_groups ) {
if ( is_object( $callback_groups ) && $callback_groups instanceof WP_Hook ) {
$normalized[ $hook_name ] = $callback_groups;
continue;
}
$hook = new WP_Hook();
// Loop through callback groups.
foreach ( $callback_groups as $priority => $callbacks ) {
// Loop through callbacks.
foreach ( $callbacks as $cb ) {
$hook->add_filter( $hook_name, $cb['function'], $priority, $cb['accepted_args'] );
}
}
$normalized[ $hook_name ] = $hook;
}
return $normalized;
}
```
| Used By | Description |
| --- | --- |
| [wp\_start\_object\_cache()](../../functions/wp_start_object_cache) wp-includes/load.php | Start the WordPress object cache. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Feed_Cache::create( string $location, string $filename, string $extension ): WP_Feed_Cache_Transient WP\_Feed\_Cache::create( string $location, string $filename, string $extension ): WP\_Feed\_Cache\_Transient
============================================================================================================
Creates a new SimplePie\_Cache object.
`$location` string Required URL location (scheme is used to determine handler). `$filename` string Required Unique identifier for cache object. `$extension` string Required `'spi'` or `'spc'`. [WP\_Feed\_Cache\_Transient](../wp_feed_cache_transient) Feed cache handler object that uses transients.
File: `wp-includes/class-wp-feed-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-feed-cache.php/)
```
public function create( $location, $filename, $extension ) {
return new WP_Feed_Cache_Transient( $location, $filename, $extension );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Feed\_Cache\_Transient::\_\_construct()](../wp_feed_cache_transient/__construct) wp-includes/class-wp-feed-cache-transient.php | Constructor. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_List_Util::sort( string|array $orderby = array(), string $order = 'ASC', bool $preserve_keys = false ): array WP\_List\_Util::sort( string|array $orderby = array(), string $order = 'ASC', bool $preserve\_keys = false ): array
===================================================================================================================
Sorts the input array based on one or more orderby arguments.
`$orderby` string|array Optional Either the field name to order by or an array of multiple orderby fields as $orderby => $order. Default: `array()`
`$order` string Optional Either `'ASC'` or `'DESC'`. Only used if $orderby is a string. Default: `'ASC'`
`$preserve_keys` bool Optional Whether to preserve keys. Default: `false`
array The sorted array.
File: `wp-includes/class-wp-list-util.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-list-util.php/)
```
public function sort( $orderby = array(), $order = 'ASC', $preserve_keys = false ) {
if ( empty( $orderby ) ) {
return $this->output;
}
if ( is_string( $orderby ) ) {
$orderby = array( $orderby => $order );
}
foreach ( $orderby as $field => $direction ) {
$orderby[ $field ] = 'DESC' === strtoupper( $direction ) ? 'DESC' : 'ASC';
}
$this->orderby = $orderby;
if ( $preserve_keys ) {
uasort( $this->output, array( $this, 'sort_callback' ) );
} else {
usort( $this->output, array( $this, 'sort_callback' ) );
}
$this->orderby = array();
return $this->output;
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_List_Util::get_input(): array WP\_List\_Util::get\_input(): array
===================================
Returns the original input array.
array The input array.
File: `wp-includes/class-wp-list-util.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-list-util.php/)
```
public function get_input() {
return $this->input;
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_List_Util::get_output(): array WP\_List\_Util::get\_output(): array
====================================
Returns the output array.
array The output array.
File: `wp-includes/class-wp-list-util.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-list-util.php/)
```
public function get_output() {
return $this->output;
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_List_Util::sort_callback( object|array $a, object|array $b ): int WP\_List\_Util::sort\_callback( object|array $a, object|array $b ): 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. Use [WP\_List\_Util::sort()](../wp_list_util/sort) instead.
Callback to sort an array by specific fields.
* [WP\_List\_Util::sort()](../wp_list_util/sort)
`$a` object|array Required One object to compare. `$b` object|array Required The other object to compare. int 0 if both objects equal. -1 if second object should come first, 1 otherwise.
File: `wp-includes/class-wp-list-util.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-list-util.php/)
```
private function sort_callback( $a, $b ) {
if ( empty( $this->orderby ) ) {
return 0;
}
$a = (array) $a;
$b = (array) $b;
foreach ( $this->orderby as $field => $direction ) {
if ( ! isset( $a[ $field ] ) || ! isset( $b[ $field ] ) ) {
continue;
}
if ( $a[ $field ] == $b[ $field ] ) {
continue;
}
$results = 'DESC' === $direction ? array( 1, -1 ) : array( -1, 1 );
if ( is_numeric( $a[ $field ] ) && is_numeric( $b[ $field ] ) ) {
return ( $a[ $field ] < $b[ $field ] ) ? $results[0] : $results[1];
}
return 0 > strcmp( $a[ $field ], $b[ $field ] ) ? $results[0] : $results[1];
}
return 0;
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_List_Util::pluck( int|string $field, int|string $index_key = null ): array WP\_List\_Util::pluck( int|string $field, int|string $index\_key = null ): array
================================================================================
Plucks a certain field out of each element in the input array.
This has the same functionality and prototype of array\_column() (PHP 5.5) but also supports objects.
`$field` int|string Required Field to fetch from the object or array. `$index_key` int|string Optional Field from the element to use as keys for the new array.
Default: `null`
array Array of found values. If `$index_key` is set, an array of found values with keys corresponding to `$index_key`. If `$index_key` is null, array keys from the original `$list` will be preserved in the results.
File: `wp-includes/class-wp-list-util.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-list-util.php/)
```
public function pluck( $field, $index_key = null ) {
$newlist = array();
if ( ! $index_key ) {
/*
* This is simple. Could at some point wrap array_column()
* if we knew we had an array of arrays.
*/
foreach ( $this->output as $key => $value ) {
if ( is_object( $value ) ) {
$newlist[ $key ] = $value->$field;
} else {
$newlist[ $key ] = $value[ $field ];
}
}
$this->output = $newlist;
return $this->output;
}
/*
* When index_key is not set for a particular item, push the value
* to the end of the stack. This is how array_column() behaves.
*/
foreach ( $this->output as $value ) {
if ( is_object( $value ) ) {
if ( isset( $value->$index_key ) ) {
$newlist[ $value->$index_key ] = $value->$field;
} else {
$newlist[] = $value->$field;
}
} else {
if ( isset( $value[ $index_key ] ) ) {
$newlist[ $value[ $index_key ] ] = $value[ $field ];
} else {
$newlist[] = $value[ $field ];
}
}
}
$this->output = $newlist;
return $this->output;
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_List_Util::__construct( array $input ) WP\_List\_Util::\_\_construct( array $input )
=============================================
Constructor.
Sets the input array.
`$input` array Required Array to perform operations on. File: `wp-includes/class-wp-list-util.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-list-util.php/)
```
public function __construct( $input ) {
$this->output = $input;
$this->input = $input;
}
```
| Used By | Description |
| --- | --- |
| [wp\_list\_sort()](../../functions/wp_list_sort) wp-includes/functions.php | Sorts an array of objects or arrays based on one or more orderby arguments. |
| [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. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_List_Util::filter( array $args = array(), string $operator = 'AND' ): array WP\_List\_Util::filter( array $args = array(), string $operator = 'AND' ): array
================================================================================
Filters the list, based on a set of key => value arguments.
Retrieves the objects from the list that match the given arguments.
Key represents property name, and value represents property value.
If an object has more properties than those specified in arguments, that will not disqualify it. When using the ‘AND’ operator, any missing properties will disqualify it.
`$args` array Optional An array of key => value arguments to match against each object. Default: `array()`
`$operator` string Optional The logical operation to perform. `'AND'` means all elements from the array must match. `'OR'` means only one element needs to match. `'NOT'` means no elements may match. Default `'AND'`. Default: `'AND'`
array Array of found values.
File: `wp-includes/class-wp-list-util.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-list-util.php/)
```
public function filter( $args = array(), $operator = 'AND' ) {
if ( empty( $args ) ) {
return $this->output;
}
$operator = strtoupper( $operator );
if ( ! in_array( $operator, array( 'AND', 'OR', 'NOT' ), true ) ) {
$this->output = array();
return $this->output;
}
$count = count( $args );
$filtered = array();
foreach ( $this->output as $key => $obj ) {
$matched = 0;
foreach ( $args as $m_key => $m_value ) {
if ( is_array( $obj ) ) {
// Treat object as an array.
if ( array_key_exists( $m_key, $obj ) && ( $m_value == $obj[ $m_key ] ) ) {
$matched++;
}
} elseif ( is_object( $obj ) ) {
// Treat object as an object.
if ( isset( $obj->{$m_key} ) && ( $m_value == $obj->{$m_key} ) ) {
$matched++;
}
}
}
if ( ( 'AND' === $operator && $matched === $count )
|| ( 'OR' === $operator && $matched > 0 )
|| ( 'NOT' === $operator && 0 === $matched )
) {
$filtered[ $key ] = $obj;
}
}
$this->output = $filtered;
return $this->output;
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Http_Encoding::compatible_gzinflate( string $gz_data ): string|false WP\_Http\_Encoding::compatible\_gzinflate( string $gz\_data ): string|false
===========================================================================
Decompression of deflated string while staying compatible with the majority of servers.
Certain Servers will return deflated data with headers which PHP’s gzinflate() function cannot handle out of the box. The following function has been created from various snippets on the gzinflate() PHP documentation.
Warning: Magic numbers within. Due to the potential different formats that the compressed data may be returned in, some "magic offsets" are needed to ensure proper decompression takes place. For a simple pragmatic way to determine the magic offset in use, see: <https://core.trac.wordpress.org/ticket/18273>
`$gz_data` string Required String to decompress. string|false Decompressed string on success, false on failure.
File: `wp-includes/class-wp-http-encoding.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-encoding.php/)
```
public static function compatible_gzinflate( $gz_data ) {
// Compressed data might contain a full header, if so strip it for gzinflate().
if ( "\x1f\x8b\x08" === substr( $gz_data, 0, 3 ) ) {
$i = 10;
$flg = ord( substr( $gz_data, 3, 1 ) );
if ( $flg > 0 ) {
if ( $flg & 4 ) {
list($xlen) = unpack( 'v', substr( $gz_data, $i, 2 ) );
$i = $i + 2 + $xlen;
}
if ( $flg & 8 ) {
$i = strpos( $gz_data, "\0", $i ) + 1;
}
if ( $flg & 16 ) {
$i = strpos( $gz_data, "\0", $i ) + 1;
}
if ( $flg & 2 ) {
$i = $i + 2;
}
}
$decompressed = @gzinflate( substr( $gz_data, $i, -8 ) );
if ( false !== $decompressed ) {
return $decompressed;
}
}
// Compressed data from java.util.zip.Deflater amongst others.
$decompressed = @gzinflate( substr( $gz_data, 2 ) );
if ( false !== $decompressed ) {
return $decompressed;
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Http\_Encoding::decompress()](decompress) wp-includes/class-wp-http-encoding.php | Decompression of deflated string. |
| Version | Description |
| --- | --- |
| [2.8.1](https://developer.wordpress.org/reference/since/2.8.1/) | Introduced. |
wordpress WP_Http_Encoding::content_encoding(): string WP\_Http\_Encoding::content\_encoding(): string
===============================================
What encoding the content used when it was compressed to send in the headers.
string Content-Encoding string to send in the header.
File: `wp-includes/class-wp-http-encoding.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-encoding.php/)
```
public static function content_encoding() {
return 'deflate';
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Http_Encoding::decompress( string $compressed, int $length = null ): string|false WP\_Http\_Encoding::decompress( string $compressed, int $length = null ): string|false
======================================================================================
Decompression of deflated string.
Will attempt to decompress using the RFC 1950 standard, and if that fails then the RFC 1951 standard deflate will be attempted. Finally, the RFC 1952 standard gzip decode will be attempted. If all fail, then the original compressed string will be returned.
`$compressed` string Required String to decompress. `$length` int Optional The optional length of the compressed data. Default: `null`
string|false Decompressed string on success, false on failure.
File: `wp-includes/class-wp-http-encoding.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-encoding.php/)
```
public static function decompress( $compressed, $length = null ) {
if ( empty( $compressed ) ) {
return $compressed;
}
$decompressed = @gzinflate( $compressed );
if ( false !== $decompressed ) {
return $decompressed;
}
$decompressed = self::compatible_gzinflate( $compressed );
if ( false !== $decompressed ) {
return $decompressed;
}
$decompressed = @gzuncompress( $compressed );
if ( false !== $decompressed ) {
return $decompressed;
}
if ( function_exists( 'gzdecode' ) ) {
$decompressed = @gzdecode( $compressed );
if ( false !== $decompressed ) {
return $decompressed;
}
}
return $compressed;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Http\_Encoding::compatible\_gzinflate()](compatible_gzinflate) wp-includes/class-wp-http-encoding.php | Decompression of deflated string while staying compatible with the majority of servers. |
| 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_Encoding::accept_encoding( string $url, array $args ): string WP\_Http\_Encoding::accept\_encoding( string $url, array $args ): string
========================================================================
What encoding types to accept and their priority values.
`$url` string Required `$args` array Required string Types of encoding to accept.
File: `wp-includes/class-wp-http-encoding.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-encoding.php/)
```
public static function accept_encoding( $url, $args ) {
$type = array();
$compression_enabled = self::is_available();
if ( ! $args['decompress'] ) { // Decompression specifically disabled.
$compression_enabled = false;
} elseif ( $args['stream'] ) { // Disable when streaming to file.
$compression_enabled = false;
} elseif ( isset( $args['limit_response_size'] ) ) { // If only partial content is being requested, we won't be able to decompress it.
$compression_enabled = false;
}
if ( $compression_enabled ) {
if ( function_exists( 'gzinflate' ) ) {
$type[] = 'deflate;q=1.0';
}
if ( function_exists( 'gzuncompress' ) ) {
$type[] = 'compress;q=0.5';
}
if ( function_exists( 'gzdecode' ) ) {
$type[] = 'gzip;q=0.5';
}
}
/**
* Filters the allowed encoding types.
*
* @since 3.6.0
*
* @param string[] $type Array of what encoding types to accept and their priority values.
* @param string $url URL of the HTTP request.
* @param array $args HTTP request arguments.
*/
$type = apply_filters( 'wp_http_accept_encoding', $type, $url, $args );
return implode( ', ', $type );
}
```
[apply\_filters( 'wp\_http\_accept\_encoding', string[] $type, string $url, array $args )](../../hooks/wp_http_accept_encoding)
Filters the allowed encoding types.
| Uses | Description |
| --- | --- |
| [WP\_Http\_Encoding::is\_available()](is_available) wp-includes/class-wp-http-encoding.php | Whether decompression and compression are supported by the PHP version. |
| [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. |
| programming_docs |
wordpress WP_Http_Encoding::compress( string $raw, int $level = 9, string $supports = null ): string|false WP\_Http\_Encoding::compress( string $raw, int $level = 9, string $supports = null ): string|false
==================================================================================================
Compress raw string using the deflate format.
Supports the RFC 1951 standard.
`$raw` string Required String to compress. `$level` int Optional Compression level, 9 is highest. Default: `9`
`$supports` string Optional not used. When implemented it will choose the right compression based on what the server supports. Default: `null`
string|false Compressed string on success, false on failure.
File: `wp-includes/class-wp-http-encoding.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-encoding.php/)
```
public static function compress( $raw, $level = 9, $supports = null ) {
return gzdeflate( $raw, $level );
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Http_Encoding::should_decode( array|string $headers ): bool WP\_Http\_Encoding::should\_decode( array|string $headers ): bool
=================================================================
Whether the content be decoded based on the headers.
`$headers` array|string Required All of the available headers. bool
File: `wp-includes/class-wp-http-encoding.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-encoding.php/)
```
public static function should_decode( $headers ) {
if ( is_array( $headers ) ) {
if ( array_key_exists( 'content-encoding', $headers ) && ! empty( $headers['content-encoding'] ) ) {
return true;
}
} elseif ( is_string( $headers ) ) {
return ( stripos( $headers, 'content-encoding:' ) !== false );
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [stripos()](../../functions/stripos) wp-includes/class-pop3.php | |
| 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_Encoding::is_available(): bool WP\_Http\_Encoding::is\_available(): bool
=========================================
Whether decompression and compression are supported by the PHP version.
Each function is tested instead of checking for the zlib extension, to ensure that the functions all exist in the PHP version and aren’t disabled.
bool
File: `wp-includes/class-wp-http-encoding.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-encoding.php/)
```
public static function is_available() {
return ( function_exists( 'gzuncompress' ) || function_exists( 'gzdeflate' ) || function_exists( 'gzinflate' ) );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Http\_Encoding::accept\_encoding()](accept_encoding) wp-includes/class-wp-http-encoding.php | What encoding types to accept and their priority values. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader::unpack_package( string $package, bool $delete_package = true ): string|WP_Error WP\_Upgrader::unpack\_package( string $package, bool $delete\_package = true ): string|WP\_Error
================================================================================================
Unpack a compressed package file.
`$package` string Required Full path to the package file. `$delete_package` bool Optional Whether to delete the package file after attempting to unpack it. Default: `true`
string|[WP\_Error](../wp_error) The path to the unpacked contents, or a [WP\_Error](../wp_error) on failure.
File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/)
```
public function unpack_package( $package, $delete_package = true ) {
global $wp_filesystem;
$this->skin->feedback( 'unpack_package' );
$upgrade_folder = $wp_filesystem->wp_content_dir() . 'upgrade/';
// Clean up contents of upgrade directory beforehand.
$upgrade_files = $wp_filesystem->dirlist( $upgrade_folder );
if ( ! empty( $upgrade_files ) ) {
foreach ( $upgrade_files as $file ) {
$wp_filesystem->delete( $upgrade_folder . $file['name'], true );
}
}
// We need a working directory - strip off any .tmp or .zip suffixes.
$working_dir = $upgrade_folder . basename( basename( $package, '.tmp' ), '.zip' );
// Clean up working directory.
if ( $wp_filesystem->is_dir( $working_dir ) ) {
$wp_filesystem->delete( $working_dir, true );
}
// Unzip package to working directory.
$result = unzip_file( $package, $working_dir );
// Once extracted, delete the package if required.
if ( $delete_package ) {
unlink( $package );
}
if ( is_wp_error( $result ) ) {
$wp_filesystem->delete( $working_dir, true );
if ( 'incompatible_archive' === $result->get_error_code() ) {
return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], $result->get_error_data() );
}
return $result;
}
return $working_dir;
}
```
| Uses | Description |
| --- | --- |
| [unzip\_file()](../../functions/unzip_file) wp-admin/includes/file.php | Unzips a specified ZIP file to a location on the filesystem via the WordPress Filesystem Abstraction. |
| [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\_Upgrader::run()](run) wp-admin/includes/class-wp-upgrader.php | Run an upgrade/installation. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader::create_lock( string $lock_name, int $release_timeout = null ): bool WP\_Upgrader::create\_lock( string $lock\_name, int $release\_timeout = null ): bool
====================================================================================
Creates a lock using WordPress options.
`$lock_name` string Required The name of this unique lock. `$release_timeout` int Optional The duration in seconds to respect an existing lock.
Default: 1 hour. Default: `null`
bool False if a lock couldn't be created or if the lock is still valid. True otherwise.
File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/)
```
public static function create_lock( $lock_name, $release_timeout = null ) {
global $wpdb;
if ( ! $release_timeout ) {
$release_timeout = HOUR_IN_SECONDS;
}
$lock_option = $lock_name . '.lock';
// Try to lock.
$lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_option, time() ) );
if ( ! $lock_result ) {
$lock_result = get_option( $lock_option );
// If a lock couldn't be created, and there isn't a lock, bail.
if ( ! $lock_result ) {
return false;
}
// Check to see if the lock is still valid. If it is, bail.
if ( $lock_result > ( time() - $release_timeout ) ) {
return false;
}
// There must exist an expired lock, clear it and re-gain it.
WP_Upgrader::release_lock( $lock_name );
return WP_Upgrader::create_lock( $lock_name, $release_timeout );
}
// Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
update_option( $lock_option, time() );
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Upgrader::release\_lock()](release_lock) wp-admin/includes/class-wp-upgrader.php | Releases an upgrader lock. |
| [WP\_Upgrader::create\_lock()](create_lock) wp-admin/includes/class-wp-upgrader.php | Creates a lock using WordPress options. |
| [wpdb::query()](../wpdb/query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| [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. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_Upgrader::create\_lock()](create_lock) wp-admin/includes/class-wp-upgrader.php | Creates a lock using WordPress options. |
| [WP\_Automatic\_Updater::run()](../wp_automatic_updater/run) wp-admin/includes/class-wp-automatic-updater.php | Kicks off the background update process, looping through all pending updates. |
| [Core\_Upgrader::upgrade()](../core_upgrader/upgrade) wp-admin/includes/class-core-upgrader.php | Upgrade WordPress core. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Upgrader::run( array $options ): array|false|WP_Error WP\_Upgrader::run( array $options ): array|false|WP\_Error
==========================================================
Run an upgrade/installation.
Attempts to download the package (if it is not a local file), unpack it, and install it in the destination folder.
`$options` array Required Array or string of arguments for upgrading/installing a package.
* `package`stringThe full path or URI of the package to install.
Default empty.
* `destination`stringThe full path to the destination folder.
Default empty.
* `clear_destination`boolWhether to delete any files already in the destination folder. Default false.
* `clear_working`boolWhether to delete the files from the working directory after copying them to the destination.
Default true.
* `abort_if_destination_exists`boolWhether to abort the installation if the destination folder already exists. When true, `$clear_destination` should be false. Default true.
* `is_multi`boolWhether this run is one of multiple upgrade/installation actions being performed in bulk. When true, the skin WP\_Upgrader::header() and WP\_Upgrader::footer() aren't called. Default false.
* `hook_extra`arrayExtra arguments to pass to the filter hooks called by [WP\_Upgrader::run()](run).
More Arguments from WP\_Upgrader::run( ... $options ) Array or string of arguments for upgrading/installing a package.
* `package`stringThe full path or URI of the package to install.
Default empty.
* `destination`stringThe full path to the destination folder.
Default empty.
* `clear_destination`boolWhether to delete any files already in the destination folder. Default false.
* `clear_working`boolWhether to delete the files from the working directory after copying them to the destination.
Default true.
* `abort_if_destination_exists`boolWhether to abort the installation if the destination folder already exists. When true, `$clear_destination` should be false. Default true.
* `is_multi`boolWhether this run is one of multiple upgrade/installation actions being performed in bulk. When true, the skin WP\_Upgrader::header() and WP\_Upgrader::footer() aren't called. Default false.
* `hook_extra`arrayExtra arguments to pass to the filter hooks called by [WP\_Upgrader::run()](run).
array|false|[WP\_Error](../wp_error) The result from self::install\_package() on success, otherwise a [WP\_Error](../wp_error), or false if unable to connect to the filesystem.
File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/)
```
public function run( $options ) {
$defaults = array(
'package' => '', // Please always pass this.
'destination' => '', // ...and this.
'clear_destination' => false,
'clear_working' => true,
'abort_if_destination_exists' => true, // Abort if the destination directory exists. Pass clear_destination as false please.
'is_multi' => false,
'hook_extra' => array(), // Pass any extra $hook_extra args here, this will be passed to any hooked filters.
);
$options = wp_parse_args( $options, $defaults );
/**
* Filters the package options before running an update.
*
* See also {@see 'upgrader_process_complete'}.
*
* @since 4.3.0
*
* @param array $options {
* Options used by the upgrader.
*
* @type string $package Package for update.
* @type string $destination Update location.
* @type bool $clear_destination Clear the destination resource.
* @type bool $clear_working Clear the working resource.
* @type bool $abort_if_destination_exists Abort if the Destination directory exists.
* @type bool $is_multi Whether the upgrader is running multiple times.
* @type array $hook_extra {
* Extra hook arguments.
*
* @type string $action Type of action. Default 'update'.
* @type string $type Type of update process. Accepts 'plugin', 'theme', or 'core'.
* @type bool $bulk Whether the update process is a bulk update. Default true.
* @type string $plugin Path to the plugin file relative to the plugins directory.
* @type string $theme The stylesheet or template name of the theme.
* @type string $language_update_type The language pack update type. Accepts 'plugin', 'theme',
* or 'core'.
* @type object $language_update The language pack update offer.
* }
* }
*/
$options = apply_filters( 'upgrader_package_options', $options );
if ( ! $options['is_multi'] ) { // Call $this->header separately if running multiple times.
$this->skin->header();
}
// Connect to the filesystem first.
$res = $this->fs_connect( array( WP_CONTENT_DIR, $options['destination'] ) );
// Mainly for non-connected filesystem.
if ( ! $res ) {
if ( ! $options['is_multi'] ) {
$this->skin->footer();
}
return false;
}
$this->skin->before();
if ( is_wp_error( $res ) ) {
$this->skin->error( $res );
$this->skin->after();
if ( ! $options['is_multi'] ) {
$this->skin->footer();
}
return $res;
}
/*
* Download the package. Note: If the package is the full path
* to an existing local file, it will be returned untouched.
*/
$download = $this->download_package( $options['package'], true, $options['hook_extra'] );
// Allow for signature soft-fail.
// WARNING: This may be removed in the future.
if ( is_wp_error( $download ) && $download->get_error_data( 'softfail-filename' ) ) {
// Don't output the 'no signature could be found' failure message for now.
if ( 'signature_verification_no_signature' !== $download->get_error_code() || WP_DEBUG ) {
// Output the failure error as a normal feedback, and not as an error.
$this->skin->feedback( $download->get_error_message() );
// Report this failure back to WordPress.org for debugging purposes.
wp_version_check(
array(
'signature_failure_code' => $download->get_error_code(),
'signature_failure_data' => $download->get_error_data(),
)
);
}
// Pretend this error didn't happen.
$download = $download->get_error_data( 'softfail-filename' );
}
if ( is_wp_error( $download ) ) {
$this->skin->error( $download );
$this->skin->after();
if ( ! $options['is_multi'] ) {
$this->skin->footer();
}
return $download;
}
$delete_package = ( $download !== $options['package'] ); // Do not delete a "local" file.
// Unzips the file into a temporary directory.
$working_dir = $this->unpack_package( $download, $delete_package );
if ( is_wp_error( $working_dir ) ) {
$this->skin->error( $working_dir );
$this->skin->after();
if ( ! $options['is_multi'] ) {
$this->skin->footer();
}
return $working_dir;
}
// With the given options, this installs it to the destination directory.
$result = $this->install_package(
array(
'source' => $working_dir,
'destination' => $options['destination'],
'clear_destination' => $options['clear_destination'],
'abort_if_destination_exists' => $options['abort_if_destination_exists'],
'clear_working' => $options['clear_working'],
'hook_extra' => $options['hook_extra'],
)
);
/**
* Filters the result of WP_Upgrader::install_package().
*
* @since 5.7.0
*
* @param array|WP_Error $result Result from WP_Upgrader::install_package().
* @param array $hook_extra Extra arguments passed to hooked filters.
*/
$result = apply_filters( 'upgrader_install_package_result', $result, $options['hook_extra'] );
$this->skin->set_result( $result );
if ( is_wp_error( $result ) ) {
$this->skin->error( $result );
if ( ! method_exists( $this->skin, 'hide_process_failed' ) || ! $this->skin->hide_process_failed( $result ) ) {
$this->skin->feedback( 'process_failed' );
}
} else {
// Installation succeeded.
$this->skin->feedback( 'process_success' );
}
$this->skin->after();
if ( ! $options['is_multi'] ) {
/**
* Fires when the upgrader process is complete.
*
* See also {@see 'upgrader_package_options'}.
*
* @since 3.6.0
* @since 3.7.0 Added to WP_Upgrader::run().
* @since 4.6.0 `$translations` was added as a possible argument to `$hook_extra`.
*
* @param WP_Upgrader $upgrader WP_Upgrader instance. In other contexts this might be a
* Theme_Upgrader, Plugin_Upgrader, Core_Upgrade, or Language_Pack_Upgrader instance.
* @param array $hook_extra {
* Array of bulk item update data.
*
* @type string $action Type of action. Default 'update'.
* @type string $type Type of update process. Accepts 'plugin', 'theme', 'translation', or 'core'.
* @type bool $bulk Whether the update process is a bulk update. Default true.
* @type array $plugins Array of the basename paths of the plugins' main files.
* @type array $themes The theme slugs.
* @type array $translations {
* Array of translations update data.
*
* @type string $language The locale the translation is for.
* @type string $type Type of translation. Accepts 'plugin', 'theme', or 'core'.
* @type string $slug Text domain the translation is for. The slug of a theme/plugin or
* 'default' for core translations.
* @type string $version The version of a theme, plugin, or core.
* }
* }
*/
do_action( 'upgrader_process_complete', $this, $options['hook_extra'] );
$this->skin->footer();
}
return $result;
}
```
[apply\_filters( 'upgrader\_install\_package\_result', array|WP\_Error $result, array $hook\_extra )](../../hooks/upgrader_install_package_result)
Filters the result of [WP\_Upgrader::install\_package()](install_package).
[apply\_filters( 'upgrader\_package\_options', array $options )](../../hooks/upgrader_package_options)
Filters the package options before running an update.
[do\_action( 'upgrader\_process\_complete', WP\_Upgrader $upgrader, array $hook\_extra )](../../hooks/upgrader_process_complete)
Fires when the upgrader process is complete.
| Uses | Description |
| --- | --- |
| [WP\_Upgrader::fs\_connect()](fs_connect) wp-admin/includes/class-wp-upgrader.php | Connect to the filesystem. |
| [WP\_Upgrader::download\_package()](download_package) wp-admin/includes/class-wp-upgrader.php | Download a package. |
| [WP\_Upgrader::unpack\_package()](unpack_package) wp-admin/includes/class-wp-upgrader.php | Unpack a compressed package file. |
| [WP\_Upgrader::install\_package()](install_package) wp-admin/includes/class-wp-upgrader.php | Install a package. |
| [wp\_version\_check()](../../functions/wp_version_check) wp-includes/update.php | Checks WordPress version against the newest version. |
| [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. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Upgrader::init() WP\_Upgrader::init()
====================
Initialize the upgrader.
This will set the relationship between the skin being used and this upgrader, and also add the generic strings to `WP_Upgrader::$strings`.
File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/)
```
public function init() {
$this->skin->set_upgrader( $this );
$this->generic_strings();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Upgrader::generic\_strings()](generic_strings) wp-admin/includes/class-wp-upgrader.php | Add the generic strings to WP\_Upgrader::$strings. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader::flatten_dirlist( array $nested_files, string $path = '' ): array WP\_Upgrader::flatten\_dirlist( array $nested\_files, string $path = '' ): array
================================================================================
Flatten the results of [WP\_Filesystem\_Base::dirlist()](../wp_filesystem_base/dirlist) for iterating over.
`$nested_files` array Required Array of files as returned by [WP\_Filesystem\_Base::dirlist()](../wp_filesystem_base/dirlist). `$path` string Optional Relative path to prepend to child nodes. Optional. Default: `''`
array A flattened array of the $nested\_files specified.
File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/)
```
protected function flatten_dirlist( $nested_files, $path = '' ) {
$files = array();
foreach ( $nested_files as $name => $details ) {
$files[ $path . $name ] = $details;
// Append children recursively.
if ( ! empty( $details['files'] ) ) {
$children = $this->flatten_dirlist( $details['files'], $path . $name . '/' );
// Merge keeping possible numeric keys, which array_merge() will reindex from 0..n.
$files = $files + $children;
}
}
return $files;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Upgrader::flatten\_dirlist()](flatten_dirlist) wp-admin/includes/class-wp-upgrader.php | Flatten the results of [WP\_Filesystem\_Base::dirlist()](../wp_filesystem_base/dirlist) for iterating over. |
| Used By | Description |
| --- | --- |
| [WP\_Upgrader::flatten\_dirlist()](flatten_dirlist) wp-admin/includes/class-wp-upgrader.php | Flatten the results of [WP\_Filesystem\_Base::dirlist()](../wp_filesystem_base/dirlist) for iterating over. |
| [WP\_Upgrader::clear\_destination()](clear_destination) wp-admin/includes/class-wp-upgrader.php | Clears the directory where this item is going to be installed into. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Upgrader::fs_connect( string[] $directories = array(), bool $allow_relaxed_file_ownership = false ): bool|WP_Error WP\_Upgrader::fs\_connect( string[] $directories = array(), bool $allow\_relaxed\_file\_ownership = false ): bool|WP\_Error
===========================================================================================================================
Connect to the filesystem.
`$directories` string[] Optional Array of directories. If any of these do not exist, a [WP\_Error](../wp_error) object will be returned.
Default: `array()`
`$allow_relaxed_file_ownership` bool Optional Whether to allow relaxed file ownership.
Default: `false`
bool|[WP\_Error](../wp_error) True if able to connect, false or a [WP\_Error](../wp_error) otherwise.
File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/)
```
public function fs_connect( $directories = array(), $allow_relaxed_file_ownership = false ) {
global $wp_filesystem;
$credentials = $this->skin->request_filesystem_credentials( false, $directories[0], $allow_relaxed_file_ownership );
if ( false === $credentials ) {
return false;
}
if ( ! WP_Filesystem( $credentials, $directories[0], $allow_relaxed_file_ownership ) ) {
$error = true;
if ( is_object( $wp_filesystem ) && $wp_filesystem->errors->has_errors() ) {
$error = $wp_filesystem->errors;
}
// Failed to connect. Error and request again.
$this->skin->request_filesystem_credentials( $error, $directories[0], $allow_relaxed_file_ownership );
return false;
}
if ( ! is_object( $wp_filesystem ) ) {
return new WP_Error( 'fs_unavailable', $this->strings['fs_unavailable'] );
}
if ( is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
return new WP_Error( 'fs_error', $this->strings['fs_error'], $wp_filesystem->errors );
}
foreach ( (array) $directories as $dir ) {
switch ( $dir ) {
case ABSPATH:
if ( ! $wp_filesystem->abspath() ) {
return new WP_Error( 'fs_no_root_dir', $this->strings['fs_no_root_dir'] );
}
break;
case WP_CONTENT_DIR:
if ( ! $wp_filesystem->wp_content_dir() ) {
return new WP_Error( 'fs_no_content_dir', $this->strings['fs_no_content_dir'] );
}
break;
case WP_PLUGIN_DIR:
if ( ! $wp_filesystem->wp_plugins_dir() ) {
return new WP_Error( 'fs_no_plugins_dir', $this->strings['fs_no_plugins_dir'] );
}
break;
case get_theme_root():
if ( ! $wp_filesystem->wp_themes_dir() ) {
return new WP_Error( 'fs_no_themes_dir', $this->strings['fs_no_themes_dir'] );
}
break;
default:
if ( ! $wp_filesystem->find_folder( $dir ) ) {
return new WP_Error( 'fs_no_folder', sprintf( $this->strings['fs_no_folder'], esc_html( basename( $dir ) ) ) );
}
break;
}
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Filesystem()](../../functions/wp_filesystem) wp-admin/includes/file.php | Initializes and connects the WordPress Filesystem Abstraction classes. |
| [get\_theme\_root()](../../functions/get_theme_root) wp-includes/theme.php | Retrieves path to themes directory. |
| [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. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Upgrader::run()](run) wp-admin/includes/class-wp-upgrader.php | Run an upgrade/installation. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader::release_lock( string $lock_name ): bool WP\_Upgrader::release\_lock( string $lock\_name ): bool
=======================================================
Releases an upgrader lock.
* [WP\_Upgrader::create\_lock()](../wp_upgrader/create_lock)
`$lock_name` string Required The name of this unique lock. bool True if the lock was successfully released. False on failure.
File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/)
```
public static function release_lock( $lock_name ) {
return delete_option( $lock_name . '.lock' );
}
```
| Uses | Description |
| --- | --- |
| [delete\_option()](../../functions/delete_option) wp-includes/option.php | Removes option by name. Prevents removal of protected WordPress options. |
| Used By | Description |
| --- | --- |
| [WP\_Upgrader::create\_lock()](create_lock) wp-admin/includes/class-wp-upgrader.php | Creates a lock using WordPress options. |
| [WP\_Automatic\_Updater::run()](../wp_automatic_updater/run) wp-admin/includes/class-wp-automatic-updater.php | Kicks off the background update process, looping through all pending updates. |
| [Core\_Upgrader::upgrade()](../core_upgrader/upgrade) wp-admin/includes/class-core-upgrader.php | Upgrade WordPress core. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Upgrader::generic_strings() WP\_Upgrader::generic\_strings()
================================
Add the generic strings to WP\_Upgrader::$strings.
File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/)
```
public function generic_strings() {
$this->strings['bad_request'] = __( 'Invalid data provided.' );
$this->strings['fs_unavailable'] = __( 'Could not access filesystem.' );
$this->strings['fs_error'] = __( 'Filesystem error.' );
$this->strings['fs_no_root_dir'] = __( 'Unable to locate WordPress root directory.' );
$this->strings['fs_no_content_dir'] = __( 'Unable to locate WordPress content directory (wp-content).' );
$this->strings['fs_no_plugins_dir'] = __( 'Unable to locate WordPress plugin directory.' );
$this->strings['fs_no_themes_dir'] = __( 'Unable to locate WordPress theme directory.' );
/* translators: %s: Directory name. */
$this->strings['fs_no_folder'] = __( 'Unable to locate needed folder (%s).' );
$this->strings['download_failed'] = __( 'Download failed.' );
$this->strings['installing_package'] = __( 'Installing the latest version…' );
$this->strings['no_files'] = __( 'The package contains no files.' );
$this->strings['folder_exists'] = __( 'Destination folder already exists.' );
$this->strings['mkdir_failed'] = __( 'Could not create directory.' );
$this->strings['incompatible_archive'] = __( 'The package could not be installed.' );
$this->strings['files_not_writable'] = __( 'The update cannot be installed because some files could not be copied. This is usually due to inconsistent file permissions.' );
$this->strings['maintenance_start'] = __( 'Enabling Maintenance mode…' );
$this->strings['maintenance_end'] = __( 'Disabling Maintenance mode…' );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Upgrader::init()](init) wp-admin/includes/class-wp-upgrader.php | Initialize the upgrader. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader::install_package( array|string $args = array() ): array|WP_Error WP\_Upgrader::install\_package( array|string $args = array() ): array|WP\_Error
===============================================================================
Install a package.
Copies the contents of a package from a source directory, and installs them in a destination directory. Optionally removes the source. It can also optionally clear out the destination folder if it already exists.
`$args` array|string Optional Array or string of arguments for installing a package.
* `source`stringRequired path to the package source.
* `destination`stringRequired path to a folder to install the package in.
* `clear_destination`boolWhether to delete any files already in the destination folder. Default false.
* `clear_working`boolWhether to delete the files from the working directory after copying them to the destination. Default false.
* `abort_if_destination_exists`boolWhether to abort the installation if the destination folder already exists. Default true.
* `hook_extra`arrayExtra arguments to pass to the filter hooks called by [WP\_Upgrader::install\_package()](install_package).
More Arguments from WP\_Upgrader::install\_package( ... $args ) Array or string of arguments for installing a package.
* `source`stringRequired path to the package source.
* `destination`stringRequired path to a folder to install the package in.
* `clear_destination`boolWhether to delete any files already in the destination folder. Default false.
* `clear_working`boolWhether to delete the files from the working directory after copying them to the destination. Default false.
* `abort_if_destination_exists`boolWhether to abort the installation if the destination folder already exists. Default true.
* `hook_extra`arrayExtra arguments to pass to the filter hooks called by [WP\_Upgrader::install\_package()](install_package).
Default: `array()`
array|[WP\_Error](../wp_error) The result (also stored in `WP_Upgrader::$result`), or a [WP\_Error](../wp_error) on failure.
File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/)
```
public function install_package( $args = array() ) {
global $wp_filesystem, $wp_theme_directories;
$defaults = array(
'source' => '', // Please always pass this.
'destination' => '', // ...and this.
'clear_destination' => false,
'clear_working' => false,
'abort_if_destination_exists' => true,
'hook_extra' => array(),
);
$args = wp_parse_args( $args, $defaults );
// These were previously extract()'d.
$source = $args['source'];
$destination = $args['destination'];
$clear_destination = $args['clear_destination'];
set_time_limit( 300 );
if ( empty( $source ) || empty( $destination ) ) {
return new WP_Error( 'bad_request', $this->strings['bad_request'] );
}
$this->skin->feedback( 'installing_package' );
/**
* Filters the installation response before the installation has started.
*
* Returning a value that could be evaluated as a `WP_Error` will effectively
* short-circuit the installation, returning that value instead.
*
* @since 2.8.0
*
* @param bool|WP_Error $response Installation response.
* @param array $hook_extra Extra arguments passed to hooked filters.
*/
$res = apply_filters( 'upgrader_pre_install', true, $args['hook_extra'] );
if ( is_wp_error( $res ) ) {
return $res;
}
// Retain the original source and destinations.
$remote_source = $args['source'];
$local_destination = $destination;
$source_files = array_keys( $wp_filesystem->dirlist( $remote_source ) );
$remote_destination = $wp_filesystem->find_folder( $local_destination );
// Locate which directory to copy to the new folder. This is based on the actual folder holding the files.
if ( 1 === count( $source_files ) && $wp_filesystem->is_dir( trailingslashit( $args['source'] ) . $source_files[0] . '/' ) ) {
// Only one folder? Then we want its contents.
$source = trailingslashit( $args['source'] ) . trailingslashit( $source_files[0] );
} elseif ( 0 === count( $source_files ) ) {
// There are no files?
return new WP_Error( 'incompatible_archive_empty', $this->strings['incompatible_archive'], $this->strings['no_files'] );
} else {
// It's only a single file, the upgrader will use the folder name of this file as the destination folder.
// Folder name is based on zip filename.
$source = trailingslashit( $args['source'] );
}
/**
* Filters the source file location for the upgrade package.
*
* @since 2.8.0
* @since 4.4.0 The $hook_extra parameter became available.
*
* @param string $source File source location.
* @param string $remote_source Remote file source location.
* @param WP_Upgrader $upgrader WP_Upgrader instance.
* @param array $hook_extra Extra arguments passed to hooked filters.
*/
$source = apply_filters( 'upgrader_source_selection', $source, $remote_source, $this, $args['hook_extra'] );
if ( is_wp_error( $source ) ) {
return $source;
}
// Has the source location changed? If so, we need a new source_files list.
if ( $source !== $remote_source ) {
$source_files = array_keys( $wp_filesystem->dirlist( $source ) );
}
/*
* Protection against deleting files in any important base directories.
* Theme_Upgrader & Plugin_Upgrader also trigger this, as they pass the
* destination directory (WP_PLUGIN_DIR / wp-content/themes) intending
* to copy the directory into the directory, whilst they pass the source
* as the actual files to copy.
*/
$protected_directories = array( ABSPATH, WP_CONTENT_DIR, WP_PLUGIN_DIR, WP_CONTENT_DIR . '/themes' );
if ( is_array( $wp_theme_directories ) ) {
$protected_directories = array_merge( $protected_directories, $wp_theme_directories );
}
if ( in_array( $destination, $protected_directories, true ) ) {
$remote_destination = trailingslashit( $remote_destination ) . trailingslashit( basename( $source ) );
$destination = trailingslashit( $destination ) . trailingslashit( basename( $source ) );
}
if ( $clear_destination ) {
// We're going to clear the destination if there's something there.
$this->skin->feedback( 'remove_old' );
$removed = $this->clear_destination( $remote_destination );
/**
* Filters whether the upgrader cleared the destination.
*
* @since 2.8.0
*
* @param true|WP_Error $removed Whether the destination was cleared.
* True upon success, WP_Error on failure.
* @param string $local_destination The local package destination.
* @param string $remote_destination The remote package destination.
* @param array $hook_extra Extra arguments passed to hooked filters.
*/
$removed = apply_filters( 'upgrader_clear_destination', $removed, $local_destination, $remote_destination, $args['hook_extra'] );
if ( is_wp_error( $removed ) ) {
return $removed;
}
} elseif ( $args['abort_if_destination_exists'] && $wp_filesystem->exists( $remote_destination ) ) {
// If we're not clearing the destination folder and something exists there already, bail.
// But first check to see if there are actually any files in the folder.
$_files = $wp_filesystem->dirlist( $remote_destination );
if ( ! empty( $_files ) ) {
$wp_filesystem->delete( $remote_source, true ); // Clear out the source files.
return new WP_Error( 'folder_exists', $this->strings['folder_exists'], $remote_destination );
}
}
// Create destination if needed.
if ( ! $wp_filesystem->exists( $remote_destination ) ) {
if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) ) {
return new WP_Error( 'mkdir_failed_destination', $this->strings['mkdir_failed'], $remote_destination );
}
}
// Copy new version of item into place.
$result = copy_dir( $source, $remote_destination );
if ( is_wp_error( $result ) ) {
if ( $args['clear_working'] ) {
$wp_filesystem->delete( $remote_source, true );
}
return $result;
}
// Clear the working folder?
if ( $args['clear_working'] ) {
$wp_filesystem->delete( $remote_source, true );
}
$destination_name = basename( str_replace( $local_destination, '', $destination ) );
if ( '.' === $destination_name ) {
$destination_name = '';
}
$this->result = compact( 'source', 'source_files', 'destination', 'destination_name', 'local_destination', 'remote_destination', 'clear_destination' );
/**
* Filters the installation response after the installation has finished.
*
* @since 2.8.0
*
* @param bool $response Installation response.
* @param array $hook_extra Extra arguments passed to hooked filters.
* @param array $result Installation result data.
*/
$res = apply_filters( 'upgrader_post_install', true, $args['hook_extra'], $this->result );
if ( is_wp_error( $res ) ) {
$this->result = $res;
return $res;
}
// Bombard the calling function will all the info which we've just used.
return $this->result;
}
```
[apply\_filters( 'upgrader\_clear\_destination', true|WP\_Error $removed, string $local\_destination, string $remote\_destination, array $hook\_extra )](../../hooks/upgrader_clear_destination)
Filters whether the upgrader cleared the destination.
[apply\_filters( 'upgrader\_post\_install', bool $response, array $hook\_extra, array $result )](../../hooks/upgrader_post_install)
Filters the installation response after the installation has finished.
[apply\_filters( 'upgrader\_pre\_install', bool|WP\_Error $response, array $hook\_extra )](../../hooks/upgrader_pre_install)
Filters the installation response before the installation has started.
[apply\_filters( 'upgrader\_source\_selection', string $source, string $remote\_source, WP\_Upgrader $upgrader, array $hook\_extra )](../../hooks/upgrader_source_selection)
Filters the source file location for the upgrade package.
| Uses | Description |
| --- | --- |
| [WP\_Upgrader::clear\_destination()](clear_destination) wp-admin/includes/class-wp-upgrader.php | Clears the directory where this item is going to be installed into. |
| [copy\_dir()](../../functions/copy_dir) wp-admin/includes/file.php | Copies a directory from one location to another via the WordPress Filesystem Abstraction. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [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. |
| [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\_Upgrader::run()](run) wp-admin/includes/class-wp-upgrader.php | Run an upgrade/installation. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Upgrader::maintenance_mode( bool $enable = false ) WP\_Upgrader::maintenance\_mode( bool $enable = false )
=======================================================
Toggle maintenance mode for the site.
Creates/deletes the maintenance file to enable/disable maintenance mode.
`$enable` bool Optional True to enable maintenance mode, false to disable. Default: `false`
File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/)
```
public function maintenance_mode( $enable = false ) {
global $wp_filesystem;
$file = $wp_filesystem->abspath() . '.maintenance';
if ( $enable ) {
$this->skin->feedback( 'maintenance_start' );
// Create maintenance file to signal that we are upgrading.
$maintenance_string = '<?php $upgrading = ' . time() . '; ?>';
$wp_filesystem->delete( $file );
$wp_filesystem->put_contents( $file, $maintenance_string, FS_CHMOD_FILE );
} elseif ( ! $enable && $wp_filesystem->exists( $file ) ) {
$this->skin->feedback( 'maintenance_end' );
$wp_filesystem->delete( $file );
}
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader::__construct( WP_Upgrader_Skin $skin = null ) WP\_Upgrader::\_\_construct( WP\_Upgrader\_Skin $skin = null )
==============================================================
Construct the upgrader with a skin.
`$skin` [WP\_Upgrader\_Skin](../wp_upgrader_skin) Optional The upgrader skin to use. Default is a [WP\_Upgrader\_Skin](../wp_upgrader_skin) instance. Default: `null`
File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/)
```
public function __construct( $skin = null ) {
if ( null === $skin ) {
$this->skin = new WP_Upgrader_Skin();
} else {
$this->skin = $skin;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Upgrader\_Skin::\_\_construct()](../wp_upgrader_skin/__construct) wp-admin/includes/class-wp-upgrader-skin.php | Constructor. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Upgrader::clear_destination( string $remote_destination ): true|WP_Error WP\_Upgrader::clear\_destination( string $remote\_destination ): true|WP\_Error
===============================================================================
Clears the directory where this item is going to be installed into.
`$remote_destination` string Required The location on the remote filesystem to be cleared. true|[WP\_Error](../wp_error) True upon success, [WP\_Error](../wp_error) on failure.
File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/)
```
public function clear_destination( $remote_destination ) {
global $wp_filesystem;
$files = $wp_filesystem->dirlist( $remote_destination, true, true );
// False indicates that the $remote_destination doesn't exist.
if ( false === $files ) {
return true;
}
// Flatten the file list to iterate over.
$files = $this->flatten_dirlist( $files );
// Check all files are writable before attempting to clear the destination.
$unwritable_files = array();
// Check writability.
foreach ( $files as $filename => $file_details ) {
if ( ! $wp_filesystem->is_writable( $remote_destination . $filename ) ) {
// Attempt to alter permissions to allow writes and try again.
$wp_filesystem->chmod( $remote_destination . $filename, ( 'd' === $file_details['type'] ? FS_CHMOD_DIR : FS_CHMOD_FILE ) );
if ( ! $wp_filesystem->is_writable( $remote_destination . $filename ) ) {
$unwritable_files[] = $filename;
}
}
}
if ( ! empty( $unwritable_files ) ) {
return new WP_Error( 'files_not_writable', $this->strings['files_not_writable'], implode( ', ', $unwritable_files ) );
}
if ( ! $wp_filesystem->delete( $remote_destination, true ) ) {
return new WP_Error( 'remove_old_failed', $this->strings['remove_old_failed'] );
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Upgrader::flatten\_dirlist()](flatten_dirlist) wp-admin/includes/class-wp-upgrader.php | Flatten the results of [WP\_Filesystem\_Base::dirlist()](../wp_filesystem_base/dirlist) for iterating over. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Upgrader::install\_package()](install_package) wp-admin/includes/class-wp-upgrader.php | Install a package. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Upgrader::download_package( string $package, bool $check_signatures = false, array $hook_extra = array() ): string|WP_Error WP\_Upgrader::download\_package( string $package, bool $check\_signatures = false, array $hook\_extra = array() ): string|WP\_Error
===================================================================================================================================
Download a package.
`$package` string Required The URI of the package. If this is the full path to an existing local file, it will be returned untouched. `$check_signatures` bool Optional Whether to validate file signatures. Default: `false`
`$hook_extra` array Optional Extra arguments to pass to the filter hooks. Default: `array()`
string|[WP\_Error](../wp_error) The full path to the downloaded package file, or a [WP\_Error](../wp_error) object.
File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/)
```
public function download_package( $package, $check_signatures = false, $hook_extra = array() ) {
/**
* Filters whether to return the package.
*
* @since 3.7.0
* @since 5.5.0 Added the `$hook_extra` parameter.
*
* @param bool $reply Whether to bail without returning the package.
* Default false.
* @param string $package The package file name.
* @param WP_Upgrader $upgrader The WP_Upgrader instance.
* @param array $hook_extra Extra arguments passed to hooked filters.
*/
$reply = apply_filters( 'upgrader_pre_download', false, $package, $this, $hook_extra );
if ( false !== $reply ) {
return $reply;
}
if ( ! preg_match( '!^(http|https|ftp)://!i', $package ) && file_exists( $package ) ) { // Local file or remote?
return $package; // Must be a local file.
}
if ( empty( $package ) ) {
return new WP_Error( 'no_package', $this->strings['no_package'] );
}
$this->skin->feedback( 'downloading_package', $package );
$download_file = download_url( $package, 300, $check_signatures );
if ( is_wp_error( $download_file ) && ! $download_file->get_error_data( 'softfail-filename' ) ) {
return new WP_Error( 'download_failed', $this->strings['download_failed'], $download_file->get_error_message() );
}
return $download_file;
}
```
[apply\_filters( 'upgrader\_pre\_download', bool $reply, string $package, WP\_Upgrader $upgrader, array $hook\_extra )](../../hooks/upgrader_pre_download)
Filters whether to return the package.
| Uses | Description |
| --- | --- |
| [download\_url()](../../functions/download_url) wp-admin/includes/file.php | Downloads a URL to a local temporary file using the WordPress HTTP API. |
| [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\_Upgrader::run()](run) wp-admin/includes/class-wp-upgrader.php | Run an upgrade/installation. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Added the `$hook_extra` parameter. |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Added the `$check_signatures` parameter. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Sitemaps_Posts::get_max_num_pages( string $object_subtype = '' ): int WP\_Sitemaps\_Posts::get\_max\_num\_pages( string $object\_subtype = '' ): int
==============================================================================
Gets the max number of pages available for the object type.
`$object_subtype` string Optional Post type name. Default: `''`
int Total number of pages.
File: `wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/providers/class-wp-sitemaps-posts.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.
$post_type = $object_subtype;
/**
* Filters the max number of pages 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 $post_type Post type name.
*/
$max_num_pages = apply_filters( 'wp_sitemaps_posts_pre_max_num_pages', null, $post_type );
if ( null !== $max_num_pages ) {
return $max_num_pages;
}
$args = $this->get_posts_query_args( $post_type );
$args['fields'] = 'ids';
$args['no_found_rows'] = false;
$query = new WP_Query( $args );
$min_num_pages = ( 'page' === $post_type && 'posts' === get_option( 'show_on_front' ) ) ? 1 : 0;
return isset( $query->max_num_pages ) ? max( $min_num_pages, $query->max_num_pages ) : 1;
}
```
[apply\_filters( 'wp\_sitemaps\_posts\_pre\_max\_num\_pages', int|null $max\_num\_pages, string $post\_type )](../../hooks/wp_sitemaps_posts_pre_max_num_pages)
Filters the max number of pages before it is generated.
| Uses | Description |
| --- | --- |
| [WP\_Sitemaps\_Posts::get\_posts\_query\_args()](get_posts_query_args) wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php | Returns the query args for retrieving posts to list in the sitemap. |
| [WP\_Query::\_\_construct()](../wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [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.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$post_type` 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_Posts::get_posts_query_args( string $post_type ): array WP\_Sitemaps\_Posts::get\_posts\_query\_args( string $post\_type ): array
=========================================================================
Returns the query args for retrieving posts to list in the sitemap.
`$post_type` string Required Post type name. array Array of [WP\_Query](../wp_query) arguments.
File: `wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php/)
```
protected function get_posts_query_args( $post_type ) {
/**
* Filters the query arguments for post type sitemap queries.
*
* @see WP_Query for a full list of arguments.
*
* @since 5.5.0
* @since 6.1.0 Added `ignore_sticky_posts` default parameter.
*
* @param array $args Array of WP_Query arguments.
* @param string $post_type Post type name.
*/
$args = apply_filters(
'wp_sitemaps_posts_query_args',
array(
'orderby' => 'ID',
'order' => 'ASC',
'post_type' => $post_type,
'posts_per_page' => wp_sitemaps_get_max_urls( $this->object_type ),
'post_status' => array( 'publish' ),
'no_found_rows' => true,
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
'ignore_sticky_posts' => true, // sticky posts will still appear, but they won't be moved to the front.
),
$post_type
);
return $args;
}
```
[apply\_filters( 'wp\_sitemaps\_posts\_query\_args', array $args, string $post\_type )](../../hooks/wp_sitemaps_posts_query_args)
Filters the query arguments for post type sitemap queries.
| 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\_Posts::get\_url\_list()](get_url_list) wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php | Gets a URL list for a post type sitemap. |
| [WP\_Sitemaps\_Posts::get\_max\_num\_pages()](get_max_num_pages) wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php | Gets the max number of pages available for the object type. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Added `ignore_sticky_posts` default parameter. |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps_Posts::__construct() WP\_Sitemaps\_Posts::\_\_construct()
====================================
[WP\_Sitemaps\_Posts](../wp_sitemaps_posts) constructor.
File: `wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php/)
```
public function __construct() {
$this->name = 'posts';
$this->object_type = 'post';
}
```
| 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_Posts::get_url_list( int $page_num, string $object_subtype = '' ): array[] WP\_Sitemaps\_Posts::get\_url\_list( int $page\_num, string $object\_subtype = '' ): array[]
============================================================================================
Gets a URL list for a post type sitemap.
`$page_num` int Required Page of results. `$object_subtype` string Optional Post type name. Default: `''`
array[] Array of URL information for a sitemap.
File: `wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php/)
```
public function get_url_list( $page_num, $object_subtype = '' ) {
// Restores the more descriptive, specific name for use within this method.
$post_type = $object_subtype;
// Bail early if the queried post type is not supported.
$supported_types = $this->get_object_subtypes();
if ( ! isset( $supported_types[ $post_type ] ) ) {
return array();
}
/**
* Filters the posts 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 $post_type Post type name.
* @param int $page_num Page of results.
*/
$url_list = apply_filters(
'wp_sitemaps_posts_pre_url_list',
null,
$post_type,
$page_num
);
if ( null !== $url_list ) {
return $url_list;
}
$args = $this->get_posts_query_args( $post_type );
$args['paged'] = $page_num;
$query = new WP_Query( $args );
$url_list = array();
/*
* Add a URL for the homepage in the pages sitemap.
* Shows only on the first page if the reading settings are set to display latest posts.
*/
if ( 'page' === $post_type && 1 === $page_num && 'posts' === get_option( 'show_on_front' ) ) {
// Extract the data needed for home URL to add to the array.
$sitemap_entry = array(
'loc' => home_url( '/' ),
);
/**
* Filters the sitemap entry for the home page when the 'show_on_front' option equals 'posts'.
*
* @since 5.5.0
*
* @param array $sitemap_entry Sitemap entry for the home page.
*/
$sitemap_entry = apply_filters( 'wp_sitemaps_posts_show_on_front_entry', $sitemap_entry );
$url_list[] = $sitemap_entry;
}
foreach ( $query->posts as $post ) {
$sitemap_entry = array(
'loc' => get_permalink( $post ),
);
/**
* Filters the sitemap entry for an individual post.
*
* @since 5.5.0
*
* @param array $sitemap_entry Sitemap entry for the post.
* @param WP_Post $post Post object.
* @param string $post_type Name of the post_type.
*/
$sitemap_entry = apply_filters( 'wp_sitemaps_posts_entry', $sitemap_entry, $post, $post_type );
$url_list[] = $sitemap_entry;
}
return $url_list;
}
```
[apply\_filters( 'wp\_sitemaps\_posts\_entry', array $sitemap\_entry, WP\_Post $post, string $post\_type )](../../hooks/wp_sitemaps_posts_entry)
Filters the sitemap entry for an individual post.
[apply\_filters( 'wp\_sitemaps\_posts\_pre\_url\_list', array[]|null $url\_list, string $post\_type, int $page\_num )](../../hooks/wp_sitemaps_posts_pre_url_list)
Filters the posts URL list before it is generated.
[apply\_filters( 'wp\_sitemaps\_posts\_show\_on\_front\_entry', array $sitemap\_entry )](../../hooks/wp_sitemaps_posts_show_on_front_entry)
Filters the sitemap entry for the home page when the ‘show\_on\_front’ option equals ‘posts’.
| Uses | Description |
| --- | --- |
| [WP\_Sitemaps\_Posts::get\_posts\_query\_args()](get_posts_query_args) wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php | Returns the query args for retrieving posts to list in the sitemap. |
| [WP\_Sitemaps\_Posts::get\_object\_subtypes()](get_object_subtypes) wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php | Returns the public post types, which excludes nav\_items and similar types. |
| [WP\_Query::\_\_construct()](../wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [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\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$post_type` 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. |
| programming_docs |
wordpress WP_Sitemaps_Posts::get_object_subtypes(): WP_Post_Type[] WP\_Sitemaps\_Posts::get\_object\_subtypes(): WP\_Post\_Type[]
==============================================================
Returns the public post types, which excludes nav\_items and similar types.
Attachments are also excluded. This includes custom post types with public = true.
[WP\_Post\_Type](../wp_post_type)[] Array of registered post type objects keyed by their name.
File: `wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php/)
```
public function get_object_subtypes() {
$post_types = get_post_types( array( 'public' => true ), 'objects' );
unset( $post_types['attachment'] );
$post_types = array_filter( $post_types, 'is_post_type_viewable' );
/**
* Filters the list of post object sub types available within the sitemap.
*
* @since 5.5.0
*
* @param WP_Post_Type[] $post_types Array of registered post type objects keyed by their name.
*/
return apply_filters( 'wp_sitemaps_post_types', $post_types );
}
```
[apply\_filters( 'wp\_sitemaps\_post\_types', WP\_Post\_Type[] $post\_types )](../../hooks/wp_sitemaps_post_types)
Filters the list of post object sub types available within the sitemap.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added 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\_Sitemaps\_Posts::get\_url\_list()](get_url_list) wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php | Gets a URL list for a post type sitemap. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress Requests_SSL::match_domain( string $host, string $reference ): boolean Requests\_SSL::match\_domain( string $host, string $reference ): boolean
========================================================================
Match a hostname against a dNSName reference
`$host` string Required Requested host `$reference` string Required dNSName to match against boolean Does the domain match?
File: `wp-includes/Requests/SSL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/ssl.php/)
```
public static function match_domain($host, $reference) {
// Check if the reference is blocklisted first
if (self::verify_reference_name($reference) !== true) {
return false;
}
// Check for a direct match
if ($host === $reference) {
return true;
}
// Calculate the valid wildcard match if the host is not an IP address
// Also validates that the host has 3 parts or more, as per Firefox's
// ruleset.
if (ip2long($host) === false) {
$parts = explode('.', $host);
$parts[0] = '*';
$wildcard = implode('.', $parts);
if ($wildcard === $reference) {
return true;
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_SSL::verify\_reference\_name()](verify_reference_name) wp-includes/Requests/SSL.php | Verify that a reference name is valid |
| Used By | Description |
| --- | --- |
| [Requests\_SSL::verify\_certificate()](verify_certificate) wp-includes/Requests/SSL.php | Verify the certificate against common name and subject alternative names |
wordpress Requests_SSL::verify_certificate( string $host, array $cert ): bool Requests\_SSL::verify\_certificate( string $host, array $cert ): bool
=====================================================================
Verify the certificate against common name and subject alternative names
Unfortunately, PHP doesn’t check the certificate against the alternative names, leading things like ‘<https://www.github.com/>‘ to be invalid.
* <https://tools.ietf.org/html/rfc2818#section-3.1>: RFC2818, Section 3.1
`$host` string Required Host name to verify against `$cert` array Required Certificate data from openssl\_x509\_parse() bool
File: `wp-includes/Requests/SSL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/ssl.php/)
```
public static function verify_certificate($host, $cert) {
$has_dns_alt = false;
// Check the subjectAltName
if (!empty($cert['extensions']) && !empty($cert['extensions']['subjectAltName'])) {
$altnames = explode(',', $cert['extensions']['subjectAltName']);
foreach ($altnames as $altname) {
$altname = trim($altname);
if (strpos($altname, 'DNS:') !== 0) {
continue;
}
$has_dns_alt = true;
// Strip the 'DNS:' prefix and trim whitespace
$altname = trim(substr($altname, 4));
// Check for a match
if (self::match_domain($host, $altname) === true) {
return true;
}
}
}
// Fall back to checking the common name if we didn't get any dNSName
// alt names, as per RFC2818
if (!$has_dns_alt && !empty($cert['subject']['CN'])) {
// Check for a match
if (self::match_domain($host, $cert['subject']['CN']) === true) {
return true;
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [Requests\_SSL::match\_domain()](match_domain) wp-includes/Requests/SSL.php | Match a hostname against a dNSName reference |
| Used By | Description |
| --- | --- |
| [Requests\_Transport\_fsockopen::verify\_certificate\_from\_context()](../requests_transport_fsockopen/verify_certificate_from_context) wp-includes/Requests/Transport/fsockopen.php | Verify the certificate against common name and subject alternative names |
wordpress Requests_SSL::verify_reference_name( string $reference ): boolean Requests\_SSL::verify\_reference\_name( string $reference ): boolean
====================================================================
Verify that a reference name is valid
Verifies a dNSName for HTTPS usage, (almost) as per Firefox’s rules:
* Wildcards can only occur in a name with more than 3 components
* Wildcards can only occur as the last character in the first component
* Wildcards may be preceded by additional characters
We modify these rules to be a bit stricter and only allow the wildcard character to be the full first component; that is, with the exclusion of the third rule.
`$reference` string Required Reference dNSName boolean Is the name valid?
File: `wp-includes/Requests/SSL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/ssl.php/)
```
public static function verify_reference_name($reference) {
$parts = explode('.', $reference);
// Check the first part of the name
$first = array_shift($parts);
if (strpos($first, '*') !== false) {
// Check that the wildcard is the full part
if ($first !== '*') {
return false;
}
// Check that we have at least 3 components (including first)
if (count($parts) < 2) {
return false;
}
}
// Check the remaining parts
foreach ($parts as $part) {
if (strpos($part, '*') !== false) {
return false;
}
}
// Nothing found, verified!
return true;
}
```
| Used By | Description |
| --- | --- |
| [Requests\_SSL::match\_domain()](match_domain) wp-includes/Requests/SSL.php | Match a hostname against a dNSName reference |
wordpress WP_REST_Block_Patterns_Controller::prepare_item_for_response( array $item, WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Block\_Patterns\_Controller::prepare\_item\_for\_response( array $item, WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
============================================================================================================================================
Prepare a raw block pattern before it gets output in a REST API response.
`$item` array Required Raw pattern 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-patterns-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-patterns-controller.php/)
```
public function prepare_item_for_response( $item, $request ) {
$fields = $this->get_fields_for_response( $request );
$keys = array(
'name' => 'name',
'title' => 'title',
'description' => 'description',
'viewportWidth' => 'viewport_width',
'blockTypes' => 'block_types',
'postTypes' => 'post_types',
'categories' => 'categories',
'keywords' => 'keywords',
'content' => 'content',
'inserter' => 'inserter',
);
$data = array();
foreach ( $keys as $item_key => $rest_key ) {
if ( isset( $item[ $item_key ] ) && rest_is_field_included( $rest_key, $fields ) ) {
$data[ $rest_key ] = $item[ $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\_Patterns\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-block-patterns-controller.php | Retrieves all block patterns. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_REST_Block_Patterns_Controller::get_items( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Block\_Patterns\_Controller::get\_items( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=============================================================================================================
Retrieves all block patterns.
`$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-block-patterns-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-patterns-controller.php/)
```
public function get_items( $request ) {
if ( ! $this->remote_patterns_loaded ) {
// Load block patterns from w.org.
_load_remote_block_patterns(); // Patterns with the `core` keyword.
_load_remote_featured_patterns(); // Patterns in the `featured` category.
_register_remote_theme_patterns(); // Patterns requested by current theme.
$this->remote_patterns_loaded = true;
}
$response = array();
$patterns = WP_Block_Patterns_Registry::get_instance()->get_all_registered();
foreach ( $patterns as $pattern ) {
$prepared_pattern = $this->prepare_item_for_response( $pattern, $request );
$response[] = $this->prepare_response_for_collection( $prepared_pattern );
}
return rest_ensure_response( $response );
}
```
| Uses | Description |
| --- | --- |
| [\_register\_remote\_theme\_patterns()](../../functions/_register_remote_theme_patterns) wp-includes/block-patterns.php | Registers patterns from Pattern Directory provided by a theme’s `theme.json` file. |
| [WP\_REST\_Block\_Patterns\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-block-patterns-controller.php | Prepare a raw block pattern before it gets output in a REST API response. |
| [\_load\_remote\_featured\_patterns()](../../functions/_load_remote_featured_patterns) wp-includes/block-patterns.php | Register `Featured` (category) patterns from wordpress.org/patterns. |
| [\_load\_remote\_block\_patterns()](../../functions/_load_remote_block_patterns) wp-includes/block-patterns.php | Register Core’s official patterns from wordpress.org/patterns. |
| [WP\_Block\_Patterns\_Registry::get\_instance()](../wp_block_patterns_registry/get_instance) wp-includes/class-wp-block-patterns-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_Patterns_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Block\_Patterns\_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-patterns-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-patterns-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 patterns.' ),
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_Patterns_Controller::register_routes() WP\_REST\_Block\_Patterns\_Controller::register\_routes()
=========================================================
Registers the routes for the objects of the controller.
File: `wp-includes/rest-api/endpoints/class-wp-rest-block-patterns-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-patterns-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_Patterns_Controller::__construct() WP\_REST\_Block\_Patterns\_Controller::\_\_construct()
======================================================
Constructs the controller.
File: `wp-includes/rest-api/endpoints/class-wp-rest-block-patterns-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-patterns-controller.php/)
```
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'block-patterns/patterns';
}
```
| 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_Patterns_Controller::get_item_schema(): array WP\_REST\_Block\_Patterns\_Controller::get\_item\_schema(): array
=================================================================
Retrieves the block pattern schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-block-patterns-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-patterns-controller.php/)
```
public function get_item_schema() {
$schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'block-pattern',
'type' => 'object',
'properties' => array(
'name' => array(
'description' => __( 'The pattern name.' ),
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'title' => array(
'description' => __( 'The pattern title, in human readable format.' ),
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'description' => array(
'description' => __( 'The pattern detailed description.' ),
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'viewport_width' => array(
'description' => __( 'The pattern viewport width for inserter preview.' ),
'type' => 'number',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'block_types' => array(
'description' => __( 'Block types that the pattern is intended to be used with.' ),
'type' => 'array',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'post_types' => array(
'description' => __( 'An array of post types that the pattern is restricted to be used with.' ),
'type' => 'array',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'categories' => array(
'description' => __( 'The pattern category slugs.' ),
'type' => 'array',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'keywords' => array(
'description' => __( 'The pattern keywords.' ),
'type' => 'array',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'content' => array(
'description' => __( 'The pattern content.' ),
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'inserter' => array(
'description' => __( 'Determines whether the pattern is visible in inserter.' ),
'type' => 'boolean',
'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. |
| programming_docs |
wordpress _WP_Editors::editor_settings( string $editor_id, array $set ) \_WP\_Editors::editor\_settings( string $editor\_id, array $set )
=================================================================
`$editor_id` string Required Unique editor identifier, e.g. `'content'`. `$set` array Required Array of editor arguments. File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function editor_settings( $editor_id, $set ) {
if ( empty( self::$first_init ) ) {
if ( is_admin() ) {
add_action( 'admin_print_footer_scripts', array( __CLASS__, 'editor_js' ), 50 );
add_action( 'admin_print_footer_scripts', array( __CLASS__, 'force_uncompressed_tinymce' ), 1 );
add_action( 'admin_print_footer_scripts', array( __CLASS__, 'enqueue_scripts' ), 1 );
} else {
add_action( 'wp_print_footer_scripts', array( __CLASS__, 'editor_js' ), 50 );
add_action( 'wp_print_footer_scripts', array( __CLASS__, 'force_uncompressed_tinymce' ), 1 );
add_action( 'wp_print_footer_scripts', array( __CLASS__, 'enqueue_scripts' ), 1 );
}
}
if ( self::$this_quicktags ) {
$qtInit = array(
'id' => $editor_id,
'buttons' => '',
);
if ( is_array( $set['quicktags'] ) ) {
$qtInit = array_merge( $qtInit, $set['quicktags'] );
}
if ( empty( $qtInit['buttons'] ) ) {
$qtInit['buttons'] = 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close';
}
if ( $set['_content_editor_dfw'] ) {
$qtInit['buttons'] .= ',dfw';
}
/**
* Filters the Quicktags settings.
*
* @since 3.3.0
*
* @param array $qtInit Quicktags settings.
* @param string $editor_id Unique editor identifier, e.g. 'content'.
*/
$qtInit = apply_filters( 'quicktags_settings', $qtInit, $editor_id );
self::$qt_settings[ $editor_id ] = $qtInit;
self::$qt_buttons = array_merge( self::$qt_buttons, explode( ',', $qtInit['buttons'] ) );
}
if ( self::$this_tinymce ) {
if ( empty( self::$first_init ) ) {
$baseurl = self::get_baseurl();
$mce_locale = self::get_mce_locale();
$ext_plugins = '';
if ( $set['teeny'] ) {
/**
* Filters the list of teenyMCE plugins.
*
* @since 2.7.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $plugins An array of teenyMCE plugins.
* @param string $editor_id Unique editor identifier, e.g. 'content'.
*/
$plugins = apply_filters(
'teeny_mce_plugins',
array(
'colorpicker',
'lists',
'fullscreen',
'image',
'wordpress',
'wpeditimage',
'wplink',
),
$editor_id
);
} else {
/**
* Filters the list of TinyMCE external plugins.
*
* The filter takes an associative array of external plugins for
* TinyMCE in the form 'plugin_name' => 'url'.
*
* The url should be absolute, and should include the js filename
* to be loaded. For example:
* 'myplugin' => 'http://mysite.com/wp-content/plugins/myfolder/mce_plugin.js'.
*
* If the external plugin adds a button, it should be added with
* one of the 'mce_buttons' filters.
*
* @since 2.5.0
* @since 5.3.0 The `$editor_id` parameter was added.
*
* @param array $external_plugins An array of external TinyMCE plugins.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$mce_external_plugins = apply_filters( 'mce_external_plugins', array(), $editor_id );
$plugins = array(
'charmap',
'colorpicker',
'hr',
'lists',
'media',
'paste',
'tabfocus',
'textcolor',
'fullscreen',
'wordpress',
'wpautoresize',
'wpeditimage',
'wpemoji',
'wpgallery',
'wplink',
'wpdialogs',
'wptextpattern',
'wpview',
);
if ( ! self::$has_medialib ) {
$plugins[] = 'image';
}
/**
* Filters the list of default TinyMCE plugins.
*
* The filter specifies which of the default plugins included
* in WordPress should be added to the TinyMCE instance.
*
* @since 3.3.0
* @since 5.3.0 The `$editor_id` parameter was added.
*
* @param array $plugins An array of default TinyMCE plugins.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$plugins = array_unique( apply_filters( 'tiny_mce_plugins', $plugins, $editor_id ) );
$key = array_search( 'spellchecker', $plugins, true );
if ( false !== $key ) {
// Remove 'spellchecker' from the internal plugins if added with 'tiny_mce_plugins' filter to prevent errors.
// It can be added with 'mce_external_plugins'.
unset( $plugins[ $key ] );
}
if ( ! empty( $mce_external_plugins ) ) {
/**
* Filters the translations loaded for external TinyMCE 3.x plugins.
*
* The filter takes an associative array ('plugin_name' => 'path')
* where 'path' is the include path to the file.
*
* The language file should follow the same format as wp_mce_translation(),
* and should define a variable ($strings) that holds all translated strings.
*
* @since 2.5.0
* @since 5.3.0 The `$editor_id` parameter was added.
*
* @param array $translations Translations for external TinyMCE plugins.
* @param string $editor_id Unique editor identifier, e.g. 'content'.
*/
$mce_external_languages = apply_filters( 'mce_external_languages', array(), $editor_id );
$loaded_langs = array();
$strings = '';
if ( ! empty( $mce_external_languages ) ) {
foreach ( $mce_external_languages as $name => $path ) {
if ( @is_file( $path ) && @is_readable( $path ) ) {
include_once $path;
$ext_plugins .= $strings . "\n";
$loaded_langs[] = $name;
}
}
}
foreach ( $mce_external_plugins as $name => $url ) {
if ( in_array( $name, $plugins, true ) ) {
unset( $mce_external_plugins[ $name ] );
continue;
}
$url = set_url_scheme( $url );
$mce_external_plugins[ $name ] = $url;
$plugurl = dirname( $url );
$strings = '';
// Try to load langs/[locale].js and langs/[locale]_dlg.js.
if ( ! in_array( $name, $loaded_langs, true ) ) {
$path = str_replace( content_url(), '', $plugurl );
$path = WP_CONTENT_DIR . $path . '/langs/';
$path = trailingslashit( realpath( $path ) );
if ( @is_file( $path . $mce_locale . '.js' ) ) {
$strings .= @file_get_contents( $path . $mce_locale . '.js' ) . "\n";
}
if ( @is_file( $path . $mce_locale . '_dlg.js' ) ) {
$strings .= @file_get_contents( $path . $mce_locale . '_dlg.js' ) . "\n";
}
if ( 'en' !== $mce_locale && empty( $strings ) ) {
if ( @is_file( $path . 'en.js' ) ) {
$str1 = @file_get_contents( $path . 'en.js' );
$strings .= preg_replace( '/([\'"])en\./', '$1' . $mce_locale . '.', $str1, 1 ) . "\n";
}
if ( @is_file( $path . 'en_dlg.js' ) ) {
$str2 = @file_get_contents( $path . 'en_dlg.js' );
$strings .= preg_replace( '/([\'"])en\./', '$1' . $mce_locale . '.', $str2, 1 ) . "\n";
}
}
if ( ! empty( $strings ) ) {
$ext_plugins .= "\n" . $strings . "\n";
}
}
$ext_plugins .= 'tinyMCEPreInit.load_ext("' . $plugurl . '", "' . $mce_locale . '");' . "\n";
}
}
}
self::$plugins = $plugins;
self::$ext_plugins = $ext_plugins;
$settings = self::default_settings();
$settings['plugins'] = implode( ',', $plugins );
if ( ! empty( $mce_external_plugins ) ) {
$settings['external_plugins'] = wp_json_encode( $mce_external_plugins );
}
/** This filter is documented in wp-admin/includes/media.php */
if ( apply_filters( 'disable_captions', '' ) ) {
$settings['wpeditimage_disable_captions'] = true;
}
$mce_css = $settings['content_css'];
/*
* The `editor-style.css` added by the theme is generally intended for the editor instance on the Edit Post screen.
* Plugins that use wp_editor() on the front-end can decide whether to add the theme stylesheet
* by using `get_editor_stylesheets()` and the `mce_css` or `tiny_mce_before_init` filters, see below.
*/
if ( is_admin() ) {
$editor_styles = get_editor_stylesheets();
if ( ! empty( $editor_styles ) ) {
// Force urlencoding of commas.
foreach ( $editor_styles as $key => $url ) {
if ( strpos( $url, ',' ) !== false ) {
$editor_styles[ $key ] = str_replace( ',', '%2C', $url );
}
}
$mce_css .= ',' . implode( ',', $editor_styles );
}
}
/**
* Filters the comma-delimited list of stylesheets to load in TinyMCE.
*
* @since 2.1.0
*
* @param string $stylesheets Comma-delimited list of stylesheets.
*/
$mce_css = trim( apply_filters( 'mce_css', $mce_css ), ' ,' );
if ( ! empty( $mce_css ) ) {
$settings['content_css'] = $mce_css;
} else {
unset( $settings['content_css'] );
}
self::$first_init = $settings;
}
if ( $set['teeny'] ) {
$mce_buttons = array(
'bold',
'italic',
'underline',
'blockquote',
'strikethrough',
'bullist',
'numlist',
'alignleft',
'aligncenter',
'alignright',
'undo',
'redo',
'link',
'fullscreen',
);
/**
* Filters the list of teenyMCE buttons (Text tab).
*
* @since 2.7.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mce_buttons An array of teenyMCE buttons.
* @param string $editor_id Unique editor identifier, e.g. 'content'.
*/
$mce_buttons = apply_filters( 'teeny_mce_buttons', $mce_buttons, $editor_id );
$mce_buttons_2 = array();
$mce_buttons_3 = array();
$mce_buttons_4 = array();
} else {
$mce_buttons = array(
'formatselect',
'bold',
'italic',
'bullist',
'numlist',
'blockquote',
'alignleft',
'aligncenter',
'alignright',
'link',
'wp_more',
'spellchecker',
);
if ( ! wp_is_mobile() ) {
if ( $set['_content_editor_dfw'] ) {
$mce_buttons[] = 'wp_adv';
$mce_buttons[] = 'dfw';
} else {
$mce_buttons[] = 'fullscreen';
$mce_buttons[] = 'wp_adv';
}
} else {
$mce_buttons[] = 'wp_adv';
}
/**
* Filters the first-row list of TinyMCE buttons (Visual tab).
*
* @since 2.0.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mce_buttons First-row list of buttons.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$mce_buttons = apply_filters( 'mce_buttons', $mce_buttons, $editor_id );
$mce_buttons_2 = array(
'strikethrough',
'hr',
'forecolor',
'pastetext',
'removeformat',
'charmap',
'outdent',
'indent',
'undo',
'redo',
);
if ( ! wp_is_mobile() ) {
$mce_buttons_2[] = 'wp_help';
}
/**
* Filters the second-row list of TinyMCE buttons (Visual tab).
*
* @since 2.0.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mce_buttons_2 Second-row list of buttons.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$mce_buttons_2 = apply_filters( 'mce_buttons_2', $mce_buttons_2, $editor_id );
/**
* Filters the third-row list of TinyMCE buttons (Visual tab).
*
* @since 2.0.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mce_buttons_3 Third-row list of buttons.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$mce_buttons_3 = apply_filters( 'mce_buttons_3', array(), $editor_id );
/**
* Filters the fourth-row list of TinyMCE buttons (Visual tab).
*
* @since 2.5.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mce_buttons_4 Fourth-row list of buttons.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$mce_buttons_4 = apply_filters( 'mce_buttons_4', array(), $editor_id );
}
$body_class = $editor_id;
$post = get_post();
if ( $post ) {
$body_class .= ' post-type-' . sanitize_html_class( $post->post_type ) . ' post-status-' . sanitize_html_class( $post->post_status );
if ( post_type_supports( $post->post_type, 'post-formats' ) ) {
$post_format = get_post_format( $post );
if ( $post_format && ! is_wp_error( $post_format ) ) {
$body_class .= ' post-format-' . sanitize_html_class( $post_format );
} else {
$body_class .= ' post-format-standard';
}
}
$page_template = get_page_template_slug( $post );
if ( false !== $page_template ) {
$page_template = empty( $page_template ) ? 'default' : str_replace( '.', '-', basename( $page_template, '.php' ) );
$body_class .= ' page-template-' . sanitize_html_class( $page_template );
}
}
$body_class .= ' locale-' . sanitize_html_class( strtolower( str_replace( '_', '-', get_user_locale() ) ) );
if ( ! empty( $set['tinymce']['body_class'] ) ) {
$body_class .= ' ' . $set['tinymce']['body_class'];
unset( $set['tinymce']['body_class'] );
}
$mceInit = array(
'selector' => "#$editor_id",
'wpautop' => (bool) $set['wpautop'],
'indent' => ! $set['wpautop'],
'toolbar1' => implode( ',', $mce_buttons ),
'toolbar2' => implode( ',', $mce_buttons_2 ),
'toolbar3' => implode( ',', $mce_buttons_3 ),
'toolbar4' => implode( ',', $mce_buttons_4 ),
'tabfocus_elements' => $set['tabfocus_elements'],
'body_class' => $body_class,
);
// Merge with the first part of the init array.
$mceInit = array_merge( self::$first_init, $mceInit );
if ( is_array( $set['tinymce'] ) ) {
$mceInit = array_merge( $mceInit, $set['tinymce'] );
}
/*
* For people who really REALLY know what they're doing with TinyMCE
* You can modify $mceInit to add, remove, change elements of the config
* before tinyMCE.init. Setting "valid_elements", "invalid_elements"
* and "extended_valid_elements" can be done through this filter. Best
* is to use the default cleanup by not specifying valid_elements,
* as TinyMCE checks against the full set of HTML 5.0 elements and attributes.
*/
if ( $set['teeny'] ) {
/**
* Filters the teenyMCE config before init.
*
* @since 2.7.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mceInit An array with teenyMCE config.
* @param string $editor_id Unique editor identifier, e.g. 'content'.
*/
$mceInit = apply_filters( 'teeny_mce_before_init', $mceInit, $editor_id );
} else {
/**
* Filters the TinyMCE config before init.
*
* @since 2.5.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mceInit An array with TinyMCE config.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$mceInit = apply_filters( 'tiny_mce_before_init', $mceInit, $editor_id );
}
if ( empty( $mceInit['toolbar3'] ) && ! empty( $mceInit['toolbar4'] ) ) {
$mceInit['toolbar3'] = $mceInit['toolbar4'];
$mceInit['toolbar4'] = '';
}
self::$mce_settings[ $editor_id ] = $mceInit;
} // End if self::$this_tinymce.
}
```
[apply\_filters( 'disable\_captions', bool $bool )](../../hooks/disable_captions)
Filters whether to disable captions.
[apply\_filters( 'mce\_buttons', array $mce\_buttons, string $editor\_id )](../../hooks/mce_buttons)
Filters the first-row list of TinyMCE buttons (Visual tab).
[apply\_filters( 'mce\_buttons\_2', array $mce\_buttons\_2, string $editor\_id )](../../hooks/mce_buttons_2)
Filters the second-row list of TinyMCE buttons (Visual tab).
[apply\_filters( 'mce\_buttons\_3', array $mce\_buttons\_3, string $editor\_id )](../../hooks/mce_buttons_3)
Filters the third-row list of TinyMCE buttons (Visual tab).
[apply\_filters( 'mce\_buttons\_4', array $mce\_buttons\_4, string $editor\_id )](../../hooks/mce_buttons_4)
Filters the fourth-row list of TinyMCE buttons (Visual tab).
[apply\_filters( 'mce\_css', string $stylesheets )](../../hooks/mce_css)
Filters the comma-delimited list of stylesheets to load in TinyMCE.
[apply\_filters( 'mce\_external\_languages', array $translations, string $editor\_id )](../../hooks/mce_external_languages)
Filters the translations loaded for external TinyMCE 3.x plugins.
[apply\_filters( 'mce\_external\_plugins', array $external\_plugins, string $editor\_id )](../../hooks/mce_external_plugins)
Filters the list of TinyMCE external plugins.
[apply\_filters( 'quicktags\_settings', array $qtInit, string $editor\_id )](../../hooks/quicktags_settings)
Filters the Quicktags settings.
[apply\_filters( 'teeny\_mce\_before\_init', array $mceInit, string $editor\_id )](../../hooks/teeny_mce_before_init)
Filters the teenyMCE config before init.
[apply\_filters( 'teeny\_mce\_buttons', array $mce\_buttons, string $editor\_id )](../../hooks/teeny_mce_buttons)
Filters the list of teenyMCE buttons (Text tab).
[apply\_filters( 'teeny\_mce\_plugins', array $plugins, string $editor\_id )](../../hooks/teeny_mce_plugins)
Filters the list of teenyMCE plugins.
[apply\_filters( 'tiny\_mce\_before\_init', array $mceInit, string $editor\_id )](../../hooks/tiny_mce_before_init)
Filters the TinyMCE config before init.
[apply\_filters( 'tiny\_mce\_plugins', array $plugins, string $editor\_id )](../../hooks/tiny_mce_plugins)
Filters the list of default TinyMCE plugins.
| Uses | Description |
| --- | --- |
| [\_WP\_Editors::get\_baseurl()](get_baseurl) wp-includes/class-wp-editor.php | Returns the TinyMCE base URL. |
| [get\_page\_template\_slug()](../../functions/get_page_template_slug) wp-includes/post-template.php | Gets the specific template filename for a given post. |
| [\_WP\_Editors::default\_settings()](default_settings) wp-includes/class-wp-editor.php | Returns the default TinyMCE settings. |
| [get\_user\_locale()](../../functions/get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| [get\_post\_format()](../../functions/get_post_format) wp-includes/post-formats.php | Retrieve the format slug for a post |
| [get\_editor\_stylesheets()](../../functions/get_editor_stylesheets) wp-includes/theme.php | Retrieves any registered editor stylesheet URLs. |
| [sanitize\_html\_class()](../../functions/sanitize_html_class) wp-includes/formatting.php | Sanitizes an HTML classname to ensure it only contains valid characters. |
| [wp\_is\_mobile()](../../functions/wp_is_mobile) wp-includes/vars.php | Test if the current browser runs on a mobile device (smart phone, tablet, etc.) |
| [\_WP\_Editors::get\_mce\_locale()](get_mce_locale) wp-includes/class-wp-editor.php | Returns the TinyMCE locale. |
| [set\_url\_scheme()](../../functions/set_url_scheme) wp-includes/link-template.php | Sets the scheme for a URL. |
| [content\_url()](../../functions/content_url) wp-includes/link-template.php | Retrieves the URL to the content directory. |
| [post\_type\_supports()](../../functions/post_type_supports) wp-includes/post.php | Checks a post type’s support for a given feature. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| [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. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [wp\_tiny\_mce()](../../functions/wp_tiny_mce) wp-admin/includes/deprecated.php | Outputs the TinyMCE editor. |
| [\_WP\_Editors::editor()](editor) wp-includes/class-wp-editor.php | Outputs the HTML for a single instance of the editor. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
| programming_docs |
wordpress _WP_Editors::_parse_init( array $init ): string \_WP\_Editors::\_parse\_init( array $init ): 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.
`$init` array Required string
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
private static function _parse_init( $init ) {
$options = '';
foreach ( $init as $key => $value ) {
if ( is_bool( $value ) ) {
$val = $value ? 'true' : 'false';
$options .= $key . ':' . $val . ',';
continue;
} elseif ( ! empty( $value ) && is_string( $value ) && (
( '{' === $value[0] && '}' === $value[ strlen( $value ) - 1 ] ) ||
( '[' === $value[0] && ']' === $value[ strlen( $value ) - 1 ] ) ||
preg_match( '/^\(?function ?\(/', $value ) ) ) {
$options .= $key . ':' . $value . ',';
continue;
}
$options .= $key . ':"' . $value . '",';
}
return '{' . trim( $options, ' ,' ) . '}';
}
```
| Used By | Description |
| --- | --- |
| [\_WP\_Editors::print\_default\_editor\_scripts()](print_default_editor_scripts) wp-includes/class-wp-editor.php | Print (output) all editor scripts and default settings. |
| [\_WP\_Editors::editor\_js()](editor_js) wp-includes/class-wp-editor.php | Print (output) the TinyMCE configuration and initialization scripts. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress _WP_Editors::get_mce_locale(): string \_WP\_Editors::get\_mce\_locale(): string
=========================================
Returns the TinyMCE locale.
string
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function get_mce_locale() {
if ( empty( self::$mce_locale ) ) {
$mce_locale = get_user_locale();
self::$mce_locale = empty( $mce_locale ) ? 'en' : strtolower( substr( $mce_locale, 0, 2 ) ); // ISO 639-1.
}
return self::$mce_locale;
}
```
| Uses | Description |
| --- | --- |
| [get\_user\_locale()](../../functions/get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| Used By | Description |
| --- | --- |
| [\_WP\_Editors::default\_settings()](default_settings) wp-includes/class-wp-editor.php | Returns the default TinyMCE settings. |
| [\_WP\_Editors::editor\_settings()](editor_settings) wp-includes/class-wp-editor.php | |
| [\_WP\_Editors::wp\_mce\_translation()](wp_mce_translation) wp-includes/class-wp-editor.php | Translates the default TinyMCE strings and returns them as JSON encoded object ready to be loaded with tinymce.addI18n(), or as JS snippet that should run after tinymce.js is loaded. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress _WP_Editors::get_baseurl(): string \_WP\_Editors::get\_baseurl(): string
=====================================
Returns the TinyMCE base URL.
string
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function get_baseurl() {
if ( empty( self::$baseurl ) ) {
self::$baseurl = includes_url( 'js/tinymce' );
}
return self::$baseurl;
}
```
| Uses | Description |
| --- | --- |
| [includes\_url()](../../functions/includes_url) wp-includes/link-template.php | Retrieves the URL to the includes directory. |
| Used By | Description |
| --- | --- |
| [\_WP\_Editors::print\_default\_editor\_scripts()](print_default_editor_scripts) wp-includes/class-wp-editor.php | Print (output) all editor scripts and default settings. |
| [\_WP\_Editors::editor\_settings()](editor_settings) wp-includes/class-wp-editor.php | |
| [\_WP\_Editors::wp\_mce\_translation()](wp_mce_translation) wp-includes/class-wp-editor.php | Translates the default TinyMCE strings and returns them as JSON encoded object ready to be loaded with tinymce.addI18n(), or as JS snippet that should run after tinymce.js is loaded. |
| [\_WP\_Editors::editor\_js()](editor_js) wp-includes/class-wp-editor.php | Print (output) the TinyMCE configuration and initialization scripts. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress _WP_Editors::wp_mce_translation( string $mce_locale = '', bool $json_only = false ): string \_WP\_Editors::wp\_mce\_translation( string $mce\_locale = '', bool $json\_only = false ): string
=================================================================================================
Translates the default TinyMCE strings and returns them as JSON encoded object ready to be loaded with tinymce.addI18n(), or as JS snippet that should run after tinymce.js is loaded.
`$mce_locale` string Optional The locale used for the editor. Default: `''`
`$json_only` bool Optional Whether to include the JavaScript calls to tinymce.addI18n() and tinymce.ScriptLoader.markDone(). Default: `false`
string Translation object, JSON encoded.
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function wp_mce_translation( $mce_locale = '', $json_only = false ) {
if ( ! $mce_locale ) {
$mce_locale = self::get_mce_locale();
}
$mce_translation = self::get_translation();
foreach ( $mce_translation as $name => $value ) {
if ( is_array( $value ) ) {
$mce_translation[ $name ] = $value[0];
}
}
/**
* Filters translated strings prepared for TinyMCE.
*
* @since 3.9.0
*
* @param array $mce_translation Key/value pairs of strings.
* @param string $mce_locale Locale.
*/
$mce_translation = apply_filters( 'wp_mce_translation', $mce_translation, $mce_locale );
foreach ( $mce_translation as $key => $value ) {
// Remove strings that are not translated.
if ( $key === $value ) {
unset( $mce_translation[ $key ] );
continue;
}
if ( false !== strpos( $value, '&' ) ) {
$mce_translation[ $key ] = html_entity_decode( $value, ENT_QUOTES, 'UTF-8' );
}
}
// Set direction.
if ( is_rtl() ) {
$mce_translation['_dir'] = 'rtl';
}
if ( $json_only ) {
return wp_json_encode( $mce_translation );
}
$baseurl = self::get_baseurl();
return "tinymce.addI18n( '$mce_locale', " . wp_json_encode( $mce_translation ) . ");\n" .
"tinymce.ScriptLoader.markDone( '$baseurl/langs/$mce_locale.js' );\n";
}
```
[apply\_filters( 'wp\_mce\_translation', array $mce\_translation, string $mce\_locale )](../../hooks/wp_mce_translation)
Filters translated strings prepared for TinyMCE.
| Uses | Description |
| --- | --- |
| [\_WP\_Editors::get\_mce\_locale()](get_mce_locale) wp-includes/class-wp-editor.php | Returns the TinyMCE locale. |
| [\_WP\_Editors::get\_baseurl()](get_baseurl) wp-includes/class-wp-editor.php | Returns the TinyMCE base URL. |
| [\_WP\_Editors::get\_translation()](get_translation) wp-includes/class-wp-editor.php | |
| [is\_rtl()](../../functions/is_rtl) wp-includes/l10n.php | Determines whether the current locale is right-to-left (RTL). |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [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\_Editors::print\_tinymce\_scripts()](print_tinymce_scripts) wp-includes/class-wp-editor.php | Print (output) the main TinyMCE scripts. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress _WP_Editors::enqueue_default_editor() \_WP\_Editors::enqueue\_default\_editor()
=========================================
Enqueue all editor scripts.
For use when the editor is going to be initialized after page load.
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function enqueue_default_editor() {
// We are past the point where scripts can be enqueued properly.
if ( did_action( 'wp_enqueue_editor' ) ) {
return;
}
self::enqueue_scripts( true );
// Also add wp-includes/css/editor.css.
wp_enqueue_style( 'editor-buttons' );
if ( is_admin() ) {
add_action( 'admin_print_footer_scripts', array( __CLASS__, 'force_uncompressed_tinymce' ), 1 );
add_action( 'admin_print_footer_scripts', array( __CLASS__, 'print_default_editor_scripts' ), 45 );
} else {
add_action( 'wp_print_footer_scripts', array( __CLASS__, 'force_uncompressed_tinymce' ), 1 );
add_action( 'wp_print_footer_scripts', array( __CLASS__, 'print_default_editor_scripts' ), 45 );
}
}
```
| 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\_enqueue\_style()](../../functions/wp_enqueue_style) wp-includes/functions.wp-styles.php | Enqueue a CSS stylesheet. |
| [\_WP\_Editors::enqueue\_scripts()](enqueue_scripts) wp-includes/class-wp-editor.php | |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Used By | Description |
| --- | --- |
| [wp\_enqueue\_editor()](../../functions/wp_enqueue_editor) wp-includes/general-template.php | Outputs the editor scripts, stylesheets, and default settings. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress _WP_Editors::editor( string $content, string $editor_id, array $settings = array() ) \_WP\_Editors::editor( string $content, string $editor\_id, array $settings = array() )
=======================================================================================
Outputs the HTML for a single instance of the editor.
`$content` string Required Initial content for the editor. `$editor_id` string Required HTML ID for the textarea and TinyMCE and Quicktags instances.
Should not contain square brackets. `$settings` array Optional See [\_WP\_Editors::parse\_settings()](parse_settings) for description. More Arguments from \_WP\_Editors::parse\_settings( ... $settings ) Array of editor arguments.
* `wpautop`boolWhether to use [wpautop()](../../functions/wpautop) . Default true.
* `media_buttons`boolWhether to show the Add Media/other media buttons.
* `default_editor`stringWhen both TinyMCE and Quicktags are used, set which editor is shown on page load. Default empty.
* `drag_drop_upload`boolWhether to enable drag & drop on the editor uploading. Default false.
Requires the media modal.
* `textarea_name`stringGive the textarea a unique name here. Square brackets can be used here. Default $editor\_id.
* `textarea_rows`intNumber rows in the editor textarea. Default 20.
* `tabindex`string|intTabindex value to use. Default empty.
* `tabfocus_elements`stringThe previous and next element ID to move the focus to when pressing the Tab key in TinyMCE. Default `':prev,:next'`.
* `editor_css`stringIntended for extra styles for both Visual and Text editors.
Should include `<style>` tags, and can use "scoped". Default empty.
* `editor_class`stringExtra classes to add to the editor textarea element. Default empty.
* `teeny`boolWhether to output the minimal editor config. Examples include Press This and the Comment editor. Default false.
* `dfw`boolDeprecated in 4.1. Unused.
* `tinymce`bool|arrayWhether to load TinyMCE. Can be used to pass settings directly to TinyMCE using an array. Default true.
* `quicktags`bool|arrayWhether to load Quicktags. Can be used to pass settings directly to Quicktags using an array. Default true.
Default: `array()`
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function editor( $content, $editor_id, $settings = array() ) {
$set = self::parse_settings( $editor_id, $settings );
$editor_class = ' class="' . trim( esc_attr( $set['editor_class'] ) . ' wp-editor-area' ) . '"';
$tabindex = $set['tabindex'] ? ' tabindex="' . (int) $set['tabindex'] . '"' : '';
$default_editor = 'html';
$buttons = '';
$autocomplete = '';
$editor_id_attr = esc_attr( $editor_id );
if ( $set['drag_drop_upload'] ) {
self::$drag_drop_upload = true;
}
if ( ! empty( $set['editor_height'] ) ) {
$height = ' style="height: ' . (int) $set['editor_height'] . 'px"';
} else {
$height = ' rows="' . (int) $set['textarea_rows'] . '"';
}
if ( ! current_user_can( 'upload_files' ) ) {
$set['media_buttons'] = false;
}
if ( self::$this_tinymce ) {
$autocomplete = ' autocomplete="off"';
if ( self::$this_quicktags ) {
$default_editor = $set['default_editor'] ? $set['default_editor'] : wp_default_editor();
// 'html' is used for the "Text" editor tab.
if ( 'html' !== $default_editor ) {
$default_editor = 'tinymce';
}
$buttons .= '<button type="button" id="' . $editor_id_attr . '-tmce" class="wp-switch-editor switch-tmce"' .
' data-wp-editor-id="' . $editor_id_attr . '">' . _x( 'Visual', 'Name for the Visual editor tab' ) . "</button>\n";
$buttons .= '<button type="button" id="' . $editor_id_attr . '-html" class="wp-switch-editor switch-html"' .
' data-wp-editor-id="' . $editor_id_attr . '">' . _x( 'Text', 'Name for the Text editor tab (formerly HTML)' ) . "</button>\n";
} else {
$default_editor = 'tinymce';
}
}
$switch_class = 'html' === $default_editor ? 'html-active' : 'tmce-active';
$wrap_class = 'wp-core-ui wp-editor-wrap ' . $switch_class;
if ( $set['_content_editor_dfw'] ) {
$wrap_class .= ' has-dfw';
}
echo '<div id="wp-' . $editor_id_attr . '-wrap" class="' . $wrap_class . '">';
if ( self::$editor_buttons_css ) {
wp_print_styles( 'editor-buttons' );
self::$editor_buttons_css = false;
}
if ( ! empty( $set['editor_css'] ) ) {
echo $set['editor_css'] . "\n";
}
if ( ! empty( $buttons ) || $set['media_buttons'] ) {
echo '<div id="wp-' . $editor_id_attr . '-editor-tools" class="wp-editor-tools hide-if-no-js">';
if ( $set['media_buttons'] ) {
self::$has_medialib = true;
if ( ! function_exists( 'media_buttons' ) ) {
require ABSPATH . 'wp-admin/includes/media.php';
}
echo '<div id="wp-' . $editor_id_attr . '-media-buttons" class="wp-media-buttons">';
/**
* Fires after the default media button(s) are displayed.
*
* @since 2.5.0
*
* @param string $editor_id Unique editor identifier, e.g. 'content'.
*/
do_action( 'media_buttons', $editor_id );
echo "</div>\n";
}
echo '<div class="wp-editor-tabs">' . $buttons . "</div>\n";
echo "</div>\n";
}
$quicktags_toolbar = '';
if ( self::$this_quicktags ) {
if ( 'content' === $editor_id && ! empty( $GLOBALS['current_screen'] ) && 'post' === $GLOBALS['current_screen']->base ) {
$toolbar_id = 'ed_toolbar';
} else {
$toolbar_id = 'qt_' . $editor_id_attr . '_toolbar';
}
$quicktags_toolbar = '<div id="' . $toolbar_id . '" class="quicktags-toolbar hide-if-no-js"></div>';
}
/**
* Filters the HTML markup output that displays the editor.
*
* @since 2.1.0
*
* @param string $output Editor's HTML markup.
*/
$the_editor = apply_filters(
'the_editor',
'<div id="wp-' . $editor_id_attr . '-editor-container" class="wp-editor-container">' .
$quicktags_toolbar .
'<textarea' . $editor_class . $height . $tabindex . $autocomplete . ' cols="40" name="' . esc_attr( $set['textarea_name'] ) . '" ' .
'id="' . $editor_id_attr . '">%s</textarea></div>'
);
// Prepare the content for the Visual or Text editor, only when TinyMCE is used (back-compat).
if ( self::$this_tinymce ) {
add_filter( 'the_editor_content', 'format_for_editor', 10, 2 );
}
/**
* Filters the default editor content.
*
* @since 2.1.0
*
* @param string $content Default editor content.
* @param string $default_editor The default editor for the current user.
* Either 'html' or 'tinymce'.
*/
$content = apply_filters( 'the_editor_content', $content, $default_editor );
// Remove the filter as the next editor on the same page may not need it.
if ( self::$this_tinymce ) {
remove_filter( 'the_editor_content', 'format_for_editor' );
}
// Back-compat for the `htmledit_pre` and `richedit_pre` filters.
if ( 'html' === $default_editor && has_filter( 'htmledit_pre' ) ) {
/** This filter is documented in wp-includes/deprecated.php */
$content = apply_filters_deprecated( 'htmledit_pre', array( $content ), '4.3.0', 'format_for_editor' );
} elseif ( 'tinymce' === $default_editor && has_filter( 'richedit_pre' ) ) {
/** This filter is documented in wp-includes/deprecated.php */
$content = apply_filters_deprecated( 'richedit_pre', array( $content ), '4.3.0', 'format_for_editor' );
}
if ( false !== stripos( $content, 'textarea' ) ) {
$content = preg_replace( '%</textarea%i', '</textarea', $content );
}
printf( $the_editor, $content );
echo "\n</div>\n\n";
self::editor_settings( $editor_id, $set );
}
```
[apply\_filters( 'htmledit\_pre', string $output )](../../hooks/htmledit_pre)
Filters the text before it is formatted for the HTML editor.
[do\_action( 'media\_buttons', string $editor\_id )](../../hooks/media_buttons)
Fires after the default media button(s) are displayed.
[apply\_filters( 'richedit\_pre', string $output )](../../hooks/richedit_pre)
Filters text returned for the rich text editor.
[apply\_filters( 'the\_editor', string $output )](../../hooks/the_editor)
Filters the HTML markup output that displays the editor.
[apply\_filters( 'the\_editor\_content', string $content, string $default\_editor )](../../hooks/the_editor_content)
Filters the default editor content.
| Uses | Description |
| --- | --- |
| [stripos()](../../functions/stripos) wp-includes/class-pop3.php | |
| [apply\_filters\_deprecated()](../../functions/apply_filters_deprecated) wp-includes/plugin.php | Fires functions attached to a deprecated filter hook. |
| [wp\_default\_editor()](../../functions/wp_default_editor) wp-includes/general-template.php | Finds out which editor should be displayed by default. |
| [wp\_print\_styles()](../../functions/wp_print_styles) wp-includes/functions.wp-styles.php | Display styles that are in the $handles queue. |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| [has\_filter()](../../functions/has_filter) wp-includes/plugin.php | Checks if any filter has been registered for a hook. |
| [\_WP\_Editors::editor\_settings()](editor_settings) wp-includes/class-wp-editor.php | |
| [\_WP\_Editors::parse\_settings()](parse_settings) wp-includes/class-wp-editor.php | Parse default arguments for the editor instance. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_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. |
| [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. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Used By | Description |
| --- | --- |
| [wp\_editor()](../../functions/wp_editor) wp-includes/general-template.php | Renders an editor. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
| programming_docs |
wordpress _WP_Editors::wp_fullscreen_html() \_WP\_Editors::wp\_fullscreen\_html()
=====================================
This method has been deprecated.
Outputs the HTML for distraction-free writing mode.
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function wp_fullscreen_html() {
_deprecated_function( __FUNCTION__, '4.3.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.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | This method has been deprecated. |
| [3.2.0](https://developer.wordpress.org/reference/since/3.2.0/) | Introduced. |
wordpress _WP_Editors::print_default_editor_scripts() \_WP\_Editors::print\_default\_editor\_scripts()
================================================
Print (output) all editor scripts and default settings.
For use when the editor is going to be initialized after page load.
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function print_default_editor_scripts() {
$user_can_richedit = user_can_richedit();
if ( $user_can_richedit ) {
$settings = self::default_settings();
$settings['toolbar1'] = 'bold,italic,bullist,numlist,link';
$settings['wpautop'] = false;
$settings['indent'] = true;
$settings['elementpath'] = false;
if ( is_rtl() ) {
$settings['directionality'] = 'rtl';
}
/*
* In production all plugins are loaded (they are in wp-editor.js.gz).
* The 'wpview', 'wpdialogs', and 'media' TinyMCE plugins are not initialized by default.
* Can be added from js by using the 'wp-before-tinymce-init' event.
*/
$settings['plugins'] = implode(
',',
array(
'charmap',
'colorpicker',
'hr',
'lists',
'paste',
'tabfocus',
'textcolor',
'fullscreen',
'wordpress',
'wpautoresize',
'wpeditimage',
'wpemoji',
'wpgallery',
'wplink',
'wptextpattern',
)
);
$settings = self::_parse_init( $settings );
} else {
$settings = '{}';
}
?>
<script type="text/javascript">
window.wp = window.wp || {};
window.wp.editor = window.wp.editor || {};
window.wp.editor.getDefaultSettings = function() {
return {
tinymce: <?php echo $settings; ?>,
quicktags: {
buttons: 'strong,em,link,ul,ol,li,code'
}
};
};
<?php
if ( $user_can_richedit ) {
$suffix = SCRIPT_DEBUG ? '' : '.min';
$baseurl = self::get_baseurl();
?>
var tinyMCEPreInit = {
baseURL: "<?php echo $baseurl; ?>",
suffix: "<?php echo $suffix; ?>",
mceInit: {},
qtInit: {},
load_ext: function(url,lang){var sl=tinymce.ScriptLoader;sl.markDone(url+'/langs/'+lang+'.js');sl.markDone(url+'/langs/'+lang+'_dlg.js');}
};
<?php
}
?>
</script>
<?php
if ( $user_can_richedit ) {
self::print_tinymce_scripts();
}
/**
* Fires when the editor scripts are loaded for later initialization,
* after all scripts and settings are printed.
*
* @since 4.8.0
*/
do_action( 'print_default_editor_scripts' );
self::wp_link_dialog();
}
```
[do\_action( 'print\_default\_editor\_scripts' )](../../hooks/print_default_editor_scripts)
Fires when the editor scripts are loaded for later initialization, after all scripts and settings are printed.
| Uses | Description |
| --- | --- |
| [\_WP\_Editors::print\_tinymce\_scripts()](print_tinymce_scripts) wp-includes/class-wp-editor.php | Print (output) the main TinyMCE scripts. |
| [\_WP\_Editors::default\_settings()](default_settings) wp-includes/class-wp-editor.php | Returns the default TinyMCE settings. |
| [\_WP\_Editors::get\_baseurl()](get_baseurl) wp-includes/class-wp-editor.php | Returns the TinyMCE base URL. |
| [user\_can\_richedit()](../../functions/user_can_richedit) wp-includes/general-template.php | Determines whether the user can access the visual editor. |
| [is\_rtl()](../../functions/is_rtl) wp-includes/l10n.php | Determines whether the current locale is right-to-left (RTL). |
| [\_WP\_Editors::wp\_link\_dialog()](wp_link_dialog) wp-includes/class-wp-editor.php | Dialog for internal linking. |
| [\_WP\_Editors::\_parse\_init()](_parse_init) wp-includes/class-wp-editor.php | |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress _WP_Editors::default_settings(): array \_WP\_Editors::default\_settings(): 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.
Returns the default TinyMCE settings.
Doesn’t include plugins, buttons, editor selector.
array
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
private static function default_settings() {
global $tinymce_version;
$shortcut_labels = array();
foreach ( self::get_translation() as $name => $value ) {
if ( is_array( $value ) ) {
$shortcut_labels[ $name ] = $value[1];
}
}
$settings = array(
'theme' => 'modern',
'skin' => 'lightgray',
'language' => self::get_mce_locale(),
'formats' => '{' .
'alignleft: [' .
'{selector: "p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li", styles: {textAlign:"left"}},' .
'{selector: "img,table,dl.wp-caption", classes: "alignleft"}' .
'],' .
'aligncenter: [' .
'{selector: "p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li", styles: {textAlign:"center"}},' .
'{selector: "img,table,dl.wp-caption", classes: "aligncenter"}' .
'],' .
'alignright: [' .
'{selector: "p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li", styles: {textAlign:"right"}},' .
'{selector: "img,table,dl.wp-caption", classes: "alignright"}' .
'],' .
'strikethrough: {inline: "del"}' .
'}',
'relative_urls' => false,
'remove_script_host' => false,
'convert_urls' => false,
'browser_spellcheck' => true,
'fix_list_elements' => true,
'entities' => '38,amp,60,lt,62,gt',
'entity_encoding' => 'raw',
'keep_styles' => false,
'cache_suffix' => 'wp-mce-' . $tinymce_version,
'resize' => 'vertical',
'menubar' => false,
'branding' => false,
// Limit the preview styles in the menu/toolbar.
'preview_styles' => 'font-family font-size font-weight font-style text-decoration text-transform',
'end_container_on_empty_block' => true,
'wpeditimage_html5_captions' => true,
'wp_lang_attr' => get_bloginfo( 'language' ),
'wp_keep_scroll_position' => false,
'wp_shortcut_labels' => wp_json_encode( $shortcut_labels ),
);
$suffix = SCRIPT_DEBUG ? '' : '.min';
$version = 'ver=' . get_bloginfo( 'version' );
// Default stylesheets.
$settings['content_css'] = includes_url( "css/dashicons$suffix.css?$version" ) . ',' .
includes_url( "js/tinymce/skins/wordpress/wp-content.css?$version" );
return $settings;
}
```
| Uses | Description |
| --- | --- |
| [\_WP\_Editors::get\_mce\_locale()](get_mce_locale) wp-includes/class-wp-editor.php | Returns the TinyMCE locale. |
| [\_WP\_Editors::get\_translation()](get_translation) wp-includes/class-wp-editor.php | |
| [includes\_url()](../../functions/includes_url) wp-includes/link-template.php | Retrieves the URL to the includes directory. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| Used By | Description |
| --- | --- |
| [\_WP\_Editors::print\_default\_editor\_scripts()](print_default_editor_scripts) wp-includes/class-wp-editor.php | Print (output) all editor scripts and default settings. |
| [\_WP\_Editors::editor\_settings()](editor_settings) wp-includes/class-wp-editor.php | |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress _WP_Editors::get_translation(): array \_WP\_Editors::get\_translation(): 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.
array
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
private static function get_translation() {
if ( empty( self::$translation ) ) {
self::$translation = array(
// Default TinyMCE strings.
'New document' => __( 'New document' ),
'Formats' => _x( 'Formats', 'TinyMCE' ),
'Headings' => _x( 'Headings', 'TinyMCE' ),
'Heading 1' => array( __( 'Heading 1' ), 'access1' ),
'Heading 2' => array( __( 'Heading 2' ), 'access2' ),
'Heading 3' => array( __( 'Heading 3' ), 'access3' ),
'Heading 4' => array( __( 'Heading 4' ), 'access4' ),
'Heading 5' => array( __( 'Heading 5' ), 'access5' ),
'Heading 6' => array( __( 'Heading 6' ), 'access6' ),
/* translators: Block tags. */
'Blocks' => _x( 'Blocks', 'TinyMCE' ),
'Paragraph' => array( __( 'Paragraph' ), 'access7' ),
'Blockquote' => array( __( 'Blockquote' ), 'accessQ' ),
'Div' => _x( 'Div', 'HTML tag' ),
'Pre' => _x( 'Pre', 'HTML tag' ),
'Preformatted' => _x( 'Preformatted', 'HTML tag' ),
'Address' => _x( 'Address', 'HTML tag' ),
'Inline' => _x( 'Inline', 'HTML elements' ),
'Underline' => array( __( 'Underline' ), 'metaU' ),
'Strikethrough' => array( __( 'Strikethrough' ), 'accessD' ),
'Subscript' => __( 'Subscript' ),
'Superscript' => __( 'Superscript' ),
'Clear formatting' => __( 'Clear formatting' ),
'Bold' => array( __( 'Bold' ), 'metaB' ),
'Italic' => array( __( 'Italic' ), 'metaI' ),
'Code' => array( __( 'Code' ), 'accessX' ),
'Source code' => __( 'Source code' ),
'Font Family' => __( 'Font Family' ),
'Font Sizes' => __( 'Font Sizes' ),
'Align center' => array( __( 'Align center' ), 'accessC' ),
'Align right' => array( __( 'Align right' ), 'accessR' ),
'Align left' => array( __( 'Align left' ), 'accessL' ),
'Justify' => array( __( 'Justify' ), 'accessJ' ),
'Increase indent' => __( 'Increase indent' ),
'Decrease indent' => __( 'Decrease indent' ),
'Cut' => array( __( 'Cut' ), 'metaX' ),
'Copy' => array( __( 'Copy' ), 'metaC' ),
'Paste' => array( __( 'Paste' ), 'metaV' ),
'Select all' => array( __( 'Select all' ), 'metaA' ),
'Undo' => array( __( 'Undo' ), 'metaZ' ),
'Redo' => array( __( 'Redo' ), 'metaY' ),
'Ok' => __( 'OK' ),
'Cancel' => __( 'Cancel' ),
'Close' => __( 'Close' ),
'Visual aids' => __( 'Visual aids' ),
'Bullet list' => array( __( 'Bulleted list' ), 'accessU' ),
'Numbered list' => array( __( 'Numbered list' ), 'accessO' ),
'Square' => _x( 'Square', 'list style' ),
'Default' => _x( 'Default', 'list style' ),
'Circle' => _x( 'Circle', 'list style' ),
'Disc' => _x( 'Disc', 'list style' ),
'Lower Greek' => _x( 'Lower Greek', 'list style' ),
'Lower Alpha' => _x( 'Lower Alpha', 'list style' ),
'Upper Alpha' => _x( 'Upper Alpha', 'list style' ),
'Upper Roman' => _x( 'Upper Roman', 'list style' ),
'Lower Roman' => _x( 'Lower Roman', 'list style' ),
// Anchor plugin.
'Name' => _x( 'Name', 'Name of link anchor (TinyMCE)' ),
'Anchor' => _x( 'Anchor', 'Link anchor (TinyMCE)' ),
'Anchors' => _x( 'Anchors', 'Link anchors (TinyMCE)' ),
'Id should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores.' =>
__( 'Id should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores.' ),
'Id' => _x( 'Id', 'Id for link anchor (TinyMCE)' ),
// Fullpage plugin.
'Document properties' => __( 'Document properties' ),
'Robots' => __( 'Robots' ),
'Title' => __( 'Title' ),
'Keywords' => __( 'Keywords' ),
'Encoding' => __( 'Encoding' ),
'Description' => __( 'Description' ),
'Author' => __( 'Author' ),
// Media, image plugins.
'Image' => __( 'Image' ),
'Insert/edit image' => array( __( 'Insert/edit image' ), 'accessM' ),
'General' => __( 'General' ),
'Advanced' => __( 'Advanced' ),
'Source' => __( 'Source' ),
'Border' => __( 'Border' ),
'Constrain proportions' => __( 'Constrain proportions' ),
'Vertical space' => __( 'Vertical space' ),
'Image description' => __( 'Image description' ),
'Style' => __( 'Style' ),
'Dimensions' => __( 'Dimensions' ),
'Insert image' => __( 'Insert image' ),
'Date/time' => __( 'Date/time' ),
'Insert date/time' => __( 'Insert date/time' ),
'Table of Contents' => __( 'Table of Contents' ),
'Insert/Edit code sample' => __( 'Insert/edit code sample' ),
'Language' => __( 'Language' ),
'Media' => __( 'Media' ),
'Insert/edit media' => __( 'Insert/edit media' ),
'Poster' => __( 'Poster' ),
'Alternative source' => __( 'Alternative source' ),
'Paste your embed code below:' => __( 'Paste your embed code below:' ),
'Insert video' => __( 'Insert video' ),
'Embed' => __( 'Embed' ),
// Each of these have a corresponding plugin.
'Special character' => __( 'Special character' ),
'Right to left' => _x( 'Right to left', 'editor button' ),
'Left to right' => _x( 'Left to right', 'editor button' ),
'Emoticons' => __( 'Emoticons' ),
'Nonbreaking space' => __( 'Nonbreaking space' ),
'Page break' => __( 'Page break' ),
'Paste as text' => __( 'Paste as text' ),
'Preview' => __( 'Preview' ),
'Print' => __( 'Print' ),
'Save' => __( 'Save' ),
'Fullscreen' => __( 'Fullscreen' ),
'Horizontal line' => __( 'Horizontal line' ),
'Horizontal space' => __( 'Horizontal space' ),
'Restore last draft' => __( 'Restore last draft' ),
'Insert/edit link' => array( __( 'Insert/edit link' ), 'metaK' ),
'Remove link' => array( __( 'Remove link' ), 'accessS' ),
// Link plugin.
'Link' => __( 'Link' ),
'Insert link' => __( 'Insert link' ),
'Target' => __( 'Target' ),
'New window' => __( 'New window' ),
'Text to display' => __( 'Text to display' ),
'Url' => __( 'URL' ),
'The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?' =>
__( 'The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?' ),
'The URL you entered seems to be an external link. Do you want to add the required http:// prefix?' =>
__( 'The URL you entered seems to be an external link. Do you want to add the required http:// prefix?' ),
'Color' => __( 'Color' ),
'Custom color' => __( 'Custom color' ),
'Custom...' => _x( 'Custom...', 'label for custom color' ), // No ellipsis.
'No color' => __( 'No color' ),
'R' => _x( 'R', 'Short for red in RGB' ),
'G' => _x( 'G', 'Short for green in RGB' ),
'B' => _x( 'B', 'Short for blue in RGB' ),
// Spelling, search/replace plugins.
'Could not find the specified string.' => __( 'Could not find the specified string.' ),
'Replace' => _x( 'Replace', 'find/replace' ),
'Next' => _x( 'Next', 'find/replace' ),
/* translators: Previous. */
'Prev' => _x( 'Prev', 'find/replace' ),
'Whole words' => _x( 'Whole words', 'find/replace' ),
'Find and replace' => __( 'Find and replace' ),
'Replace with' => _x( 'Replace with', 'find/replace' ),
'Find' => _x( 'Find', 'find/replace' ),
'Replace all' => _x( 'Replace all', 'find/replace' ),
'Match case' => __( 'Match case' ),
'Spellcheck' => __( 'Check Spelling' ),
'Finish' => _x( 'Finish', 'spellcheck' ),
'Ignore all' => _x( 'Ignore all', 'spellcheck' ),
'Ignore' => _x( 'Ignore', 'spellcheck' ),
'Add to Dictionary' => __( 'Add to Dictionary' ),
// TinyMCE tables.
'Insert table' => __( 'Insert table' ),
'Delete table' => __( 'Delete table' ),
'Table properties' => __( 'Table properties' ),
'Row properties' => __( 'Table row properties' ),
'Cell properties' => __( 'Table cell properties' ),
'Border color' => __( 'Border color' ),
'Row' => __( 'Row' ),
'Rows' => __( 'Rows' ),
'Column' => __( 'Column' ),
'Cols' => __( 'Columns' ),
'Cell' => _x( 'Cell', 'table cell' ),
'Header cell' => __( 'Header cell' ),
'Header' => _x( 'Header', 'table header' ),
'Body' => _x( 'Body', 'table body' ),
'Footer' => _x( 'Footer', 'table footer' ),
'Insert row before' => __( 'Insert row before' ),
'Insert row after' => __( 'Insert row after' ),
'Insert column before' => __( 'Insert column before' ),
'Insert column after' => __( 'Insert column after' ),
'Paste row before' => __( 'Paste table row before' ),
'Paste row after' => __( 'Paste table row after' ),
'Delete row' => __( 'Delete row' ),
'Delete column' => __( 'Delete column' ),
'Cut row' => __( 'Cut table row' ),
'Copy row' => __( 'Copy table row' ),
'Merge cells' => __( 'Merge table cells' ),
'Split cell' => __( 'Split table cell' ),
'Height' => __( 'Height' ),
'Width' => __( 'Width' ),
'Caption' => __( 'Caption' ),
'Alignment' => __( 'Alignment' ),
'H Align' => _x( 'H Align', 'horizontal table cell alignment' ),
'Left' => __( 'Left' ),
'Center' => __( 'Center' ),
'Right' => __( 'Right' ),
'None' => _x( 'None', 'table cell alignment attribute' ),
'V Align' => _x( 'V Align', 'vertical table cell alignment' ),
'Top' => __( 'Top' ),
'Middle' => __( 'Middle' ),
'Bottom' => __( 'Bottom' ),
'Row group' => __( 'Row group' ),
'Column group' => __( 'Column group' ),
'Row type' => __( 'Row type' ),
'Cell type' => __( 'Cell type' ),
'Cell padding' => __( 'Cell padding' ),
'Cell spacing' => __( 'Cell spacing' ),
'Scope' => _x( 'Scope', 'table cell scope attribute' ),
'Insert template' => _x( 'Insert template', 'TinyMCE' ),
'Templates' => _x( 'Templates', 'TinyMCE' ),
'Background color' => __( 'Background color' ),
'Text color' => __( 'Text color' ),
'Show blocks' => _x( 'Show blocks', 'editor button' ),
'Show invisible characters' => __( 'Show invisible characters' ),
/* translators: Word count. */
'Words: {0}' => sprintf( __( 'Words: %s' ), '{0}' ),
'Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.' =>
__( 'Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.' ) . "\n\n" .
__( 'If you are looking to paste rich content from Microsoft Word, try turning this option off. The editor will clean up text pasted from Word automatically.' ),
'Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help' =>
__( 'Rich Text Area. Press Alt-Shift-H for help.' ),
'Rich Text Area. Press Control-Option-H for help.' => __( 'Rich Text Area. Press Control-Option-H for help.' ),
'You have unsaved changes are you sure you want to navigate away?' =>
__( 'The changes you made will be lost if you navigate away from this page.' ),
'Your browser doesn\'t support direct access to the clipboard. Please use the Ctrl+X/C/V keyboard shortcuts instead.' =>
__( 'Your browser does not support direct access to the clipboard. Please use keyboard shortcuts or your browser’s edit menu instead.' ),
// TinyMCE menus.
'Insert' => _x( 'Insert', 'TinyMCE menu' ),
'File' => _x( 'File', 'TinyMCE menu' ),
'Edit' => _x( 'Edit', 'TinyMCE menu' ),
'Tools' => _x( 'Tools', 'TinyMCE menu' ),
'View' => _x( 'View', 'TinyMCE menu' ),
'Table' => _x( 'Table', 'TinyMCE menu' ),
'Format' => _x( 'Format', 'TinyMCE menu' ),
// WordPress strings.
'Toolbar Toggle' => array( __( 'Toolbar Toggle' ), 'accessZ' ),
'Insert Read More tag' => array( __( 'Insert Read More tag' ), 'accessT' ),
'Insert Page Break tag' => array( __( 'Insert Page Break tag' ), 'accessP' ),
'Read more...' => __( 'Read more...' ), // Title on the placeholder inside the editor (no ellipsis).
'Distraction-free writing mode' => array( __( 'Distraction-free writing mode' ), 'accessW' ),
'No alignment' => __( 'No alignment' ), // Tooltip for the 'alignnone' button in the image toolbar.
'Remove' => __( 'Remove' ), // Tooltip for the 'remove' button in the image toolbar.
'Edit|button' => __( 'Edit' ), // Tooltip for the 'edit' button in the image toolbar.
'Paste URL or type to search' => __( 'Paste URL or type to search' ), // Placeholder for the inline link dialog.
'Apply' => __( 'Apply' ), // Tooltip for the 'apply' button in the inline link dialog.
'Link options' => __( 'Link options' ), // Tooltip for the 'link options' button in the inline link dialog.
'Visual' => _x( 'Visual', 'Name for the Visual editor tab' ), // Editor switch tab label.
'Text' => _x( 'Text', 'Name for the Text editor tab (formerly HTML)' ), // Editor switch tab label.
'Add Media' => array( __( 'Add Media' ), 'accessM' ), // Tooltip for the 'Add Media' button in the block editor Classic block.
// Shortcuts help modal.
'Keyboard Shortcuts' => array( __( 'Keyboard Shortcuts' ), 'accessH' ),
'Classic Block Keyboard Shortcuts' => __( 'Classic Block Keyboard Shortcuts' ),
'Default shortcuts,' => __( 'Default shortcuts,' ),
'Additional shortcuts,' => __( 'Additional shortcuts,' ),
'Focus shortcuts:' => __( 'Focus shortcuts:' ),
'Inline toolbar (when an image, link or preview is selected)' => __( 'Inline toolbar (when an image, link or preview is selected)' ),
'Editor menu (when enabled)' => __( 'Editor menu (when enabled)' ),
'Editor toolbar' => __( 'Editor toolbar' ),
'Elements path' => __( 'Elements path' ),
'Ctrl + Alt + letter:' => __( 'Ctrl + Alt + letter:' ),
'Shift + Alt + letter:' => __( 'Shift + Alt + letter:' ),
'Cmd + letter:' => __( 'Cmd + letter:' ),
'Ctrl + letter:' => __( 'Ctrl + letter:' ),
'Letter' => __( 'Letter' ),
'Action' => __( 'Action' ),
'Warning: the link has been inserted but may have errors. Please test it.' => __( 'Warning: the link has been inserted but may have errors. Please test it.' ),
'To move focus to other buttons use Tab or the arrow keys. To return focus to the editor press Escape or use one of the buttons.' =>
__( 'To move focus to other buttons use Tab or the arrow keys. To return focus to the editor press Escape or use one of the buttons.' ),
'When starting a new paragraph with one of these formatting shortcuts followed by a space, the formatting will be applied automatically. Press Backspace or Escape to undo.' =>
__( 'When starting a new paragraph with one of these formatting shortcuts followed by a space, the formatting will be applied automatically. Press Backspace or Escape to undo.' ),
'The following formatting shortcuts are replaced when pressing Enter. Press Escape or the Undo button to undo.' =>
__( 'The following formatting shortcuts are replaced when pressing Enter. Press Escape or the Undo button to undo.' ),
'The next group of formatting shortcuts are applied as you type or when you insert them around plain text in the same paragraph. Press Escape or the Undo button to undo.' =>
__( 'The next group of formatting shortcuts are applied as you type or when you insert them around plain text in the same paragraph. Press Escape or the Undo button to undo.' ),
);
}
/*
Imagetools plugin (not included):
'Edit image' => __( 'Edit image' ),
'Image options' => __( 'Image options' ),
'Back' => __( 'Back' ),
'Invert' => __( 'Invert' ),
'Flip horizontally' => __( 'Flip horizontal' ),
'Flip vertically' => __( 'Flip vertical' ),
'Crop' => __( 'Crop' ),
'Orientation' => __( 'Orientation' ),
'Resize' => __( 'Resize' ),
'Rotate clockwise' => __( 'Rotate right' ),
'Rotate counterclockwise' => __( 'Rotate left' ),
'Sharpen' => __( 'Sharpen' ),
'Brightness' => __( 'Brightness' ),
'Color levels' => __( 'Color levels' ),
'Contrast' => __( 'Contrast' ),
'Gamma' => __( 'Gamma' ),
'Zoom in' => __( 'Zoom in' ),
'Zoom out' => __( 'Zoom out' ),
*/
return self::$translation;
}
```
| 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. |
| Used By | Description |
| --- | --- |
| [\_WP\_Editors::default\_settings()](default_settings) wp-includes/class-wp-editor.php | Returns the default TinyMCE settings. |
| [\_WP\_Editors::wp\_mce\_translation()](wp_mce_translation) wp-includes/class-wp-editor.php | Translates the default TinyMCE strings and returns them as JSON encoded object ready to be loaded with tinymce.addI18n(), or as JS snippet that should run after tinymce.js is loaded. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress _WP_Editors::editor_js() \_WP\_Editors::editor\_js()
===========================
Print (output) the TinyMCE configuration and initialization scripts.
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function editor_js() {
global $tinymce_version;
$tmce_on = ! empty( self::$mce_settings );
$mceInit = '';
$qtInit = '';
if ( $tmce_on ) {
foreach ( self::$mce_settings as $editor_id => $init ) {
$options = self::_parse_init( $init );
$mceInit .= "'$editor_id':{$options},";
}
$mceInit = '{' . trim( $mceInit, ',' ) . '}';
} else {
$mceInit = '{}';
}
if ( ! empty( self::$qt_settings ) ) {
foreach ( self::$qt_settings as $editor_id => $init ) {
$options = self::_parse_init( $init );
$qtInit .= "'$editor_id':{$options},";
}
$qtInit = '{' . trim( $qtInit, ',' ) . '}';
} else {
$qtInit = '{}';
}
$ref = array(
'plugins' => implode( ',', self::$plugins ),
'theme' => 'modern',
'language' => self::$mce_locale,
);
$suffix = SCRIPT_DEBUG ? '' : '.min';
$baseurl = self::get_baseurl();
$version = 'ver=' . $tinymce_version;
/**
* Fires immediately before the TinyMCE settings are printed.
*
* @since 3.2.0
*
* @param array $mce_settings TinyMCE settings array.
*/
do_action( 'before_wp_tiny_mce', self::$mce_settings );
?>
<script type="text/javascript">
tinyMCEPreInit = {
baseURL: "<?php echo $baseurl; ?>",
suffix: "<?php echo $suffix; ?>",
<?php
if ( self::$drag_drop_upload ) {
echo 'dragDropUpload: true,';
}
?>
mceInit: <?php echo $mceInit; ?>,
qtInit: <?php echo $qtInit; ?>,
ref: <?php echo self::_parse_init( $ref ); ?>,
load_ext: function(url,lang){var sl=tinymce.ScriptLoader;sl.markDone(url+'/langs/'+lang+'.js');sl.markDone(url+'/langs/'+lang+'_dlg.js');}
};
</script>
<?php
if ( $tmce_on ) {
self::print_tinymce_scripts();
if ( self::$ext_plugins ) {
// Load the old-format English strings to prevent unsightly labels in old style popups.
echo "<script type='text/javascript' src='{$baseurl}/langs/wp-langs-en.js?$version'></script>\n";
}
}
/**
* Fires after tinymce.js is loaded, but before any TinyMCE editor
* instances are created.
*
* @since 3.9.0
*
* @param array $mce_settings TinyMCE settings array.
*/
do_action( 'wp_tiny_mce_init', self::$mce_settings );
?>
<script type="text/javascript">
<?php
if ( self::$ext_plugins ) {
echo self::$ext_plugins . "\n";
}
if ( ! is_admin() ) {
echo 'var ajaxurl = "' . admin_url( 'admin-ajax.php', 'relative' ) . '";';
}
?>
( function() {
var initialized = [];
var initialize = function() {
var init, id, inPostbox, $wrap;
var readyState = document.readyState;
if ( readyState !== 'complete' && readyState !== 'interactive' ) {
return;
}
for ( id in tinyMCEPreInit.mceInit ) {
if ( initialized.indexOf( id ) > -1 ) {
continue;
}
init = tinyMCEPreInit.mceInit[id];
$wrap = tinymce.$( '#wp-' + id + '-wrap' );
inPostbox = $wrap.parents( '.postbox' ).length > 0;
if (
! init.wp_skip_init &&
( $wrap.hasClass( 'tmce-active' ) || ! tinyMCEPreInit.qtInit.hasOwnProperty( id ) ) &&
( readyState === 'complete' || ( ! inPostbox && readyState === 'interactive' ) )
) {
tinymce.init( init );
initialized.push( id );
if ( ! window.wpActiveEditor ) {
window.wpActiveEditor = id;
}
}
}
}
if ( typeof tinymce !== 'undefined' ) {
if ( tinymce.Env.ie && tinymce.Env.ie < 11 ) {
tinymce.$( '.wp-editor-wrap ' ).removeClass( 'tmce-active' ).addClass( 'html-active' );
} else {
if ( document.readyState === 'complete' ) {
initialize();
} else {
document.addEventListener( 'readystatechange', initialize );
}
}
}
if ( typeof quicktags !== 'undefined' ) {
for ( id in tinyMCEPreInit.qtInit ) {
quicktags( tinyMCEPreInit.qtInit[id] );
if ( ! window.wpActiveEditor ) {
window.wpActiveEditor = id;
}
}
}
}());
</script>
<?php
if ( in_array( 'wplink', self::$plugins, true ) || in_array( 'link', self::$qt_buttons, true ) ) {
self::wp_link_dialog();
}
/**
* Fires after any core TinyMCE editor instances are created.
*
* @since 3.2.0
*
* @param array $mce_settings TinyMCE settings array.
*/
do_action( 'after_wp_tiny_mce', self::$mce_settings );
}
```
[do\_action( 'after\_wp\_tiny\_mce', array $mce\_settings )](../../hooks/after_wp_tiny_mce)
Fires after any core TinyMCE editor instances are created.
[do\_action( 'before\_wp\_tiny\_mce', array $mce\_settings )](../../hooks/before_wp_tiny_mce)
Fires immediately before the TinyMCE settings are printed.
[do\_action( 'wp\_tiny\_mce\_init', array $mce\_settings )](../../hooks/wp_tiny_mce_init)
Fires after tinymce.js is loaded, but before any TinyMCE editor instances are created.
| Uses | Description |
| --- | --- |
| [\_WP\_Editors::print\_tinymce\_scripts()](print_tinymce_scripts) wp-includes/class-wp-editor.php | Print (output) the main TinyMCE scripts. |
| [\_WP\_Editors::get\_baseurl()](get_baseurl) wp-includes/class-wp-editor.php | Returns the TinyMCE base URL. |
| [\_WP\_Editors::wp\_link\_dialog()](wp_link_dialog) wp-includes/class-wp-editor.php | Dialog for internal linking. |
| [\_WP\_Editors::\_parse\_init()](_parse_init) wp-includes/class-wp-editor.php | |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [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_Editors::__construct() \_WP\_Editors::\_\_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.
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
private function __construct() {}
```
wordpress _WP_Editors::enqueue_scripts( bool $default_scripts = false ) \_WP\_Editors::enqueue\_scripts( bool $default\_scripts = false )
=================================================================
`$default_scripts` bool Optional Whether default scripts should be enqueued. Default: `false`
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function enqueue_scripts( $default_scripts = false ) {
if ( $default_scripts || self::$has_tinymce ) {
wp_enqueue_script( 'editor' );
}
if ( $default_scripts || self::$has_quicktags ) {
wp_enqueue_script( 'quicktags' );
wp_enqueue_style( 'buttons' );
}
if ( $default_scripts || in_array( 'wplink', self::$plugins, true ) || in_array( 'link', self::$qt_buttons, true ) ) {
wp_enqueue_script( 'wplink' );
wp_enqueue_script( 'jquery-ui-autocomplete' );
}
if ( self::$has_medialib ) {
add_thickbox();
wp_enqueue_script( 'media-upload' );
wp_enqueue_script( 'wp-embed' );
} elseif ( $default_scripts ) {
wp_enqueue_script( 'media-upload' );
}
/**
* Fires when scripts and styles are enqueued for the editor.
*
* @since 3.9.0
*
* @param array $to_load An array containing boolean values whether TinyMCE
* and Quicktags are being loaded.
*/
do_action(
'wp_enqueue_editor',
array(
'tinymce' => ( $default_scripts || self::$has_tinymce ),
'quicktags' => ( $default_scripts || self::$has_quicktags ),
)
);
}
```
[do\_action( 'wp\_enqueue\_editor', array $to\_load )](../../hooks/wp_enqueue_editor)
Fires when scripts and styles are enqueued for the editor.
| Uses | Description |
| --- | --- |
| [add\_thickbox()](../../functions/add_thickbox) wp-includes/general-template.php | Enqueues the default ThickBox js and css. |
| [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. |
| [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\_Editors::enqueue\_default\_editor()](enqueue_default_editor) wp-includes/class-wp-editor.php | Enqueue all editor scripts. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress _WP_Editors::wp_link_dialog() \_WP\_Editors::wp\_link\_dialog()
=================================
Dialog for internal linking.
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function wp_link_dialog() {
// Run once.
if ( self::$link_dialog_printed ) {
return;
}
self::$link_dialog_printed = true;
// `display: none` is required here, see #WP27605.
?>
<div id="wp-link-backdrop" style="display: none"></div>
<div id="wp-link-wrap" class="wp-core-ui" style="display: none" role="dialog" aria-labelledby="link-modal-title">
<form id="wp-link" tabindex="-1">
<?php wp_nonce_field( 'internal-linking', '_ajax_linking_nonce', false ); ?>
<h1 id="link-modal-title"><?php _e( 'Insert/edit link' ); ?></h1>
<button type="button" id="wp-link-close"><span class="screen-reader-text"><?php _e( 'Close' ); ?></span></button>
<div id="link-selector">
<div id="link-options">
<p class="howto" id="wplink-enter-url"><?php _e( 'Enter the destination URL' ); ?></p>
<div>
<label><span><?php _e( 'URL' ); ?></span>
<input id="wp-link-url" type="text" aria-describedby="wplink-enter-url" /></label>
</div>
<div class="wp-link-text-field">
<label><span><?php _e( 'Link Text' ); ?></span>
<input id="wp-link-text" type="text" /></label>
</div>
<div class="link-target">
<label><span></span>
<input type="checkbox" id="wp-link-target" /> <?php _e( 'Open link in a new tab' ); ?></label>
</div>
</div>
<p class="howto" id="wplink-link-existing-content"><?php _e( 'Or link to existing content' ); ?></p>
<div id="search-panel">
<div class="link-search-wrapper">
<label>
<span class="search-label"><?php _e( 'Search' ); ?></span>
<input type="search" id="wp-link-search" class="link-search-field" autocomplete="off" aria-describedby="wplink-link-existing-content" />
<span class="spinner"></span>
</label>
</div>
<div id="search-results" class="query-results" tabindex="0">
<ul></ul>
<div class="river-waiting">
<span class="spinner"></span>
</div>
</div>
<div id="most-recent-results" class="query-results" tabindex="0">
<div class="query-notice" id="query-notice-message">
<em class="query-notice-default"><?php _e( 'No search term specified. Showing recent items.' ); ?></em>
<em class="query-notice-hint screen-reader-text"><?php _e( 'Search or use up and down arrow keys to select an item.' ); ?></em>
</div>
<ul></ul>
<div class="river-waiting">
<span class="spinner"></span>
</div>
</div>
</div>
</div>
<div class="submitbox">
<div id="wp-link-cancel">
<button type="button" class="button"><?php _e( 'Cancel' ); ?></button>
</div>
<div id="wp-link-update">
<input type="submit" value="<?php esc_attr_e( 'Add Link' ); ?>" class="button button-primary" id="wp-link-submit" name="wp-link-submit">
</div>
</div>
</form>
</div>
<?php
}
```
| Uses | Description |
| --- | --- |
| [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. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| Used By | Description |
| --- | --- |
| [\_WP\_Editors::print\_default\_editor\_scripts()](print_default_editor_scripts) wp-includes/class-wp-editor.php | Print (output) all editor scripts and default settings. |
| [\_WP\_Editors::editor\_js()](editor_js) wp-includes/class-wp-editor.php | Print (output) the TinyMCE configuration and initialization scripts. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress _WP_Editors::force_uncompressed_tinymce() \_WP\_Editors::force\_uncompressed\_tinymce()
=============================================
Force uncompressed TinyMCE when a custom theme has been defined.
The compressed TinyMCE file cannot deal with custom themes, so this makes sure that we use the uncompressed TinyMCE file if a theme is defined.
Even if we are on a production environment.
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function force_uncompressed_tinymce() {
$has_custom_theme = false;
foreach ( self::$mce_settings as $init ) {
if ( ! empty( $init['theme_url'] ) ) {
$has_custom_theme = true;
break;
}
}
if ( ! $has_custom_theme ) {
return;
}
$wp_scripts = wp_scripts();
$wp_scripts->remove( 'wp-tinymce' );
wp_register_tinymce_scripts( $wp_scripts, true );
}
```
| Uses | Description |
| --- | --- |
| [wp\_register\_tinymce\_scripts()](../../functions/wp_register_tinymce_scripts) wp-includes/script-loader.php | Registers TinyMCE scripts. |
| [wp\_scripts()](../../functions/wp_scripts) wp-includes/functions.wp-scripts.php | Initialize $wp\_scripts if it has not been set. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress _WP_Editors::parse_settings( string $editor_id, array $settings ): array \_WP\_Editors::parse\_settings( string $editor\_id, array $settings ): array
============================================================================
Parse default arguments for the editor instance.
`$editor_id` string Required HTML ID for the textarea and TinyMCE and Quicktags instances.
Should not contain square brackets. `$settings` array Required Array of editor arguments.
* `wpautop`boolWhether to use [wpautop()](../../functions/wpautop) . Default true.
* `media_buttons`boolWhether to show the Add Media/other media buttons.
* `default_editor`stringWhen both TinyMCE and Quicktags are used, set which editor is shown on page load. Default empty.
* `drag_drop_upload`boolWhether to enable drag & drop on the editor uploading. Default false.
Requires the media modal.
* `textarea_name`stringGive the textarea a unique name here. Square brackets can be used here. Default $editor\_id.
* `textarea_rows`intNumber rows in the editor textarea. Default 20.
* `tabindex`string|intTabindex value to use. Default empty.
* `tabfocus_elements`stringThe previous and next element ID to move the focus to when pressing the Tab key in TinyMCE. Default `':prev,:next'`.
* `editor_css`stringIntended for extra styles for both Visual and Text editors.
Should include `<style>` tags, and can use "scoped". Default empty.
* `editor_class`stringExtra classes to add to the editor textarea element. Default empty.
* `teeny`boolWhether to output the minimal editor config. Examples include Press This and the Comment editor. Default false.
* `dfw`boolDeprecated in 4.1. Unused.
* `tinymce`bool|arrayWhether to load TinyMCE. Can be used to pass settings directly to TinyMCE using an array. Default true.
* `quicktags`bool|arrayWhether to load Quicktags. Can be used to pass settings directly to Quicktags using an array. Default true.
array Parsed arguments array.
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function parse_settings( $editor_id, $settings ) {
/**
* Filters the wp_editor() settings.
*
* @since 4.0.0
*
* @see _WP_Editors::parse_settings()
*
* @param array $settings Array of editor arguments.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$settings = apply_filters( 'wp_editor_settings', $settings, $editor_id );
$set = wp_parse_args(
$settings,
array(
// Disable autop if the current post has blocks in it.
'wpautop' => ! has_blocks(),
'media_buttons' => true,
'default_editor' => '',
'drag_drop_upload' => false,
'textarea_name' => $editor_id,
'textarea_rows' => 20,
'tabindex' => '',
'tabfocus_elements' => ':prev,:next',
'editor_css' => '',
'editor_class' => '',
'teeny' => false,
'_content_editor_dfw' => false,
'tinymce' => true,
'quicktags' => true,
)
);
self::$this_tinymce = ( $set['tinymce'] && user_can_richedit() );
if ( self::$this_tinymce ) {
if ( false !== strpos( $editor_id, '[' ) ) {
self::$this_tinymce = false;
_deprecated_argument( 'wp_editor()', '3.9.0', 'TinyMCE editor IDs cannot have brackets.' );
}
}
self::$this_quicktags = (bool) $set['quicktags'];
if ( self::$this_tinymce ) {
self::$has_tinymce = true;
}
if ( self::$this_quicktags ) {
self::$has_quicktags = true;
}
if ( empty( $set['editor_height'] ) ) {
return $set;
}
if ( 'content' === $editor_id && empty( $set['tinymce']['wp_autoresize_on'] ) ) {
// A cookie (set when a user resizes the editor) overrides the height.
$cookie = (int) get_user_setting( 'ed_size' );
if ( $cookie ) {
$set['editor_height'] = $cookie;
}
}
if ( $set['editor_height'] < 50 ) {
$set['editor_height'] = 50;
} elseif ( $set['editor_height'] > 5000 ) {
$set['editor_height'] = 5000;
}
return $set;
}
```
[apply\_filters( 'wp\_editor\_settings', array $settings, string $editor\_id )](../../hooks/wp_editor_settings)
Filters the [wp\_editor()](../../functions/wp_editor) settings.
| Uses | Description |
| --- | --- |
| [has\_blocks()](../../functions/has_blocks) wp-includes/blocks.php | Determines whether a post or content string has blocks. |
| [user\_can\_richedit()](../../functions/user_can_richedit) wp-includes/general-template.php | Determines whether the user can access the visual editor. |
| [get\_user\_setting()](../../functions/get_user_setting) wp-includes/option.php | Retrieves user interface setting value based on setting name. |
| [\_deprecated\_argument()](../../functions/_deprecated_argument) wp-includes/functions.php | Marks a function argument as deprecated and inform when it has been used. |
| [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\_tiny\_mce()](../../functions/wp_tiny_mce) wp-admin/includes/deprecated.php | Outputs the TinyMCE editor. |
| [\_WP\_Editors::editor()](editor) wp-includes/class-wp-editor.php | Outputs the HTML for a single instance of the editor. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
| programming_docs |
wordpress _WP_Editors::print_tinymce_scripts() \_WP\_Editors::print\_tinymce\_scripts()
========================================
Print (output) the main TinyMCE scripts.
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function print_tinymce_scripts() {
global $concatenate_scripts;
if ( self::$tinymce_scripts_printed ) {
return;
}
self::$tinymce_scripts_printed = true;
if ( ! isset( $concatenate_scripts ) ) {
script_concat_settings();
}
wp_print_scripts( array( 'wp-tinymce' ) );
echo "<script type='text/javascript'>\n" . self::wp_mce_translation() . "</script>\n";
}
```
| Uses | Description |
| --- | --- |
| [wp\_print\_scripts()](../../functions/wp_print_scripts) wp-includes/functions.wp-scripts.php | Prints scripts in document head that are in the $handles queue. |
| [script\_concat\_settings()](../../functions/script_concat_settings) wp-includes/script-loader.php | Determines the concatenation and compression settings for scripts and styles. |
| [\_WP\_Editors::wp\_mce\_translation()](wp_mce_translation) wp-includes/class-wp-editor.php | Translates the default TinyMCE strings and returns them as JSON encoded object ready to be loaded with tinymce.addI18n(), or as JS snippet that should run after tinymce.js is loaded. |
| Used By | Description |
| --- | --- |
| [\_WP\_Editors::print\_default\_editor\_scripts()](print_default_editor_scripts) wp-includes/class-wp-editor.php | Print (output) all editor scripts and default settings. |
| [\_WP\_Editors::editor\_js()](editor_js) wp-includes/class-wp-editor.php | Print (output) the TinyMCE configuration and initialization scripts. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress _WP_Editors::wp_link_query( array $args = array() ): array|false \_WP\_Editors::wp\_link\_query( array $args = array() ): array|false
====================================================================
Performs post queries for internal linking.
`$args` array Optional Accepts `'pagenum'` and `'s'` (search) arguments. Default: `array()`
array|false $results { An array of associative arrays of query results, false if there are none.
@type array ...$0 { @type int $ID Post ID.
@type string $title The trimmed, escaped post title.
@type string $permalink Post permalink.
@type string $info A `'Y/m/d'`-formatted date for `'post'` post type, the `'singular_name'` post type label otherwise.
} }
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
public static function wp_link_query( $args = array() ) {
$pts = get_post_types( array( 'public' => true ), 'objects' );
$pt_names = array_keys( $pts );
$query = array(
'post_type' => $pt_names,
'suppress_filters' => true,
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
'post_status' => 'publish',
'posts_per_page' => 20,
);
$args['pagenum'] = isset( $args['pagenum'] ) ? absint( $args['pagenum'] ) : 1;
if ( isset( $args['s'] ) ) {
$query['s'] = $args['s'];
}
$query['offset'] = $args['pagenum'] > 1 ? $query['posts_per_page'] * ( $args['pagenum'] - 1 ) : 0;
/**
* Filters the link query arguments.
*
* Allows modification of the link query arguments before querying.
*
* @see WP_Query for a full list of arguments
*
* @since 3.7.0
*
* @param array $query An array of WP_Query arguments.
*/
$query = apply_filters( 'wp_link_query_args', $query );
// Do main query.
$get_posts = new WP_Query;
$posts = $get_posts->query( $query );
// Build results.
$results = array();
foreach ( $posts as $post ) {
if ( 'post' === $post->post_type ) {
$info = mysql2date( __( 'Y/m/d' ), $post->post_date );
} else {
$info = $pts[ $post->post_type ]->labels->singular_name;
}
$results[] = array(
'ID' => $post->ID,
'title' => trim( esc_html( strip_tags( get_the_title( $post ) ) ) ),
'permalink' => get_permalink( $post->ID ),
'info' => $info,
);
}
/**
* Filters the link query results.
*
* Allows modification of the returned link query results.
*
* @since 3.7.0
*
* @see 'wp_link_query_args' filter
*
* @param array $results {
* An array of associative arrays of query results.
*
* @type array ...$0 {
* @type int $ID Post ID.
* @type string $title The trimmed, escaped post title.
* @type string $permalink Post permalink.
* @type string $info A 'Y/m/d'-formatted date for 'post' post type,
* the 'singular_name' post type label otherwise.
* }
* }
* @param array $query An array of WP_Query arguments.
*/
$results = apply_filters( 'wp_link_query', $results, $query );
return ! empty( $results ) ? $results : false;
}
```
[apply\_filters( 'wp\_link\_query', array $results, array $query )](../../hooks/wp_link_query)
Filters the link query results.
[apply\_filters( 'wp\_link\_query\_args', array $query )](../../hooks/wp_link_query_args)
Filters the link query arguments.
| Uses | Description |
| --- | --- |
| [WP\_Query::\_\_construct()](../wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [mysql2date()](../../functions/mysql2date) wp-includes/functions.php | Converts given MySQL date string into a different format. |
| [get\_the\_title()](../../functions/get_the_title) wp-includes/post-template.php | Retrieves the post title. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [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\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| Used By | Description |
| --- | --- |
| [wp\_ajax\_wp\_link\_ajax()](../../functions/wp_ajax_wp_link_ajax) wp-admin/includes/ajax-actions.php | Ajax handler for internal linking. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress wp_atom_server::__callStatic( $name, $arguments ) wp\_atom\_server::\_\_callStatic( $name, $arguments )
=====================================================
File: `wp-includes/pluggable-deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pluggable-deprecated.php/)
```
public static function __callStatic( $name, $arguments ) {
_deprecated_function( __CLASS__ . '::' . $name, '3.5.0', 'the Atom Publishing Protocol plugin' );
}
```
| 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_atom_server::__call( $name, $arguments ) wp\_atom\_server::\_\_call( $name, $arguments )
===============================================
File: `wp-includes/pluggable-deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pluggable-deprecated.php/)
```
public function __call( $name, $arguments ) {
_deprecated_function( __CLASS__ . '::' . $name, '3.5.0', 'the Atom Publishing Protocol plugin' );
}
```
| 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_Customize_Color_Control::content_template() WP\_Customize\_Color\_Control::content\_template()
==================================================
Render a JS template for the content of the color picker control.
File: `wp-includes/customize/class-wp-customize-color-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-color-control.php/)
```
public function content_template() {
?>
<# var defaultValue = '#RRGGBB', defaultValueAttr = '',
isHueSlider = data.mode === 'hue';
if ( data.defaultValue && _.isString( data.defaultValue ) && ! isHueSlider ) {
if ( '#' !== data.defaultValue.substring( 0, 1 ) ) {
defaultValue = '#' + data.defaultValue;
} else {
defaultValue = data.defaultValue;
}
defaultValueAttr = ' data-default-color=' + defaultValue; // Quotes added automatically.
} #>
<# if ( data.label ) { #>
<span class="customize-control-title">{{{ data.label }}}</span>
<# } #>
<# if ( data.description ) { #>
<span class="description customize-control-description">{{{ data.description }}}</span>
<# } #>
<div class="customize-control-content">
<label><span class="screen-reader-text">{{{ data.label }}}</span>
<# if ( isHueSlider ) { #>
<input class="color-picker-hue" type="text" data-type="hue" />
<# } else { #>
<input class="color-picker-hex" type="text" maxlength="7" placeholder="{{ defaultValue }}" {{ defaultValueAttr }} />
<# } #>
</label>
</div>
<?php
}
```
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Color_Control::to_json() WP\_Customize\_Color\_Control::to\_json()
=========================================
Refresh the parameters passed to the JavaScript via JSON.
File: `wp-includes/customize/class-wp-customize-color-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-color-control.php/)
```
public function to_json() {
parent::to_json();
$this->json['statuses'] = $this->statuses;
$this->json['defaultValue'] = $this->setting->default;
$this->json['mode'] = $this->mode;
}
```
| 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.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Color_Control::__construct( WP_Customize_Manager $manager, string $id, array $args = array() ) WP\_Customize\_Color\_Control::\_\_construct( WP\_Customize\_Manager $manager, string $id, array $args = array() )
==================================================================================================================
Constructor.
* [WP\_Customize\_Control::\_\_construct()](../wp_customize_control/__construct)
`$manager` [WP\_Customize\_Manager](../wp_customize_manager) Required Customizer bootstrap instance. `$id` string Required Control ID. `$args` array Optional Arguments to override class property defaults.
See [WP\_Customize\_Control::\_\_construct()](../wp_customize_control/__construct) for information on accepted arguments. More Arguments from WP\_Customize\_Control::\_\_construct( ... $args ) Array of properties for the new Control object.
* `instance_number`intOrder in which this instance was created in relation to other instances.
* `manager`[WP\_Customize\_Manager](../wp_customize_manager)Customizer bootstrap instance.
* `id`stringControl ID.
* `settings`arrayAll settings tied to the control. If undefined, `$id` will be used.
* `setting`stringThe primary setting for the control (if there is one).
Default `'default'`.
* `capability`stringCapability required to use this control. Normally this is empty and the capability is derived from `$settings`.
* `priority`intOrder priority to load the control. Default 10.
* `section`stringSection the control belongs to.
* `label`stringLabel for the control.
* `description`stringDescription for the control.
* `choices`arrayList of choices for `'radio'` or `'select'` type controls, where values are the keys, and labels are the values.
* `input_attrs`arrayList of custom input attributes for control output, where attribute names are the keys and values are the values. Not used for `'checkbox'`, `'radio'`, `'select'`, `'textarea'`, or `'dropdown-pages'` control types.
* `allow_addition`boolShow UI for adding new content, currently only used for the dropdown-pages control. Default false.
* `json`arrayDeprecated. Use [WP\_Customize\_Control::json()](../wp_customize_control/json) instead.
* `type`stringControl type. Core controls include `'text'`, `'checkbox'`, `'textarea'`, `'radio'`, `'select'`, and `'dropdown-pages'`. Additional input types such as `'email'`, `'url'`, `'number'`, `'hidden'`, and `'date'` are supported implicitly. Default `'text'`.
* `active_callback`callableActive callback.
Default: `array()`
File: `wp-includes/customize/class-wp-customize-color-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-color-control.php/)
```
public function __construct( $manager, $id, $args = array() ) {
$this->statuses = array( '' => __( 'Default' ) );
parent::__construct( $manager, $id, $args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::\_\_construct()](../wp_customize_control/__construct) wp-includes/class-wp-customize-control.php | Constructor. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::register\_controls()](../wp_customize_manager/register_controls) wp-includes/class-wp-customize-manager.php | Registers some default controls. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Color_Control::render_content() WP\_Customize\_Color\_Control::render\_content()
================================================
Don’t render the control content from PHP, as it’s rendered via JS on load.
File: `wp-includes/customize/class-wp-customize-color-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-color-control.php/)
```
public function render_content() {}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Color_Control::enqueue() WP\_Customize\_Color\_Control::enqueue()
========================================
Enqueue scripts/styles for the color picker.
File: `wp-includes/customize/class-wp-customize-color-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-color-control.php/)
```
public function enqueue() {
wp_enqueue_script( 'wp-color-picker' );
wp_enqueue_style( 'wp-color-picker' );
}
```
| 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. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Themes_Section::json(): array WP\_Customize\_Themes\_Section::json(): array
=============================================
Get section parameters for JS.
array Exported parameters.
File: `wp-includes/customize/class-wp-customize-themes-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-themes-section.php/)
```
public function json() {
$exported = parent::json();
$exported['action'] = $this->action;
$exported['filter_type'] = $this->filter_type;
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.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Themes_Section::render_template() WP\_Customize\_Themes\_Section::render\_template()
==================================================
Render a themes section as a JS template.
The template is only rendered by PHP once, so all actions are prepared at once on the server side.
File: `wp-includes/customize/class-wp-customize-themes-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-themes-section.php/)
```
protected function render_template() {
?>
<li id="accordion-section-{{ data.id }}" class="theme-section">
<button type="button" class="customize-themes-section-title themes-section-{{ data.id }}">{{ data.title }}</button>
<?php if ( current_user_can( 'install_themes' ) || is_multisite() ) : // @todo Upload support. ?>
<?php endif; ?>
<div class="customize-themes-section themes-section-{{ data.id }} control-section-content themes-php">
<div class="theme-overlay" tabindex="0" role="dialog" aria-label="<?php esc_attr_e( 'Theme Details' ); ?>"></div>
<div class="theme-browser rendered">
<div class="customize-preview-header themes-filter-bar">
<?php $this->filter_bar_content_template(); ?>
</div>
<?php $this->filter_drawer_content_template(); ?>
<div class="error unexpected-error" style="display: none; ">
<p>
<?php
printf(
/* translators: %s: Support forums URL. */
__( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the <a href="%s">support forums</a>.' ),
__( 'https://wordpress.org/support/forums/' )
);
?>
</p>
</div>
<ul class="themes">
</ul>
<p class="no-themes"><?php _e( 'No themes found. Try a different search.' ); ?></p>
<p class="no-themes-local">
<?php
printf(
/* translators: %s: "Search WordPress.org themes" button text. */
__( 'No themes found. Try a different search, or %s.' ),
sprintf( '<button type="button" class="button-link search-dotorg-themes">%s</button>', __( 'Search WordPress.org themes' ) )
);
?>
</p>
<p class="spinner"></p>
</div>
</div>
</li>
<?php
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Themes\_Section::filter\_bar\_content\_template()](filter_bar_content_template) wp-includes/customize/class-wp-customize-themes-section.php | Render the filter bar portion of a themes section as a JS template. |
| [WP\_Customize\_Themes\_Section::filter\_drawer\_content\_template()](filter_drawer_content_template) wp-includes/customize/class-wp-customize-themes-section.php | Render the filter drawer portion of a themes section as a JS template. |
| [esc\_attr\_e()](../../functions/esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [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. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Themes_Section::render() WP\_Customize\_Themes\_Section::render()
========================================
Render the themes section, which behaves like a panel.
File: `wp-includes/customize/class-wp-customize-themes-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-themes-section.php/)
```
*/
public $action = '';
/**
* Theme section filter type.
*
* Determines whether filters are applied to loaded (local) themes or by initiating a new remote query (remote).
* When filtering is local, the initial themes query is not paginated by default.
*
* @since 4.9.0
* @var string
*/
public $filter_type = 'local';
/**
* Get section parameters for JS.
*
* @since 4.9.0
* @return array Exported parameters.
*/
public function json() {
$exported = parent::json();
$exported['action'] = $this->action;
$exported['filter_type'] = $this->filter_type;
return $exported;
}
/**
* Render a themes section as a JS template.
*
* The template is only rendered by PHP once, so all actions are prepared at once on the server side.
*
* @since 4.9.0
*/
protected function render_template() {
?>
<li id="accordion-section-{{ data.id }}" class="theme-section">
<button type="button" class="customize-themes-section-title themes-section-{{ data.id }}">{{ data.title }}</button>
<?php if ( current_user_can( 'install_themes' ) || is_multisite() ) : // @todo Upload support. ?>
<?php endif; ?>
<div class="customize-themes-section themes-section-{{ data.id }} control-section-content themes-php">
<div class="theme-overlay" tabindex="0" role="dialog" aria-label="<?php esc_attr_e( 'Theme Details' ); ?>"></div>
<div class="theme-browser rendered">
<div class="customize-preview-header themes-filter-bar">
<?php $this->filter_bar_content_template(); ?>
</div>
<?php $this->filter_drawer_content_template(); ?>
<div class="error unexpected-error" style="display: none; ">
<p>
```
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Customize_Themes_Section::filter_bar_content_template() WP\_Customize\_Themes\_Section::filter\_bar\_content\_template()
================================================================
Render the filter bar portion of a themes section as a JS template.
The template is only rendered by PHP once, so all actions are prepared at once on the server side.
The filter bar container is rendered by @see `render_template()`.
File: `wp-includes/customize/class-wp-customize-themes-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-themes-section.php/)
```
protected function filter_bar_content_template() {
?>
<button type="button" class="button button-primary customize-section-back customize-themes-mobile-back"><?php _e( 'Go to theme sources' ); ?></button>
<# if ( 'wporg' === data.action ) { #>
<div class="search-form">
<label for="wp-filter-search-input-{{ data.id }}" class="screen-reader-text"><?php _e( 'Search themes…' ); ?></label>
<input type="search" id="wp-filter-search-input-{{ data.id }}" placeholder="<?php esc_attr_e( 'Search themes…' ); ?>" aria-describedby="{{ data.id }}-live-search-desc" class="wp-filter-search">
<div class="search-icon" aria-hidden="true"></div>
<span id="{{ data.id }}-live-search-desc" class="screen-reader-text"><?php _e( 'The search results will be updated as you type.' ); ?></span>
</div>
<button type="button" class="button feature-filter-toggle">
<span class="filter-count-0"><?php _e( 'Filter themes' ); ?></span><span class="filter-count-filters">
<?php
/* translators: %s: Number of filters selected. */
printf( __( 'Filter themes (%s)' ), '<span class="theme-filter-count">0</span>' );
?>
</span>
</button>
<# } else { #>
<div class="themes-filter-container">
<label for="{{ data.id }}-themes-filter" class="screen-reader-text"><?php _e( 'Search themes…' ); ?></label>
<input type="search" id="{{ data.id }}-themes-filter" placeholder="<?php esc_attr_e( 'Search themes…' ); ?>" aria-describedby="{{ data.id }}-live-search-desc" class="wp-filter-search wp-filter-search-themes" />
<div class="search-icon" aria-hidden="true"></div>
<span id="{{ data.id }}-live-search-desc" class="screen-reader-text"><?php _e( 'The search results will be updated as you type.' ); ?></span>
</div>
<# } #>
<div class="filter-themes-count">
<span class="themes-displayed">
<?php
/* translators: %s: Number of themes displayed. */
printf( __( '%s themes' ), '<span class="theme-count">0</span>' );
?>
</span>
</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. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Themes\_Section::render\_template()](render_template) wp-includes/customize/class-wp-customize-themes-section.php | Render a themes section as a JS template. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Themes_Section::filter_drawer_content_template() WP\_Customize\_Themes\_Section::filter\_drawer\_content\_template()
===================================================================
Render the filter drawer portion of a themes section as a JS template.
The filter bar container is rendered by @see `render_template()`.
File: `wp-includes/customize/class-wp-customize-themes-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-themes-section.php/)
```
protected function filter_drawer_content_template() {
// @todo Use the .org API instead of the local core feature list.
// The .org API is currently outdated and will be reconciled when the .org themes directory is next redesigned.
$feature_list = get_theme_feature_list( false );
?>
<# if ( 'wporg' === data.action ) { #>
<div class="filter-drawer filter-details">
<?php foreach ( $feature_list as $feature_name => $features ) : ?>
<fieldset class="filter-group">
<legend><?php echo esc_html( $feature_name ); ?></legend>
<div class="filter-group-feature">
<?php foreach ( $features as $feature => $feature_name ) : ?>
<input type="checkbox" id="filter-id-<?php echo esc_attr( $feature ); ?>" value="<?php echo esc_attr( $feature ); ?>" />
<label for="filter-id-<?php echo esc_attr( $feature ); ?>"><?php echo esc_html( $feature_name ); ?></label>
<?php endforeach; ?>
</div>
</fieldset>
<?php endforeach; ?>
</div>
<# } #>
<?php
}
```
| Uses | Description |
| --- | --- |
| [get\_theme\_feature\_list()](../../functions/get_theme_feature_list) wp-admin/includes/theme.php | Retrieves list of WordPress theme features (aka theme tags). |
| [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. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Themes\_Section::render\_template()](render_template) wp-includes/customize/class-wp-customize-themes-section.php | Render a themes section as a JS template. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress wpdb::set_sql_mode( array $modes = array() ) wpdb::set\_sql\_mode( array $modes = array() )
==============================================
Changes the current SQL mode, and ensures its WordPress compatibility.
If no modes are passed, it will ensure the current MySQL server modes are compatible.
`$modes` array Optional A list of SQL modes to set. Default: `array()`
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function set_sql_mode( $modes = array() ) {
if ( empty( $modes ) ) {
if ( $this->use_mysqli ) {
$res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
} else {
$res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
}
if ( empty( $res ) ) {
return;
}
if ( $this->use_mysqli ) {
$modes_array = mysqli_fetch_array( $res );
if ( empty( $modes_array[0] ) ) {
return;
}
$modes_str = $modes_array[0];
} else {
$modes_str = mysql_result( $res, 0 );
}
if ( empty( $modes_str ) ) {
return;
}
$modes = explode( ',', $modes_str );
}
$modes = array_change_key_case( $modes, CASE_UPPER );
/**
* Filters the list of incompatible SQL modes to exclude.
*
* @since 3.9.0
*
* @param array $incompatible_modes An array of incompatible modes.
*/
$incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
foreach ( $modes as $i => $mode ) {
if ( in_array( $mode, $incompatible_modes, true ) ) {
unset( $modes[ $i ] );
}
}
$modes_str = implode( ',', $modes );
if ( $this->use_mysqli ) {
mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
} else {
mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
}
}
```
[apply\_filters( 'incompatible\_sql\_modes', array $incompatible\_modes )](../../hooks/incompatible_sql_modes)
Filters the list of incompatible SQL modes to exclude.
| 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 |
| --- | --- |
| [wpdb::db\_connect()](db_connect) wp-includes/class-wpdb.php | Connects to and selects database. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress wpdb::timer_start(): true wpdb::timer\_start(): true
==========================
Starts the timer, for debugging purposes.
true
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function timer_start() {
$this->time_start = microtime( true );
return true;
}
```
| Used By | Description |
| --- | --- |
| [wpdb::\_do\_query()](_do_query) wp-includes/class-wpdb.php | Internal function to perform the mysql\_query() call. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wpdb::esc_like( string $text ): string wpdb::esc\_like( string $text ): string
=======================================
First half of escaping for `LIKE` special characters `%` and `_` before preparing for SQL.
Use this only before [wpdb::prepare()](prepare) or [esc\_sql()](../../functions/esc_sql) . Reversing the order is very bad for security.
Example Prepared Statement:
```
$wild = '%';
$find = 'only 43% of planets';
$like = $wild . $wpdb->esc_like( $find ) . $wild;
$sql = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", $like );
```
Example Escape Chain:
```
$sql = esc_sql( $wpdb->esc_like( $input ) );
```
`$text` string Required The raw text to be escaped. The input typed by the user should have no extra or deleted slashes. string Text in the form of a LIKE phrase. The output is not SQL safe.
Call [wpdb::prepare()](prepare) or [wpdb::\_real\_escape()](_real_escape) next.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function esc_like( $text ) {
return addcslashes( $text, '_%\\' );
}
```
| Used By | Description |
| --- | --- |
| [wp\_delete\_attachment\_files()](../../functions/wp_delete_attachment_files) wp-includes/post.php | Deletes all files that belong to the given attachment. |
| [delete\_expired\_transients()](../../functions/delete_expired_transients) wp-includes/option.php | Deletes all expired transients. |
| [WP\_Term\_Query::get\_search\_sql()](../wp_term_query/get_search_sql) wp-includes/class-wp-term-query.php | Used internally to generate a SQL string related to the ‘search’ parameter. |
| [WP\_Term\_Query::get\_terms()](../wp_term_query/get_terms) wp-includes/class-wp-term-query.php | Retrieves the query results. |
| [WP\_Network\_Query::get\_search\_sql()](../wp_network_query/get_search_sql) wp-includes/class-wp-network-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| [WP\_Site\_Query::get\_search\_sql()](../wp_site_query/get_search_sql) wp-includes/class-wp-site-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| [WP\_Meta\_Query::get\_sql\_for\_clause()](../wp_meta_query/get_sql_for_clause) wp-includes/class-wp-meta-query.php | Generate SQL JOIN and WHERE clauses for a first-order query clause. |
| [display\_setup\_form()](../../functions/display_setup_form) wp-admin/install.php | Displays installer setup form. |
| [network\_domain\_check()](../../functions/network_domain_check) wp-admin/includes/network.php | Check for an existing network. |
| [maybe\_create\_table()](../../functions/maybe_create_table) wp-admin/includes/upgrade.php | Creates a table in the database, if it doesn’t already exist. |
| [meta\_form()](../../functions/meta_form) wp-admin/includes/template.php | Prints the form in the Custom Fields meta box. |
| [WP\_MS\_Sites\_List\_Table::prepare\_items()](../wp_ms_sites_list_table/prepare_items) wp-admin/includes/class-wp-ms-sites-list-table.php | Prepares the list of sites for display. |
| [WP\_Query::parse\_search()](../wp_query/parse_search) wp-includes/class-wp-query.php | Generates SQL for the WHERE clause based on passed search terms. |
| [WP\_Query::parse\_search\_order()](../wp_query/parse_search_order) wp-includes/class-wp-query.php | Generates SQL for the ORDER BY condition based on passed search terms. |
| [do\_enclose()](../../functions/do_enclose) wp-includes/functions.php | Checks content for video and audio links to add as enclosures. |
| [WP\_User\_Query::get\_search\_sql()](../wp_user_query/get_search_sql) wp-includes/class-wp-user-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| [count\_users()](../../functions/count_users) wp-includes/user.php | Counts number of users who have each of the user roles. |
| [redirect\_guess\_404\_permalink()](../../functions/redirect_guess_404_permalink) wp-includes/canonical.php | Attempts to guess the correct URL for a 404 request based on query vars. |
| [get\_bookmarks()](../../functions/get_bookmarks) wp-includes/bookmark.php | Retrieves the list of bookmarks. |
| [ms\_not\_installed()](../../functions/ms_not_installed) wp-includes/ms-load.php | Displays a failure message. |
| [WP\_Comment\_Query::get\_search\_sql()](../wp_comment_query/get_search_sql) wp-includes/class-wp-comment-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 wpdb::select( string $db, mysqli|resource $dbh = null ) wpdb::select( string $db, mysqli|resource $dbh = null )
=======================================================
Selects a database using the current or provided database connection.
The database name will be changed based on the current database connection.
On failure, the execution will bail and display a DB error.
`$db` string Required Database name. `$dbh` mysqli|resource Optional database connection. Default: `null`
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function select( $db, $dbh = null ) {
if ( is_null( $dbh ) ) {
$dbh = $this->dbh;
}
if ( $this->use_mysqli ) {
$success = mysqli_select_db( $dbh, $db );
} else {
$success = mysql_select_db( $db, $dbh );
}
if ( ! $success ) {
$this->ready = false;
if ( ! did_action( 'template_redirect' ) ) {
wp_load_translations_early();
$message = '<h1>' . __( 'Cannot select database' ) . "</h1>\n";
$message .= '<p>' . sprintf(
/* translators: %s: Database name. */
__( 'The database server could be connected to (which means your username and password is okay) but the %s database could not be selected.' ),
'<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
) . "</p>\n";
$message .= "<ul>\n";
$message .= '<li>' . __( 'Are you sure it exists?' ) . "</li>\n";
$message .= '<li>' . sprintf(
/* translators: 1: Database user, 2: Database name. */
__( 'Does the user %1$s have permission to use the %2$s database?' ),
'<code>' . htmlspecialchars( $this->dbuser, ENT_QUOTES ) . '</code>',
'<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
) . "</li>\n";
$message .= '<li>' . sprintf(
/* translators: %s: Database name. */
__( 'On some systems the name of your database is prefixed with your username, so it would be like <code>username_%1$s</code>. Could that be the problem?' ),
htmlspecialchars( $db, ENT_QUOTES )
) . "</li>\n";
$message .= "</ul>\n";
$message .= '<p>' . sprintf(
/* translators: %s: Support forums URL. */
__( 'If you do not know how to set up a database you should <strong>contact your host</strong>. If all else fails you may find help at the <a href="%s">WordPress Support Forums</a>.' ),
__( 'https://wordpress.org/support/forums/' )
) . "</p>\n";
$this->bail( $message, 'db_select_fail' );
}
}
}
```
| 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\_load\_translations\_early()](../../functions/wp_load_translations_early) wp-includes/load.php | Attempt an early load of translations. |
| [wpdb::bail()](bail) wp-includes/class-wpdb.php | Wraps errors in a nice header and footer and dies. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [wpdb::db\_connect()](db_connect) wp-includes/class-wpdb.php | Connects to and selects database. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wpdb::get_charset_collate(): string wpdb::get\_charset\_collate(): string
=====================================
Retrieves the database character collate.
string The database character collate.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function get_charset_collate() {
$charset_collate = '';
if ( ! empty( $this->charset ) ) {
$charset_collate = "DEFAULT CHARACTER SET $this->charset";
}
if ( ! empty( $this->collate ) ) {
$charset_collate .= " COLLATE $this->collate";
}
return $charset_collate;
}
```
| Used By | Description |
| --- | --- |
| [wp\_get\_db\_schema()](../../functions/wp_get_db_schema) wp-admin/includes/schema.php | Retrieve the SQL for creating database tables. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
| programming_docs |
wordpress wpdb::db_connect( bool $allow_bail = true ): bool wpdb::db\_connect( bool $allow\_bail = true ): bool
===================================================
Connects to and selects database.
If `$allow_bail` is false, the lack of database connection will need to be handled manually.
`$allow_bail` bool Optional Allows the function to bail. Default: `true`
bool True with a successful connection, false on failure.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function db_connect( $allow_bail = true ) {
$this->is_mysql = true;
/*
* Deprecated in 3.9+ when using MySQLi. No equivalent
* $new_link parameter exists for mysqli_* functions.
*/
$new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
$client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
if ( $this->use_mysqli ) {
/*
* Set the MySQLi error reporting off because WordPress handles its own.
* This is due to the default value change from `MYSQLI_REPORT_OFF`
* to `MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT` in PHP 8.1.
*/
mysqli_report( MYSQLI_REPORT_OFF );
$this->dbh = mysqli_init();
$host = $this->dbhost;
$port = null;
$socket = null;
$is_ipv6 = false;
$host_data = $this->parse_db_host( $this->dbhost );
if ( $host_data ) {
list( $host, $port, $socket, $is_ipv6 ) = $host_data;
}
/*
* If using the `mysqlnd` library, the IPv6 address needs to be enclosed
* in square brackets, whereas it doesn't while using the `libmysqlclient` library.
* @see https://bugs.php.net/bug.php?id=67563
*/
if ( $is_ipv6 && extension_loaded( 'mysqlnd' ) ) {
$host = "[$host]";
}
if ( WP_DEBUG ) {
mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
} else {
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
@mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
}
if ( $this->dbh->connect_errno ) {
$this->dbh = null;
/*
* It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
* - We haven't previously connected, and
* - WP_USE_EXT_MYSQL isn't set to false, and
* - ext/mysql is loaded.
*/
$attempt_fallback = true;
if ( $this->has_connected ) {
$attempt_fallback = false;
} elseif ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
$attempt_fallback = false;
} elseif ( ! function_exists( 'mysql_connect' ) ) {
$attempt_fallback = false;
}
if ( $attempt_fallback ) {
$this->use_mysqli = false;
return $this->db_connect( $allow_bail );
}
}
} else {
if ( WP_DEBUG ) {
$this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
} else {
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
$this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
}
}
if ( ! $this->dbh && $allow_bail ) {
wp_load_translations_early();
// Load custom DB error template, if present.
if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
require_once WP_CONTENT_DIR . '/db-error.php';
die();
}
$message = '<h1>' . __( 'Error establishing a database connection' ) . "</h1>\n";
$message .= '<p>' . sprintf(
/* translators: 1: wp-config.php, 2: Database host. */
__( 'This either means that the username and password information in your %1$s file is incorrect or that contact with the database server at %2$s could not be established. This could mean your host’s database server is down.' ),
'<code>wp-config.php</code>',
'<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
) . "</p>\n";
$message .= "<ul>\n";
$message .= '<li>' . __( 'Are you sure you have the correct username and password?' ) . "</li>\n";
$message .= '<li>' . __( 'Are you sure you have typed the correct hostname?' ) . "</li>\n";
$message .= '<li>' . __( 'Are you sure the database server is running?' ) . "</li>\n";
$message .= "</ul>\n";
$message .= '<p>' . sprintf(
/* translators: %s: Support forums URL. */
__( 'If you are unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href="%s">WordPress Support Forums</a>.' ),
__( 'https://wordpress.org/support/forums/' )
) . "</p>\n";
$this->bail( $message, 'db_connect_fail' );
return false;
} elseif ( $this->dbh ) {
if ( ! $this->has_connected ) {
$this->init_charset();
}
$this->has_connected = true;
$this->set_charset( $this->dbh );
$this->ready = true;
$this->set_sql_mode();
$this->select( $this->dbname, $this->dbh );
return true;
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::parse\_db\_host()](parse_db_host) wp-includes/class-wpdb.php | Parses the DB\_HOST setting to interpret it for mysqli\_real\_connect(). |
| [wp\_load\_translations\_early()](../../functions/wp_load_translations_early) wp-includes/load.php | Attempt an early load of translations. |
| [wpdb::bail()](bail) wp-includes/class-wpdb.php | Wraps errors in a nice header and footer and dies. |
| [wpdb::db\_connect()](db_connect) wp-includes/class-wpdb.php | Connects to and selects database. |
| [wpdb::select()](select) wp-includes/class-wpdb.php | Selects a database using the current or provided database connection. |
| [wpdb::init\_charset()](init_charset) wp-includes/class-wpdb.php | Sets $this->charset and $this->collate. |
| [wpdb::set\_charset()](set_charset) wp-includes/class-wpdb.php | Sets the connection’s character set. |
| [wpdb::set\_sql\_mode()](set_sql_mode) wp-includes/class-wpdb.php | Changes the current SQL mode, and ensures its WordPress compatibility. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [wpdb::check\_connection()](check_connection) wp-includes/class-wpdb.php | Checks that the connection to the database is still up. If not, try to reconnect. |
| [wpdb::db\_connect()](db_connect) wp-includes/class-wpdb.php | Connects to and selects database. |
| [wpdb::\_\_construct()](__construct) wp-includes/class-wpdb.php | Connects to the database server and selects a database. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | $allow\_bail parameter added. |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wpdb::db_version(): string|null wpdb::db\_version(): string|null
================================
Retrieves the database server version.
string|null Version number on success, null on failure.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function db_version() {
return preg_replace( '/[^0-9.].*/', '', $this->db_server_info() );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::db\_server\_info()](db_server_info) wp-includes/class-wpdb.php | Retrieves full database server information. |
| Used By | Description |
| --- | --- |
| [WP\_Automatic\_Updater::should\_update()](../wp_automatic_updater/should_update) wp-admin/includes/class-wp-automatic-updater.php | Tests to see if we can and should update a specific item. |
| [dbDelta()](../../functions/dbdelta) wp-admin/includes/upgrade.php | Modifies the database based on specified SQL statements. |
| [update\_core()](../../functions/update_core) wp-admin/includes/update-core.php | Upgrades the core of WordPress. |
| [list\_core\_update()](../../functions/list_core_update) wp-admin/update-core.php | Lists available core updates. |
| [wp\_version\_check()](../../functions/wp_version_check) wp-includes/update.php | Checks WordPress version against the newest version. |
| [wpdb::check\_database\_version()](check_database_version) wp-includes/class-wpdb.php | Determines whether MySQL database is at least the required minimum version. |
| [wpdb::has\_cap()](has_cap) wp-includes/class-wpdb.php | Determines whether the database or WPDB supports a particular feature. |
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress wpdb::init_charset() wpdb::init\_charset()
=====================
Sets $this->charset and $this->collate.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function init_charset() {
$charset = '';
$collate = '';
if ( function_exists( 'is_multisite' ) && is_multisite() ) {
$charset = 'utf8';
if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
$collate = DB_COLLATE;
} else {
$collate = 'utf8_general_ci';
}
} elseif ( defined( 'DB_COLLATE' ) ) {
$collate = DB_COLLATE;
}
if ( defined( 'DB_CHARSET' ) ) {
$charset = DB_CHARSET;
}
$charset_collate = $this->determine_charset( $charset, $collate );
$this->charset = $charset_collate['charset'];
$this->collate = $charset_collate['collate'];
}
```
| Uses | Description |
| --- | --- |
| [wpdb::determine\_charset()](determine_charset) wp-includes/class-wpdb.php | Determines the best charset and collation to use given a charset and collation. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| Used By | Description |
| --- | --- |
| [wpdb::db\_connect()](db_connect) wp-includes/class-wpdb.php | Connects to and selects database. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress wpdb::get_table_from_query( string $query ): string|false wpdb::get\_table\_from\_query( string $query ): string|false
============================================================
Finds the first table name referenced in a query.
`$query` string Required The query to search. string|false The table name found, or false if a table couldn't be found.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
protected function get_table_from_query( $query ) {
// Remove characters that can legally trail the table name.
$query = rtrim( $query, ';/-#' );
// Allow (select...) union [...] style queries. Use the first query's table name.
$query = ltrim( $query, "\r\n\t (" );
// Strip everything between parentheses except nested selects.
$query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', $query );
// Quickly match most common queries.
if ( preg_match(
'/^\s*(?:'
. 'SELECT.*?\s+FROM'
. '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
. '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
. '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
. '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:.+?FROM)?'
. ')\s+((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)/is',
$query,
$maybe
) ) {
return str_replace( '`', '', $maybe[1] );
}
// SHOW TABLE STATUS and SHOW TABLES WHERE Name = 'wp_posts'
if ( preg_match( '/^\s*SHOW\s+(?:TABLE\s+STATUS|(?:FULL\s+)?TABLES).+WHERE\s+Name\s*=\s*("|\')((?:[0-9a-zA-Z$_.-]|[\xC2-\xDF][\x80-\xBF])+)\\1/is', $query, $maybe ) ) {
return $maybe[2];
}
/*
* SHOW TABLE STATUS LIKE and SHOW TABLES LIKE 'wp\_123\_%'
* This quoted LIKE operand seldom holds a full table name.
* It is usually a pattern for matching a prefix so we just
* strip the trailing % and unescape the _ to get 'wp_123_'
* which drop-ins can use for routing these SQL statements.
*/
if ( preg_match( '/^\s*SHOW\s+(?:TABLE\s+STATUS|(?:FULL\s+)?TABLES)\s+(?:WHERE\s+Name\s+)?LIKE\s*("|\')((?:[\\\\0-9a-zA-Z$_.-]|[\xC2-\xDF][\x80-\xBF])+)%?\\1/is', $query, $maybe ) ) {
return str_replace( '\\_', '_', $maybe[2] );
}
// Big pattern for the rest of the table-related queries.
if ( preg_match(
'/^\s*(?:'
. '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
. '|DESCRIBE|DESC|EXPLAIN|HANDLER'
. '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
. '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE'
. '|TRUNCATE(?:\s+TABLE)?'
. '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
. '|ALTER(?:\s+IGNORE)?\s+TABLE'
. '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
. '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
. '|DROP\s+INDEX.*\s+ON'
. '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
. '|(?:GRANT|REVOKE).*ON\s+TABLE'
. '|SHOW\s+(?:.*FROM|.*TABLE)'
. ')\s+\(*\s*((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\s*\)*/is',
$query,
$maybe
) ) {
return str_replace( '`', '', $maybe[1] );
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [wpdb::check\_safe\_collation()](check_safe_collation) wp-includes/class-wpdb.php | Checks if the query is accessing a collation considered safe on the current version of MySQL. |
| [wpdb::strip\_invalid\_text\_from\_query()](strip_invalid_text_from_query) wp-includes/class-wpdb.php | Strips any invalid characters from the query. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress wpdb::process_field_lengths( array $data, string $table ): array|false wpdb::process\_field\_lengths( array $data, string $table ): array|false
========================================================================
For string fields, records the maximum string length that field can safely save.
`$data` array Required As it comes from the [wpdb::process\_field\_charsets()](process_field_charsets) method. More Arguments from wpdb::process\_field\_charsets( ... $data ) Array of fields to values. `$table` string Required Table name. array|false The same array as $data with additional `'length'` keys, or false if any of the values were too long for their corresponding field.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
protected function process_field_lengths( $data, $table ) {
foreach ( $data as $field => $value ) {
if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
/*
* We can skip this field if we know it isn't a string.
* This checks %d/%f versus ! %s because its sprintf() could take more.
*/
$value['length'] = false;
} else {
$value['length'] = $this->get_col_length( $table, $field );
if ( is_wp_error( $value['length'] ) ) {
return false;
}
}
$data[ $field ] = $value;
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_col\_length()](get_col_length) wp-includes/class-wpdb.php | Retrieves the maximum string length allowed in a given column. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [wpdb::process\_fields()](process_fields) wp-includes/class-wpdb.php | Processes arrays of field/value pairs and field formats. |
| Version | Description |
| --- | --- |
| [4.2.1](https://developer.wordpress.org/reference/since/4.2.1/) | Introduced. |
wordpress wpdb::strip_invalid_text_from_query( string $query ): string|WP_Error wpdb::strip\_invalid\_text\_from\_query( string $query ): string|WP\_Error
==========================================================================
Strips any invalid characters from the query.
`$query` string Required Query to convert. string|[WP\_Error](../wp_error) The converted query, or a [WP\_Error](../wp_error) object if the conversion fails.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
protected function strip_invalid_text_from_query( $query ) {
// We don't need to check the collation for queries that don't read data.
$trimmed_query = ltrim( $query, "\r\n\t (" );
if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $trimmed_query ) ) {
return $query;
}
$table = $this->get_table_from_query( $query );
if ( $table ) {
$charset = $this->get_table_charset( $table );
if ( is_wp_error( $charset ) ) {
return $charset;
}
// We can't reliably strip text from tables containing binary/blob columns.
if ( 'binary' === $charset ) {
return $query;
}
} else {
$charset = $this->charset;
}
$data = array(
'value' => $query,
'charset' => $charset,
'ascii' => false,
'length' => false,
);
$data = $this->strip_invalid_text( array( $data ) );
if ( is_wp_error( $data ) ) {
return $data;
}
return $data[0]['value'];
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_table\_from\_query()](get_table_from_query) wp-includes/class-wpdb.php | Finds the first table name referenced in a query. |
| [wpdb::get\_table\_charset()](get_table_charset) wp-includes/class-wpdb.php | Retrieves the character set for the given table. |
| [wpdb::strip\_invalid\_text()](strip_invalid_text) wp-includes/class-wpdb.php | Strips any invalid characters based on value/charset pairs. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [wpdb::query()](query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress wpdb::insert( string $table, array $data, array|string $format = null ): int|false wpdb::insert( string $table, array $data, array|string $format = null ): int|false
==================================================================================
Inserts a row into the table.
Examples:
```
wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
```
* [wpdb::prepare()](prepare)
* wpdb::$field\_types
* [wp\_set\_wpdb\_vars()](../../functions/wp_set_wpdb_vars)
`$table` string Required Table name. `$data` array Required Data to insert (in column => value pairs).
Both $data columns and $data values should be "raw" (neither should be SQL escaped).
Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case. `$format` array|string Optional An array of formats to be mapped to each of the value in $data.
If string, that format will be used for all of the values in $data.
A format is one of `'%d'`, `'%f'`, `'%s'` (integer, float, string).
If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field\_types. Default: `null`
int|false The number of rows inserted, or false on error.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function insert( $table, $data, $format = null ) {
return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::\_insert\_replace\_helper()](_insert_replace_helper) wp-includes/class-wpdb.php | Helper function for insert and replace. |
| Used By | Description |
| --- | --- |
| [wp\_insert\_site()](../../functions/wp_insert_site) wp-includes/ms-site.php | Inserts a new site into the database. |
| [add\_network\_option()](../../functions/add_network_option) wp-includes/option.php | Adds a new network option. |
| [populate\_network()](../../functions/populate_network) wp-admin/includes/schema.php | Populate network settings. |
| [wp\_install\_defaults()](../../functions/wp_install_defaults) wp-admin/includes/upgrade.php | Creates the initial content for a newly-installed site. |
| [wp\_insert\_link()](../../functions/wp_insert_link) wp-admin/includes/bookmark.php | Inserts a link into the database, or updates an existing link. |
| [update\_usermeta()](../../functions/update_usermeta) wp-includes/deprecated.php | Update metadata of user. |
| [wp\_insert\_term()](../../functions/wp_insert_term) wp-includes/taxonomy.php | Adds a new term to the database. |
| [wp\_set\_object\_terms()](../../functions/wp_set_object_terms) wp-includes/taxonomy.php | Creates term and taxonomy relationships. |
| [wp\_insert\_user()](../../functions/wp_insert_user) wp-includes/user.php | Inserts a user into the database. |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [wpmu\_log\_new\_registrations()](../../functions/wpmu_log_new_registrations) wp-includes/ms-functions.php | Logs the user email, IP, and registration date of a new site. |
| [wpmu\_signup\_blog()](../../functions/wpmu_signup_blog) wp-includes/ms-functions.php | Records site signup information for future activation. |
| [wpmu\_signup\_user()](../../functions/wpmu_signup_user) wp-includes/ms-functions.php | Records user signup information for future activation. |
| [wp\_insert\_comment()](../../functions/wp_insert_comment) wp-includes/comment.php | Inserts a comment into the database. |
| [add\_metadata()](../../functions/add_metadata) wp-includes/meta.php | Adds metadata for the specified object. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress wpdb::check_connection( bool $allow_bail = true ): bool|void wpdb::check\_connection( bool $allow\_bail = true ): bool|void
==============================================================
Checks that the connection to the database is still up. If not, try to reconnect.
If this function is unable to reconnect, it will forcibly die, or if called after the [‘template\_redirect’](../../hooks/template_redirect) hook has been fired, return false instead.
If `$allow_bail` is false, the lack of database connection will need to be handled manually.
`$allow_bail` bool Optional Allows the function to bail. Default: `true`
bool|void True if the connection is up.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function check_connection( $allow_bail = true ) {
if ( $this->use_mysqli ) {
if ( ! empty( $this->dbh ) && mysqli_ping( $this->dbh ) ) {
return true;
}
} else {
if ( ! empty( $this->dbh ) && mysql_ping( $this->dbh ) ) {
return true;
}
}
$error_reporting = false;
// Disable warnings, as we don't want to see a multitude of "unable to connect" messages.
if ( WP_DEBUG ) {
$error_reporting = error_reporting();
error_reporting( $error_reporting & ~E_WARNING );
}
for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
// On the last try, re-enable warnings. We want to see a single instance
// of the "unable to connect" message on the bail() screen, if it appears.
if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
error_reporting( $error_reporting );
}
if ( $this->db_connect( false ) ) {
if ( $error_reporting ) {
error_reporting( $error_reporting );
}
return true;
}
sleep( 1 );
}
// If template_redirect has already happened, it's too late for wp_die()/dead_db().
// Let's just return and hope for the best.
if ( did_action( 'template_redirect' ) ) {
return false;
}
if ( ! $allow_bail ) {
return false;
}
wp_load_translations_early();
$message = '<h1>' . __( 'Error reconnecting to the database' ) . "</h1>\n";
$message .= '<p>' . sprintf(
/* translators: %s: Database host. */
__( 'This means that the contact with the database server at %s was lost. This could mean your host’s database server is down.' ),
'<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
) . "</p>\n";
$message .= "<ul>\n";
$message .= '<li>' . __( 'Are you sure the database server is running?' ) . "</li>\n";
$message .= '<li>' . __( 'Are you sure the database server is not under particularly heavy load?' ) . "</li>\n";
$message .= "</ul>\n";
$message .= '<p>' . sprintf(
/* translators: %s: Support forums URL. */
__( 'If you are unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href="%s">WordPress Support Forums</a>.' ),
__( 'https://wordpress.org/support/forums/' )
) . "</p>\n";
// We weren't able to reconnect, so we better bail.
$this->bail( $message, 'db_connect_fail' );
// Call dead_db() if bail didn't die, because this database is no more.
// It has ceased to be (at least temporarily).
dead_db();
}
```
| Uses | Description |
| --- | --- |
| [wp\_load\_translations\_early()](../../functions/wp_load_translations_early) wp-includes/load.php | Attempt an early load of translations. |
| [dead\_db()](../../functions/dead_db) wp-includes/functions.php | Loads custom DB error or display WordPress DB error. |
| [did\_action()](../../functions/did_action) wp-includes/plugin.php | Retrieves the number of times an action has been fired during the current request. |
| [wpdb::bail()](bail) wp-includes/class-wpdb.php | Wraps errors in a nice header and footer and dies. |
| [wpdb::db\_connect()](db_connect) wp-includes/class-wpdb.php | Connects to and selects database. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [wpdb::query()](query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress wpdb::check_database_version(): void|WP_Error wpdb::check\_database\_version(): void|WP\_Error
================================================
Determines whether MySQL database is at least the required minimum version.
void|[WP\_Error](../wp_error)
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function check_database_version() {
global $wp_version, $required_mysql_version;
// Make sure the server has the required MySQL version.
if ( version_compare( $this->db_version(), $required_mysql_version, '<' ) ) {
/* translators: 1: WordPress version number, 2: Minimum required MySQL version number. */
return new WP_Error( 'database_version', sprintf( __( '<strong>Error:</strong> WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ) );
}
}
```
| Uses | Description |
| --- | --- |
| [wpdb::db\_version()](db_version) wp-includes/class-wpdb.php | Retrieves the database server version. |
| [\_\_()](../../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\_check\_mysql\_version()](../../functions/wp_check_mysql_version) wp-admin/includes/upgrade.php | Checks the version of the installed MySQL binary. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wpdb::process_field_charsets( array $data, string $table ): array|false wpdb::process\_field\_charsets( array $data, string $table ): array|false
=========================================================================
Adds field charsets to field/value/format arrays generated by [wpdb::process\_field\_formats()](process_field_formats).
`$data` array Required As it comes from the [wpdb::process\_field\_formats()](process_field_formats) method. More Arguments from wpdb::process\_field\_formats( ... $data ) Array of fields to values. `$table` string Required Table name. array|false The same array as $data with additional `'charset'` keys.
False on failure.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
protected function process_field_charsets( $data, $table ) {
foreach ( $data as $field => $value ) {
if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
/*
* We can skip this field if we know it isn't a string.
* This checks %d/%f versus ! %s because its sprintf() could take more.
*/
$value['charset'] = false;
} else {
$value['charset'] = $this->get_col_charset( $table, $field );
if ( is_wp_error( $value['charset'] ) ) {
return false;
}
}
$data[ $field ] = $value;
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_col\_charset()](get_col_charset) wp-includes/class-wpdb.php | Retrieves the character set for the given column. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [wpdb::process\_fields()](process_fields) wp-includes/class-wpdb.php | Processes arrays of field/value pairs and field formats. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress wpdb::update( string $table, array $data, array $where, array|string $format = null, array|string $where_format = null ): int|false wpdb::update( string $table, array $data, array $where, array|string $format = null, array|string $where\_format = null ): int|false
====================================================================================================================================
Updates a row in the table.
Examples:
```
wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
```
* [wpdb::prepare()](prepare)
* wpdb::$field\_types
* [wp\_set\_wpdb\_vars()](../../functions/wp_set_wpdb_vars)
`$table` string Required Table name. `$data` array Required Data to update (in column => value pairs).
Both $data columns and $data values should be "raw" (neither should be SQL escaped).
Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case. `$where` array Required A named array of WHERE clauses (in column => value pairs).
Multiple clauses will be joined with ANDs.
Both $where columns and $where values should be "raw".
Sending a null value will create an IS NULL comparison - the corresponding format will be ignored in this case. `$format` array|string Optional An array of formats to be mapped to each of the values in $data.
If string, that format will be used for all of the values in $data.
A format is one of `'%d'`, `'%f'`, `'%s'` (integer, float, string).
If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field\_types. Default: `null`
`$where_format` array|string Optional An array of formats to be mapped to each of the values in $where.
If string, that format will be used for all of the items in $where.
A format is one of `'%d'`, `'%f'`, `'%s'` (integer, float, string).
If omitted, all values in $where will be treated as strings. Default: `null`
int|false The number of rows updated, or false on error.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function update( $table, $data, $where, $format = null, $where_format = null ) {
if ( ! is_array( $data ) || ! is_array( $where ) ) {
return false;
}
$data = $this->process_fields( $table, $data, $format );
if ( false === $data ) {
return false;
}
$where = $this->process_fields( $table, $where, $where_format );
if ( false === $where ) {
return false;
}
$fields = array();
$conditions = array();
$values = array();
foreach ( $data as $field => $value ) {
if ( is_null( $value['value'] ) ) {
$fields[] = "`$field` = NULL";
continue;
}
$fields[] = "`$field` = " . $value['format'];
$values[] = $value['value'];
}
foreach ( $where as $field => $value ) {
if ( is_null( $value['value'] ) ) {
$conditions[] = "`$field` IS NULL";
continue;
}
$conditions[] = "`$field` = " . $value['format'];
$values[] = $value['value'];
}
$fields = implode( ', ', $fields );
$conditions = implode( ' AND ', $conditions );
$sql = "UPDATE `$table` SET $fields WHERE $conditions";
$this->check_current_query = false;
return $this->query( $this->prepare( $sql, $values ) );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::process\_fields()](process_fields) wp-includes/class-wpdb.php | Processes arrays of field/value pairs and field formats. |
| [wpdb::query()](query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| [wpdb::prepare()](prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [wp\_update\_site()](../../functions/wp_update_site) wp-includes/ms-site.php | Updates a site in the database. |
| [wp\_comments\_personal\_data\_eraser()](../../functions/wp_comments_personal_data_eraser) wp-includes/comment.php | Erases personal data associated with an email address from the comments table. |
| [WP\_Customize\_Manager::trash\_changeset\_post()](../wp_customize_manager/trash_changeset_post) wp-includes/class-wp-customize-manager.php | Trashes or deletes a changeset post. |
| [\_wp\_keep\_alive\_customize\_changeset\_dependent\_auto\_drafts()](../../functions/_wp_keep_alive_customize_changeset_dependent_auto_drafts) wp-includes/theme.php | Makes sure that auto-draft posts get their post\_date bumped or status changed to draft to prevent premature garbage-collection. |
| [WP\_Customize\_Manager::\_publish\_changeset\_values()](../wp_customize_manager/_publish_changeset_values) wp-includes/class-wp-customize-manager.php | Publishes the values of a changeset. |
| [wp\_add\_trashed\_suffix\_to\_post\_name\_for\_post()](../../functions/wp_add_trashed_suffix_to_post_name_for_post) wp-includes/post.php | Adds a trashed suffix for a given post. |
| [update\_network\_option()](../../functions/update_network_option) wp-includes/option.php | Updates the value of a network option that was already added. |
| [update\_user\_status()](../../functions/update_user_status) wp-includes/ms-deprecated.php | Update the status of a user in the database. |
| [wp\_install\_defaults()](../../functions/wp_install_defaults) wp-admin/includes/upgrade.php | Creates the initial content for a newly-installed site. |
| [wp\_delete\_user()](../../functions/wp_delete_user) wp-admin/includes/user.php | Remove user and optionally reassign posts and links to another user. |
| [wp\_insert\_link()](../../functions/wp_insert_link) wp-admin/includes/bookmark.php | Inserts a link into the database, or updates an existing link. |
| [WP\_Posts\_List\_Table::\_display\_rows\_hierarchical()](../wp_posts_list_table/_display_rows_hierarchical) wp-admin/includes/class-wp-posts-list-table.php | |
| [wp\_set\_password()](../../functions/wp_set_password) wp-includes/pluggable.php | Updates the user’s password with a new encrypted one. |
| [update\_usermeta()](../../functions/update_usermeta) wp-includes/deprecated.php | Update metadata of user. |
| [\_update\_post\_term\_count()](../../functions/_update_post_term_count) wp-includes/taxonomy.php | Updates term count based on object types of the current taxonomy. |
| [\_update\_generic\_term\_count()](../../functions/_update_generic_term_count) wp-includes/taxonomy.php | Updates term count based on number of objects. |
| [wp\_update\_term()](../../functions/wp_update_term) wp-includes/taxonomy.php | Updates term based on arguments provided. |
| [wp\_insert\_term()](../../functions/wp_insert_term) wp-includes/taxonomy.php | Adds a new term to the database. |
| [wp\_delete\_term()](../../functions/wp_delete_term) wp-includes/taxonomy.php | Removes a term from the database. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [wp\_insert\_user()](../../functions/wp_insert_user) wp-includes/user.php | Inserts a user into the database. |
| [\_transition\_post\_status()](../../functions/_transition_post_status) wp-includes/post.php | Hook for managing future post transitions to published. |
| [wp\_publish\_post()](../../functions/wp_publish_post) wp-includes/post.php | Publishes a post by transitioning the post status. |
| [add\_ping()](../../functions/add_ping) wp-includes/post.php | Adds a URL to those already pinged. |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [wp\_trash\_post\_comments()](../../functions/wp_trash_post_comments) wp-includes/post.php | Moves comments for a post to the Trash. |
| [set\_post\_type()](../../functions/set_post_type) wp-includes/post.php | Updates the post type for the post ID. |
| [\_wp\_upgrade\_revisions\_of\_post()](../../functions/_wp_upgrade_revisions_of_post) wp-includes/revision.php | Upgrades the revisions author, adds the current post as a revision and sets the revisions version to 1. |
| [wpmu\_activate\_signup()](../../functions/wpmu_activate_signup) wp-includes/ms-functions.php | Activates a signup. |
| [wp\_xmlrpc\_server::attach\_uploads()](../wp_xmlrpc_server/attach_uploads) wp-includes/class-wp-xmlrpc-server.php | Attach upload to a post. |
| [wp\_set\_comment\_status()](../../functions/wp_set_comment_status) wp-includes/comment.php | Sets the status of a comment. |
| [wp\_update\_comment()](../../functions/wp_update_comment) wp-includes/comment.php | Updates an existing comment in the database. |
| [wp\_update\_comment\_count\_now()](../../functions/wp_update_comment_count_now) wp-includes/comment.php | Updates the comment count for the post. |
| [do\_trackbacks()](../../functions/do_trackbacks) wp-includes/comment.php | Performs trackbacks. |
| [wp\_delete\_comment()](../../functions/wp_delete_comment) wp-includes/comment.php | Trashes or deletes a comment. |
| [update\_metadata\_by\_mid()](../../functions/update_metadata_by_mid) wp-includes/meta.php | Updates metadata by meta 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. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wpdb::get_caller(): string wpdb::get\_caller(): string
===========================
Retrieves a comma-separated list of the names of the functions that called [wpdb](../wpdb).
string Comma-separated list of the calling functions.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function get_caller() {
return wp_debug_backtrace_summary( __CLASS__ );
}
```
| Uses | Description |
| --- | --- |
| [wp\_debug\_backtrace\_summary()](../../functions/wp_debug_backtrace_summary) wp-includes/functions.php | Returns a comma-separated string or array of functions that have been called to get to the current point in code. |
| Used By | Description |
| --- | --- |
| [wpdb::\_do\_query()](_do_query) wp-includes/class-wpdb.php | Internal function to perform the mysql\_query() call. |
| [wpdb::print\_error()](print_error) wp-includes/class-wpdb.php | Prints SQL/DB error. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wpdb::process_field_formats( array $data, mixed $format ): array wpdb::process\_field\_formats( array $data, mixed $format ): array
==================================================================
Prepares arrays of value/format pairs as passed to [wpdb](../wpdb) CRUD methods.
`$data` array Required Array of fields to values. `$format` mixed Required Formats to be mapped to the values in $data. array Array, keyed by field names with values being an array of `'value'` and `'format'` keys.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
protected function process_field_formats( $data, $format ) {
$formats = (array) $format;
$original_formats = $formats;
foreach ( $data as $field => $value ) {
$value = array(
'value' => $value,
'format' => '%s',
);
if ( ! empty( $format ) ) {
$value['format'] = array_shift( $formats );
if ( ! $value['format'] ) {
$value['format'] = reset( $original_formats );
}
} elseif ( isset( $this->field_types[ $field ] ) ) {
$value['format'] = $this->field_types[ $field ];
}
$data[ $field ] = $value;
}
return $data;
}
```
| Used By | Description |
| --- | --- |
| [wpdb::process\_fields()](process_fields) wp-includes/class-wpdb.php | Processes arrays of field/value pairs and field formats. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
| programming_docs |
wordpress wpdb::log_query( string $query, float $query_time, string $query_callstack, float $query_start, array $query_data ) wpdb::log\_query( string $query, float $query\_time, string $query\_callstack, float $query\_start, array $query\_data )
========================================================================================================================
Logs query data.
`$query` string Required The query's SQL. `$query_time` float Required Total time spent on the query, in seconds. `$query_callstack` string Required Comma-separated list of the calling functions. `$query_start` float Required Unix timestamp of the time at the start of the query. `$query_data` array Required Custom query data. File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function log_query( $query, $query_time, $query_callstack, $query_start, $query_data ) {
/**
* Filters the custom data to log alongside a query.
*
* Caution should be used when modifying any of this data, it is recommended that any additional
* information you need to store about a query be added as a new associative array element.
*
* @since 5.3.0
*
* @param array $query_data Custom query data.
* @param string $query The query's SQL.
* @param float $query_time Total time spent on the query, in seconds.
* @param string $query_callstack Comma-separated list of the calling functions.
* @param float $query_start Unix timestamp of the time at the start of the query.
*/
$query_data = apply_filters( 'log_query_custom_data', $query_data, $query, $query_time, $query_callstack, $query_start );
$this->queries[] = array(
$query,
$query_time,
$query_callstack,
$query_start,
$query_data,
);
}
```
[apply\_filters( 'log\_query\_custom\_data', array $query\_data, string $query, float $query\_time, string $query\_callstack, float $query\_start )](../../hooks/log_query_custom_data)
Filters the custom data to log alongside a query.
| 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 |
| --- | --- |
| [wpdb::\_do\_query()](_do_query) wp-includes/class-wpdb.php | Internal function to perform the mysql\_query() call. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress wpdb::__unset( string $name ) wpdb::\_\_unset( string $name )
===============================
Makes private properties un-settable for backward compatibility.
`$name` string Required The private member to unset File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function __unset( $name ) {
unset( $this->$name );
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress wpdb::_do_query( string $query ) wpdb::\_do\_query( string $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. Use [wpdb::query()](query) instead.
Internal function to perform the mysql\_query() call.
* [wpdb::query()](query)
`$query` string Required The query to run. File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
private function _do_query( $query ) {
if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
$this->timer_start();
}
if ( ! empty( $this->dbh ) && $this->use_mysqli ) {
$this->result = mysqli_query( $this->dbh, $query );
} elseif ( ! empty( $this->dbh ) ) {
$this->result = mysql_query( $query, $this->dbh );
}
$this->num_queries++;
if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
$this->log_query(
$query,
$this->timer_stop(),
$this->get_caller(),
$this->time_start,
array()
);
}
}
```
| Uses | Description |
| --- | --- |
| [wpdb::log\_query()](log_query) wp-includes/class-wpdb.php | Logs query data. |
| [wpdb::timer\_start()](timer_start) wp-includes/class-wpdb.php | Starts the timer, for debugging purposes. |
| [wpdb::timer\_stop()](timer_stop) wp-includes/class-wpdb.php | Stops the debugging timer. |
| [wpdb::get\_caller()](get_caller) wp-includes/class-wpdb.php | Retrieves a comma-separated list of the names of the functions that called [wpdb](../wpdb). |
| Used By | Description |
| --- | --- |
| [wpdb::query()](query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| Version | Description |
| --- | --- |
| [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
wordpress wpdb::get_col_info( string $info_type = 'name', int $col_offset = -1 ): mixed wpdb::get\_col\_info( string $info\_type = 'name', int $col\_offset = -1 ): mixed
=================================================================================
Retrieves column metadata from the last query.
`$info_type` string Optional Possible values include `'name'`, `'table'`, `'def'`, `'max_length'`, `'not_null'`, `'primary_key'`, `'multiple_key'`, `'unique_key'`, `'numeric'`, `'blob'`, `'type'`, `'unsigned'`, `'zerofill'`. Default `'name'`. Default: `'name'`
`$col_offset` int Optional 0: col name. 1: which table the col's in. 2: col's max length.
3: if the col is numeric. 4: col's type. Default: `-1`
mixed Column results.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
$this->load_col_info();
if ( $this->col_info ) {
if ( -1 === $col_offset ) {
$i = 0;
$new_array = array();
foreach ( (array) $this->col_info as $col ) {
$new_array[ $i ] = $col->{$info_type};
$i++;
}
return $new_array;
} else {
return $this->col_info[ $col_offset ]->{$info_type};
}
}
}
```
| Uses | Description |
| --- | --- |
| [wpdb::load\_col\_info()](load_col_info) wp-includes/class-wpdb.php | Loads the column metadata from the last query. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wpdb::parse_db_host( string $host ): array|false wpdb::parse\_db\_host( string $host ): array|false
==================================================
Parses the DB\_HOST setting to interpret it for mysqli\_real\_connect().
mysqli\_real\_connect() doesn’t support the host param including a port or socket like mysql\_connect() does. This duplicates how mysql\_connect() detects a port and/or socket file.
`$host` string Required The DB\_HOST setting to parse. array|false Array containing the host, the port, the socket and whether it is an IPv6 address, in that order.
False if the host couldn't be parsed.
* stringHost name.
* `1`string|nullPort.
* `2`string|nullSocket.
* `3`boolWhether it is an IPv6 address.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function parse_db_host( $host ) {
$socket = null;
$is_ipv6 = false;
// First peel off the socket parameter from the right, if it exists.
$socket_pos = strpos( $host, ':/' );
if ( false !== $socket_pos ) {
$socket = substr( $host, $socket_pos + 1 );
$host = substr( $host, 0, $socket_pos );
}
// We need to check for an IPv6 address first.
// An IPv6 address will always contain at least two colons.
if ( substr_count( $host, ':' ) > 1 ) {
$pattern = '#^(?:\[)?(?P<host>[0-9a-fA-F:]+)(?:\]:(?P<port>[\d]+))?#';
$is_ipv6 = true;
} else {
// We seem to be dealing with an IPv4 address.
$pattern = '#^(?P<host>[^:/]*)(?::(?P<port>[\d]+))?#';
}
$matches = array();
$result = preg_match( $pattern, $host, $matches );
if ( 1 !== $result ) {
// Couldn't parse the address, bail.
return false;
}
$host = ! empty( $matches['host'] ) ? $matches['host'] : '';
// MySQLi port cannot be a string; must be null or an integer.
$port = ! empty( $matches['port'] ) ? absint( $matches['port'] ) : null;
return array( $host, $port, $socket, $is_ipv6 );
}
```
| Uses | Description |
| --- | --- |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Used By | Description |
| --- | --- |
| [wpdb::db\_connect()](db_connect) wp-includes/class-wpdb.php | Connects to and selects database. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress wpdb::get_results( string $query = null, string $output = OBJECT ): array|object|null wpdb::get\_results( string $query = null, string $output = OBJECT ): array|object|null
======================================================================================
Retrieves an entire SQL result set from the database (i.e., many rows).
Executes a SQL query and returns the entire SQL result.
`$query` string Optional SQL query. Default: `null`
`$output` string Optional Any of ARRAY\_A | ARRAY\_N | OBJECT | OBJECT\_K constants.
With one of the first three, return an array of rows indexed from 0 by SQL result row number. Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object ( ->column = value ), respectively. With OBJECT\_K, return an associative array of row objects keyed by the value of each row's first column's value. Duplicate keys are discarded. Default: `OBJECT`
array|object|null Database query results.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function get_results( $query = null, $output = OBJECT ) {
$this->func_call = "\$db->get_results(\"$query\", $output)";
if ( $query ) {
if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
$this->check_current_query = false;
}
$this->query( $query );
} else {
return null;
}
$new_array = array();
if ( OBJECT === $output ) {
// Return an integer-keyed array of row objects.
return $this->last_result;
} elseif ( OBJECT_K === $output ) {
// Return an array of row objects with keys from column 1.
// (Duplicates are discarded.)
if ( $this->last_result ) {
foreach ( $this->last_result as $row ) {
$var_by_ref = get_object_vars( $row );
$key = array_shift( $var_by_ref );
if ( ! isset( $new_array[ $key ] ) ) {
$new_array[ $key ] = $row;
}
}
}
return $new_array;
} elseif ( ARRAY_A === $output || ARRAY_N === $output ) {
// Return an integer-keyed array of...
if ( $this->last_result ) {
foreach ( (array) $this->last_result as $row ) {
if ( ARRAY_N === $output ) {
// ...integer-keyed row arrays.
$new_array[] = array_values( get_object_vars( $row ) );
} else {
// ...column name-keyed row arrays.
$new_array[] = get_object_vars( $row );
}
}
}
return $new_array;
} elseif ( strtoupper( $output ) === OBJECT ) {
// Back compat for OBJECT being previously case-insensitive.
return $this->last_result;
}
return null;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::check\_safe\_collation()](check_safe_collation) wp-includes/class-wpdb.php | Checks if the query is accessing a collation considered safe on the current version of MySQL. |
| [wpdb::query()](query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::should\_suggest\_persistent\_object\_cache()](../wp_site_health/should_suggest_persistent_object_cache) wp-admin/includes/class-wp-site-health.php | Determines whether to suggest using a persistent object cache. |
| [WP\_Debug\_Data::get\_database\_size()](../wp_debug_data/get_database_size) wp-admin/includes/class-wp-debug-data.php | Fetches the total size of all the database tables for the active database user. |
| [wp\_is\_site\_initialized()](../../functions/wp_is_site_initialized) wp-includes/ms-site.php | Checks whether a site is initialized. |
| [WP\_Privacy\_Requests\_Table::get\_request\_counts()](../wp_privacy_requests_table/get_request_counts) wp-admin/includes/class-wp-privacy-requests-table.php | Count number of requests for each status. |
| [has\_term\_meta()](../../functions/has_term_meta) wp-includes/taxonomy.php | Gets all meta data, including meta IDs, for the given term ID. |
| [WP\_Term\_Query::get\_terms()](../wp_term_query/get_terms) wp-includes/class-wp-term-query.php | Retrieves the query results. |
| [\_prime\_term\_caches()](../../functions/_prime_term_caches) wp-includes/taxonomy.php | Adds any terms from the given IDs to the cache that do not already exist in cache. |
| [\_prime\_network\_caches()](../../functions/_prime_network_caches) wp-includes/ms-network.php | Adds any networks from the given IDs to the cache that do not already exist in cache. |
| [\_prime\_site\_caches()](../../functions/_prime_site_caches) wp-includes/ms-site.php | Adds any sites from the given IDs to the cache that do not already exist in cache. |
| [wxr\_term\_meta()](../../functions/wxr_term_meta) wp-admin/includes/export.php | Outputs term meta XML tags for a given term object. |
| [WP\_Term::get\_instance()](../wp_term/get_instance) wp-includes/class-wp-term.php | Retrieve [WP\_Term](../wp_term) instance. |
| [\_prime\_comment\_caches()](../../functions/_prime_comment_caches) wp-includes/comment.php | Adds any comments from the given IDs to the cache that do not already exist in cache. |
| [\_wp\_batch\_split\_terms()](../../functions/_wp_batch_split_terms) wp-includes/taxonomy.php | Splits a batch of shared taxonomy terms. |
| [wpdb::get\_table\_charset()](get_table_charset) wp-includes/class-wpdb.php | Retrieves the character set for the given table. |
| [maybe\_convert\_table\_to\_utf8mb4()](../../functions/maybe_convert_table_to_utf8mb4) wp-admin/includes/upgrade.php | If a table only contains utf8 or utf8mb4 columns, convert it to utf8mb4. |
| [attachment\_url\_to\_postid()](../../functions/attachment_url_to_postid) wp-includes/media.php | Tries to convert an attachment URL into a post ID. |
| [check\_column()](../../functions/check_column) wp-admin/install-helper.php | Checks that database table column matches the criteria. |
| [export\_date\_options()](../../functions/export_date_options) wp-admin/export.php | Create the date options fields for exporting a given post type. |
| [export\_wp()](../../functions/export_wp) wp-admin/includes/export.php | Generates the WXR export file for download. |
| [wxr\_authors\_list()](../../functions/wxr_authors_list) wp-admin/includes/export.php | Outputs list of authors with posts. |
| [get\_editable\_authors()](../../functions/get_editable_authors) wp-admin/includes/deprecated.php | Gets author users who can edit posts. |
| [get\_others\_unpublished\_posts()](../../functions/get_others_unpublished_posts) wp-admin/includes/deprecated.php | Retrieves editable posts from other users. |
| [WP\_List\_Table::months\_dropdown()](../wp_list_table/months_dropdown) wp-admin/includes/class-wp-list-table.php | Displays a dropdown for filtering items in the list table by month. |
| [pre\_schema\_upgrade()](../../functions/pre_schema_upgrade) wp-admin/includes/upgrade.php | Runs before the schema is upgraded. |
| [upgrade\_network()](../../functions/upgrade_network) wp-admin/includes/upgrade.php | Executes network-level upgrade routines. |
| [get\_alloptions\_110()](../../functions/get_alloptions_110) wp-admin/includes/upgrade.php | Retrieve all options as it was for 1.2. |
| [dbDelta()](../../functions/dbdelta) wp-admin/includes/upgrade.php | Modifies the database based on specified SQL statements. |
| [get\_users\_drafts()](../../functions/get_users_drafts) wp-admin/includes/user.php | Retrieve the user’s drafts. |
| [parent\_dropdown()](../../functions/parent_dropdown) wp-admin/includes/template.php | Prints out option HTML elements for the page parents drop-down. |
| [media\_upload\_library\_form()](../../functions/media_upload_library_form) wp-admin/includes/media.php | Outputs the legacy media upload form for the media library. |
| [has\_meta()](../../functions/has_meta) wp-admin/includes/post.php | Returns meta data for the given post ID. |
| [bulk\_edit\_posts()](../../functions/bulk_edit_posts) wp-admin/includes/post.php | Processes the post data for the bulk editing of posts. |
| [WP\_Importer::get\_imported\_comments()](../wp_importer/get_imported_comments) wp-admin/includes/class-wp-importer.php | Set array with imported comments from WordPress database |
| [WP\_Importer::get\_imported\_posts()](../wp_importer/get_imported_posts) wp-admin/includes/class-wp-importer.php | Returns array with imported permalinks from WordPress database |
| [WP\_Importer::count\_imported\_posts()](../wp_importer/count_imported_posts) wp-admin/includes/class-wp-importer.php | Return count of imported permalinks from WordPress database |
| [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. |
| [cache\_users()](../../functions/cache_users) wp-includes/pluggable.php | Retrieves info for user lists to prevent multiple queries by [get\_userdata()](../../functions/get_userdata) . |
| [wp\_get\_archives()](../../functions/wp_get_archives) wp-includes/general-template.php | Displays archive links based on type and format. |
| [get\_calendar()](../../functions/get_calendar) wp-includes/general-template.php | Displays calendar with days that have posts as links. |
| [get\_users\_of\_blog()](../../functions/get_users_of_blog) wp-includes/deprecated.php | Get users for the site. |
| [WP\_Query::get\_posts()](../wp_query/get_posts) wp-includes/class-wp-query.php | Retrieves an array of posts based on query variables. |
| [wp\_scheduled\_delete()](../../functions/wp_scheduled_delete) wp-includes/functions.php | Permanently deletes comments or posts of any type that have held a status of ‘trash’ for the number of days defined in EMPTY\_TRASH\_DAYS. |
| [is\_blog\_installed()](../../functions/is_blog_installed) wp-includes/functions.php | Determines whether WordPress is already installed. |
| [\_pad\_term\_counts()](../../functions/_pad_term_counts) wp-includes/taxonomy.php | Adds count of children to parent count. |
| [clean\_term\_cache()](../../functions/clean_term_cache) wp-includes/taxonomy.php | Removes all of the term IDs from the cache. |
| [wp\_delete\_term()](../../functions/wp_delete_term) wp-includes/taxonomy.php | Removes a term from the database. |
| [wp\_load\_alloptions()](../../functions/wp_load_alloptions) wp-includes/option.php | Loads and caches all autoloaded options, if available or all options. |
| [wp\_load\_core\_site\_options()](../../functions/wp_load_core_site_options) wp-includes/option.php | Loads and caches certain often requested site options if [is\_multisite()](../../functions/is_multisite) and a persistent cache is not being used. |
| [WP\_User\_Query::query()](../wp_user_query/query) wp-includes/class-wp-user-query.php | Executes the query, with the current variables. |
| [count\_many\_users\_posts()](../../functions/count_many_users_posts) wp-includes/user.php | Gets the number of posts written by a list of users. |
| [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. |
| [\_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\_page\_by\_path()](../../functions/get_page_by_path) wp-includes/post.php | Retrieves a page given its path. |
| [get\_pages()](../../functions/get_pages) wp-includes/post.php | Retrieves an array of pages (or hierarchical post type items). |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [wp\_trash\_post\_comments()](../../functions/wp_trash_post_comments) wp-includes/post.php | Moves comments for a post to the Trash. |
| [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. |
| [wp\_count\_attachments()](../../functions/wp_count_attachments) wp-includes/post.php | Counts number of attachments for the mime type(s). |
| [WP\_Rewrite::page\_uri\_index()](../wp_rewrite/page_uri_index) wp-includes/class-wp-rewrite.php | Retrieves all pages and attachments for pages URIs. |
| [redirect\_canonical()](../../functions/redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| [wp\_get\_post\_autosave()](../../functions/wp_get_post_autosave) wp-includes/revision.php | Retrieves the autosaved data of the specified post. |
| [install\_blog()](../../functions/install_blog) wp-includes/ms-deprecated.php | Install an empty blog. |
| [get\_admin\_users\_for\_domain()](../../functions/get_admin_users_for_domain) wp-includes/ms-deprecated.php | Get the admin for a domain/path combination. |
| [get\_bookmarks()](../../functions/get_bookmarks) wp-includes/bookmark.php | Retrieves the list of bookmarks. |
| [get\_blog\_list()](../../functions/get_blog_list) wp-includes/ms-deprecated.php | Deprecated functionality to retrieve a list of all sites. |
| [wp\_list\_authors()](../../functions/wp_list_authors) wp-includes/author-template.php | Lists all the authors of the site, with several options available. |
| [get\_last\_updated()](../../functions/get_last_updated) wp-includes/ms-blogs.php | Get a list of most recently updated blogs. |
| [wp\_xmlrpc\_server::mt\_getTrackbackPings()](../wp_xmlrpc_server/mt_gettrackbackpings) wp-includes/class-wp-xmlrpc-server.php | Retrieve trackbacks sent to a given post. |
| [wp\_xmlrpc\_server::pingback\_ping()](../wp_xmlrpc_server/pingback_ping) wp-includes/class-wp-xmlrpc-server.php | Retrieves a pingback and registers it. |
| [wp\_xmlrpc\_server::pingback\_extensions\_getPingbacks()](../wp_xmlrpc_server/pingback_extensions_getpingbacks) wp-includes/class-wp-xmlrpc-server.php | Retrieve array of URLs that pingbacked the given URL. |
| [wp\_xmlrpc\_server::attach\_uploads()](../wp_xmlrpc_server/attach_uploads) wp-includes/class-wp-xmlrpc-server.php | Attach upload to a post. |
| [wp\_xmlrpc\_server::wp\_getPageList()](../wp_xmlrpc_server/wp_getpagelist) wp-includes/class-wp-xmlrpc-server.php | Retrieve page list. |
| [update\_meta\_cache()](../../functions/update_meta_cache) wp-includes/meta.php | Updates the metadata cache for the specified objects. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
| programming_docs |
wordpress wpdb::set_prefix( string $prefix, bool $set_table_names = true ): string|WP_Error wpdb::set\_prefix( string $prefix, bool $set\_table\_names = true ): string|WP\_Error
=====================================================================================
Sets the table prefix for the WordPress tables.
`$prefix` string Required Alphanumeric name for the new prefix. `$set_table_names` bool Optional Whether the table names, e.g. wpdb::$posts, should be updated or not. Default: `true`
string|[WP\_Error](../wp_error) Old prefix or [WP\_Error](../wp_error) on error.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function set_prefix( $prefix, $set_table_names = true ) {
if ( preg_match( '|[^a-z0-9_]|i', $prefix ) ) {
return new WP_Error( 'invalid_db_prefix', 'Invalid database prefix' );
}
$old_prefix = is_multisite() ? '' : $prefix;
if ( isset( $this->base_prefix ) ) {
$old_prefix = $this->base_prefix;
}
$this->base_prefix = $prefix;
if ( $set_table_names ) {
foreach ( $this->tables( 'global' ) as $table => $prefixed_table ) {
$this->$table = $prefixed_table;
}
if ( is_multisite() && empty( $this->blogid ) ) {
return $old_prefix;
}
$this->prefix = $this->get_blog_prefix();
foreach ( $this->tables( 'blog' ) as $table => $prefixed_table ) {
$this->$table = $prefixed_table;
}
foreach ( $this->tables( 'old' ) as $table => $prefixed_table ) {
$this->$table = $prefixed_table;
}
}
return $old_prefix;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_blog\_prefix()](get_blog_prefix) wp-includes/class-wpdb.php | Gets blog prefix. |
| [wpdb::tables()](tables) wp-includes/class-wpdb.php | Returns an array of WordPress tables. |
| [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\_set\_wpdb\_vars()](../../functions/wp_set_wpdb_vars) wp-includes/load.php | Set the database table prefix and the format specifiers for database table columns. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wpdb::suppress_errors( bool $suppress = true ): bool wpdb::suppress\_errors( bool $suppress = true ): bool
=====================================================
Enables or disables suppressing of database errors.
By default database errors are suppressed.
* [wpdb::hide\_errors()](hide_errors)
`$suppress` bool Optional Whether to suppress errors. Default: `true`
bool Whether suppressing of errors was previously active.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function suppress_errors( $suppress = true ) {
$errors = $this->suppress_errors;
$this->suppress_errors = (bool) $suppress;
return $errors;
}
```
| Used By | Description |
| --- | --- |
| [wp\_is\_site\_initialized()](../../functions/wp_is_site_initialized) wp-includes/ms-site.php | Checks whether a site is initialized. |
| [dbDelta()](../../functions/dbdelta) wp-admin/includes/upgrade.php | Modifies the database based on specified SQL statements. |
| [is\_blog\_installed()](../../functions/is_blog_installed) wp-includes/functions.php | Determines whether WordPress is already installed. |
| [wp\_load\_alloptions()](../../functions/wp_load_alloptions) wp-includes/option.php | Loads and caches all autoloaded options, if available or all options. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [install\_blog()](../../functions/install_blog) wp-includes/ms-deprecated.php | Install an empty blog. |
| [install\_blog\_defaults()](../../functions/install_blog_defaults) wp-includes/ms-deprecated.php | Set blog defaults. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wpdb::prepare( string $query, mixed $args ): string|void wpdb::prepare( string $query, mixed $args ): string|void
========================================================
Prepares a SQL query for safe execution.
Uses sprintf()-like syntax. The following placeholders can be used in the query string:
* %d (integer)
* %f (float)
* %s (string)
All placeholders MUST be left unquoted in the query string. A corresponding argument MUST be passed for each placeholder.
Note: There is one exception to the above: for compatibility with old behavior, numbered or formatted string placeholders (eg, `%1$s`, `%5s`) will not have quotes added by this function, so should be passed with appropriate quotes around them.
Literal percentage signs (`%`) in the query string must be written as `%%`. Percentage wildcards (for example, to use in LIKE syntax) must be passed via a substitution argument containing the complete LIKE string, these cannot be inserted directly in the query string.
Also see [wpdb::esc\_like()](esc_like).
Arguments may be passed as individual arguments to the method, or as a single array containing all arguments. A combination of the two is not supported.
Examples:
```
$wpdb->prepare(
"SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s",
array( 'foo', 1337, '%bar' )
);
$wpdb->prepare(
"SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s",
'foo'
);
```
`$query` string Required Query statement with sprintf()-like placeholders. `$args` mixed Required Further variables to substitute into the query's placeholders if being called with individual arguments. string|void Sanitized query string, if there is a query to prepare.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function prepare( $query, ...$args ) {
if ( is_null( $query ) ) {
return;
}
// This is not meant to be foolproof -- but it will catch obviously incorrect usage.
if ( strpos( $query, '%' ) === false ) {
wp_load_translations_early();
_doing_it_wrong(
'wpdb::prepare',
sprintf(
/* translators: %s: wpdb::prepare() */
__( 'The query argument of %s must have a placeholder.' ),
'wpdb::prepare()'
),
'3.9.0'
);
}
// If args were passed as an array (as in vsprintf), move them up.
$passed_as_array = false;
if ( isset( $args[0] ) && is_array( $args[0] ) && 1 === count( $args ) ) {
$passed_as_array = true;
$args = $args[0];
}
foreach ( $args as $arg ) {
if ( ! is_scalar( $arg ) && ! is_null( $arg ) ) {
wp_load_translations_early();
_doing_it_wrong(
'wpdb::prepare',
sprintf(
/* translators: %s: Value type. */
__( 'Unsupported value type (%s).' ),
gettype( $arg )
),
'4.8.2'
);
}
}
/*
* Specify the formatting allowed in a placeholder. The following are allowed:
*
* - Sign specifier, e.g. $+d
* - Numbered placeholders, e.g. %1$s
* - Padding specifier, including custom padding characters, e.g. %05s, %'#5s
* - Alignment specifier, e.g. %05-s
* - Precision specifier, e.g. %.2f
*/
$allowed_format = '(?:[1-9][0-9]*[$])?[-+0-9]*(?: |0|\'.)?[-+0-9]*(?:\.[0-9]+)?';
/*
* If a %s placeholder already has quotes around it, removing the existing quotes
* and re-inserting them ensures the quotes are consistent.
*
* For backward compatibility, this is only applied to %s, and not to placeholders like %1$s,
* which are frequently used in the middle of longer strings, or as table name placeholders.
*/
$query = str_replace( "'%s'", '%s', $query ); // Strip any existing single quotes.
$query = str_replace( '"%s"', '%s', $query ); // Strip any existing double quotes.
$query = preg_replace( '/(?<!%)%s/', "'%s'", $query ); // Quote the strings, avoiding escaped strings like %%s.
$query = preg_replace( "/(?<!%)(%($allowed_format)?f)/", '%\\2F', $query ); // Force floats to be locale-unaware.
$query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdF]))/", '%%\\1', $query ); // Escape any unescaped percents.
// Count the number of valid placeholders in the query.
$placeholders = preg_match_all( "/(^|[^%]|(%%)+)%($allowed_format)?[sdF]/", $query, $matches );
$args_count = count( $args );
if ( $args_count !== $placeholders ) {
if ( 1 === $placeholders && $passed_as_array ) {
// If the passed query only expected one argument, but the wrong number of arguments were sent as an array, bail.
wp_load_translations_early();
_doing_it_wrong(
'wpdb::prepare',
__( 'The query only expected one placeholder, but an array of multiple placeholders was sent.' ),
'4.9.0'
);
return;
} else {
/*
* If we don't have the right number of placeholders,
* but they were passed as individual arguments,
* or we were expecting multiple arguments in an array, throw a warning.
*/
wp_load_translations_early();
_doing_it_wrong(
'wpdb::prepare',
sprintf(
/* translators: 1: Number of placeholders, 2: Number of arguments passed. */
__( 'The query does not contain the correct number of placeholders (%1$d) for the number of arguments passed (%2$d).' ),
$placeholders,
$args_count
),
'4.8.3'
);
/*
* If we don't have enough arguments to match the placeholders,
* return an empty string to avoid a fatal error on PHP 8.
*/
if ( $args_count < $placeholders ) {
$max_numbered_placeholder = ! empty( $matches[3] ) ? max( array_map( 'intval', $matches[3] ) ) : 0;
if ( ! $max_numbered_placeholder || $args_count < $max_numbered_placeholder ) {
return '';
}
}
}
}
array_walk( $args, array( $this, 'escape_by_ref' ) );
$query = vsprintf( $query, $args );
return $this->add_placeholder_escape( $query );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::add\_placeholder\_escape()](add_placeholder_escape) wp-includes/class-wpdb.php | Adds a placeholder escape string, to escape anything that resembles a printf() placeholder. |
| [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\_Site\_Health::should\_suggest\_persistent\_object\_cache()](../wp_site_health/should_suggest_persistent_object_cache) wp-admin/includes/class-wp-site-health.php | Determines whether to suggest using a persistent object cache. |
| [WP\_Debug\_Data::get\_mysql\_var()](../wp_debug_data/get_mysql_var) wp-admin/includes/class-wp-debug-data.php | Returns the value of a MySQL system variable. |
| [\_wp\_batch\_update\_comment\_type()](../../functions/_wp_batch_update_comment_type) wp-includes/comment.php | Updates the comment type for a batch of comments. |
| [wp\_delete\_site()](../../functions/wp_delete_site) wp-includes/ms-site.php | Deletes a site from the database. |
| [populate\_network\_meta()](../../functions/populate_network_meta) wp-admin/includes/schema.php | Creates WordPress network meta and sets the default values. |
| [populate\_site\_meta()](../../functions/populate_site_meta) wp-admin/includes/schema.php | Creates WordPress site meta and sets the default values. |
| [\_find\_post\_by\_old\_slug()](../../functions/_find_post_by_old_slug) wp-includes/query.php | Find the post ID for redirecting an old slug. |
| [\_find\_post\_by\_old\_date()](../../functions/_find_post_by_old_date) wp-includes/query.php | Find the post ID for redirecting an old date. |
| [wp\_delete\_attachment\_files()](../../functions/wp_delete_attachment_files) wp-includes/post.php | Deletes all files that belong to the given attachment. |
| [WP\_Privacy\_Requests\_Table::get\_request\_counts()](../wp_privacy_requests_table/get_request_counts) wp-admin/includes/class-wp-privacy-requests-table.php | Count number of requests for each status. |
| [has\_term\_meta()](../../functions/has_term_meta) wp-includes/taxonomy.php | Gets all meta data, including meta IDs, for the given term ID. |
| [delete\_expired\_transients()](../../functions/delete_expired_transients) wp-includes/option.php | Deletes all expired transients. |
| [wp\_check\_comment\_flood()](../../functions/wp_check_comment_flood) wp-includes/comment.php | Checks whether comment flooding is occurring. |
| [WP\_Term\_Query::get\_search\_sql()](../wp_term_query/get_search_sql) wp-includes/class-wp-term-query.php | Used internally to generate a SQL string related to the ‘search’ parameter. |
| [WP\_Term\_Query::get\_terms()](../wp_term_query/get_terms) wp-includes/class-wp-term-query.php | Retrieves the query results. |
| [WP\_Network\_Query::get\_search\_sql()](../wp_network_query/get_search_sql) wp-includes/class-wp-network-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| [WP\_Network\_Query::get\_network\_ids()](../wp_network_query/get_network_ids) wp-includes/class-wp-network-query.php | Used internally to get a list of network IDs matching the query vars. |
| [WP\_Site\_Query::get\_search\_sql()](../wp_site_query/get_search_sql) wp-includes/class-wp-site-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| [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. |
| [wxr\_term\_meta()](../../functions/wxr_term_meta) wp-admin/includes/export.php | Outputs term meta XML tags for a given term object. |
| [WP\_Site::get\_instance()](../wp_site/get_instance) wp-includes/class-wp-site.php | Retrieves a site from the database by its ID. |
| [WP\_Upgrader::create\_lock()](../wp_upgrader/create_lock) wp-admin/includes/class-wp-upgrader.php | Creates a lock using WordPress options. |
| [WP\_Network::get\_instance()](../wp_network/get_instance) wp-includes/class-wp-network.php | Retrieves a network from the database by its ID. |
| [wp\_term\_is\_shared()](../../functions/wp_term_is_shared) wp-includes/taxonomy.php | Determines whether a term is shared between multiple taxonomies. |
| [WP\_Comment::get\_instance()](../wp_comment/get_instance) wp-includes/class-wp-comment.php | Retrieves a [WP\_Comment](../wp_comment) instance. |
| [wp\_get\_users\_with\_no\_role()](../../functions/wp_get_users_with_no_role) wp-includes/user.php | Gets the user IDs of all users with no role on this site. |
| [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\_Term::get\_instance()](../wp_term/get_instance) wp-includes/class-wp-term.php | Retrieve [WP\_Term](../wp_term) instance. |
| [delete\_network\_option()](../../functions/delete_network_option) wp-includes/option.php | Removes a network option by name. |
| [get\_network\_option()](../../functions/get_network_option) wp-includes/option.php | Retrieves a network’s option value based on the option name. |
| [\_wp\_batch\_split\_terms()](../../functions/_wp_batch_split_terms) wp-includes/taxonomy.php | Splits a batch of shared taxonomy terms. |
| [wpdb::strip\_invalid\_text()](strip_invalid_text) wp-includes/class-wpdb.php | Strips any invalid characters based on value/charset pairs. |
| [wp\_media\_attach\_action()](../../functions/wp_media_attach_action) wp-admin/includes/media.php | Encapsulates the logic for Attach/Detach actions. |
| [WP\_Meta\_Query::get\_sql\_for\_clause()](../wp_meta_query/get_sql_for_clause) wp-includes/class-wp-meta-query.php | Generate SQL JOIN and WHERE clauses for a first-order query clause. |
| [WP\_Tax\_Query::get\_sql\_for\_clause()](../wp_tax_query/get_sql_for_clause) wp-includes/class-wp-tax-query.php | Generates SQL JOIN and WHERE clauses for a “first-order” query clause. |
| [WP\_Date\_Query::get\_sql\_for\_clause()](../wp_date_query/get_sql_for_clause) wp-includes/class-wp-date-query.php | Turns a first-order date query into SQL for a WHERE clause. |
| [attachment\_url\_to\_postid()](../../functions/attachment_url_to_postid) wp-includes/media.php | Tries to convert an attachment URL into a post ID. |
| [display\_setup\_form()](../../functions/display_setup_form) wp-admin/install.php | Displays installer setup form. |
| [network\_domain\_check()](../../functions/network_domain_check) wp-admin/includes/network.php | Check for an existing network. |
| [export\_date\_options()](../../functions/export_date_options) wp-admin/export.php | Create the date options fields for exporting a given post type. |
| [export\_wp()](../../functions/export_wp) wp-admin/includes/export.php | Generates the WXR export file for download. |
| [WP\_User\_Search::prepare\_query()](../wp_user_search/prepare_query) wp-admin/includes/deprecated.php | Prepares the user search query (legacy). |
| [get\_author\_user\_ids()](../../functions/get_author_user_ids) wp-admin/includes/deprecated.php | Get all user IDs. |
| [get\_editable\_user\_ids()](../../functions/get_editable_user_ids) wp-admin/includes/deprecated.php | Gets the IDs of any users who can edit posts. |
| [get\_nonauthor\_user\_ids()](../../functions/get_nonauthor_user_ids) wp-admin/includes/deprecated.php | Gets all users who are not authors. |
| [get\_others\_unpublished\_posts()](../../functions/get_others_unpublished_posts) wp-admin/includes/deprecated.php | Retrieves editable posts from other users. |
| [WP\_List\_Table::months\_dropdown()](../wp_list_table/months_dropdown) wp-admin/includes/class-wp-list-table.php | Displays a dropdown for filtering items in the list table by month. |
| [wpmu\_delete\_user()](../../functions/wpmu_delete_user) wp-admin/includes/ms.php | Delete a user from the network and remove from all sites. |
| [populate\_network()](../../functions/populate_network) wp-admin/includes/schema.php | Populate network settings. |
| [populate\_options()](../../functions/populate_options) wp-admin/includes/schema.php | Create WordPress options and set the default values. |
| [maybe\_create\_table()](../../functions/maybe_create_table) wp-admin/includes/upgrade.php | Creates a table in the database, if it doesn’t already exist. |
| [wp\_install\_defaults()](../../functions/wp_install_defaults) wp-admin/includes/upgrade.php | Creates the initial content for a newly-installed site. |
| [get\_users\_drafts()](../../functions/get_users_drafts) wp-admin/includes/user.php | Retrieve the user’s drafts. |
| [wp\_delete\_user()](../../functions/wp_delete_user) wp-admin/includes/user.php | Remove user and optionally reassign posts and links to another user. |
| [meta\_form()](../../functions/meta_form) wp-admin/includes/template.php | Prints the form in the Custom Fields meta box. |
| [parent\_dropdown()](../../functions/parent_dropdown) wp-admin/includes/template.php | Prints out option HTML elements for the page parents drop-down. |
| [WP\_MS\_Sites\_List\_Table::prepare\_items()](../wp_ms_sites_list_table/prepare_items) wp-admin/includes/class-wp-ms-sites-list-table.php | Prepares the list of sites for display. |
| [update\_gallery\_tab()](../../functions/update_gallery_tab) wp-admin/includes/media.php | Adds the gallery tab back to the tabs array if post has image attachments. |
| [has\_meta()](../../functions/has_meta) wp-admin/includes/post.php | Returns meta data for the given post ID. |
| [get\_available\_post\_mime\_types()](../../functions/get_available_post_mime_types) wp-includes/post.php | Gets all available post MIME types for a given post type. |
| [post\_exists()](../../functions/post_exists) wp-admin/includes/post.php | Determines if a post exists based on title, content, date and type. |
| [WP\_Importer::get\_imported\_comments()](../wp_importer/get_imported_comments) wp-admin/includes/class-wp-importer.php | Set array with imported comments from WordPress database |
| [WP\_Importer::get\_imported\_posts()](../wp_importer/get_imported_posts) wp-admin/includes/class-wp-importer.php | Returns array with imported permalinks from WordPress database |
| [WP\_Importer::count\_imported\_posts()](../wp_importer/count_imported_posts) wp-admin/includes/class-wp-importer.php | Return count of imported permalinks from WordPress database |
| [\_wp\_delete\_orphaned\_draft\_menu\_items()](../../functions/_wp_delete_orphaned_draft_menu_items) wp-admin/includes/nav-menu.php | Deletes orphaned draft menu items |
| [comment\_exists()](../../functions/comment_exists) wp-admin/includes/comment.php | Determines if a comment exists based on author and date. |
| [WP\_Posts\_List\_Table::\_\_construct()](../wp_posts_list_table/__construct) wp-admin/includes/class-wp-posts-list-table.php | Constructor. |
| [WP\_User::get\_data\_by()](../wp_user/get_data_by) wp-includes/class-wp-user.php | Returns only the main user fields. |
| [wp\_get\_archives()](../../functions/wp_get_archives) wp-includes/general-template.php | Displays archive links based on type and format. |
| [delete\_usermeta()](../../functions/delete_usermeta) wp-includes/deprecated.php | Remove user meta data. |
| [get\_usermeta()](../../functions/get_usermeta) wp-includes/deprecated.php | Retrieve user metadata. |
| [update\_usermeta()](../../functions/update_usermeta) wp-includes/deprecated.php | Update metadata of user. |
| [WP\_Query::get\_posts()](../wp_query/get_posts) wp-includes/class-wp-query.php | Retrieves an array of posts based on query variables. |
| [WP\_Query::parse\_search()](../wp_query/parse_search) wp-includes/class-wp-query.php | Generates SQL for the WHERE clause based on passed search terms. |
| [WP\_Query::parse\_search\_order()](../wp_query/parse_search_order) wp-includes/class-wp-query.php | Generates SQL for the ORDER BY condition based on passed search terms. |
| [wp\_scheduled\_delete()](../../functions/wp_scheduled_delete) wp-includes/functions.php | Permanently deletes comments or posts of any type that have held a status of ‘trash’ for the number of days defined in EMPTY\_TRASH\_DAYS. |
| [do\_enclose()](../../functions/do_enclose) wp-includes/functions.php | Checks content for video and audio links to add as enclosures. |
| [\_update\_post\_term\_count()](../../functions/_update_post_term_count) wp-includes/taxonomy.php | Updates term count based on object types of the current taxonomy. |
| [\_update\_generic\_term\_count()](../../functions/_update_generic_term_count) wp-includes/taxonomy.php | Updates term count based on number of objects. |
| [wp\_unique\_term\_slug()](../../functions/wp_unique_term_slug) wp-includes/taxonomy.php | Makes term slug unique, if it isn’t already. |
| [wp\_update\_term()](../../functions/wp_update_term) wp-includes/taxonomy.php | Updates term based on arguments provided. |
| [wp\_set\_object\_terms()](../../functions/wp_set_object_terms) wp-includes/taxonomy.php | Creates term and taxonomy relationships. |
| [wp\_insert\_term()](../../functions/wp_insert_term) wp-includes/taxonomy.php | Adds a new term to the database. |
| [wp\_remove\_object\_terms()](../../functions/wp_remove_object_terms) wp-includes/taxonomy.php | Removes term(s) associated with a given object. |
| [wp\_delete\_term()](../../functions/wp_delete_term) wp-includes/taxonomy.php | Removes a term from the database. |
| [get\_adjacent\_post()](../../functions/get_adjacent_post) wp-includes/link-template.php | Retrieves the adjacent post. |
| [ms\_allowed\_http\_request\_hosts()](../../functions/ms_allowed_http_request_hosts) wp-includes/http.php | Adds any domain in a multisite installation for safe HTTP requests to the allowed list. |
| [WP\_Date\_Query::build\_time\_query()](../wp_date_query/build_time_query) wp-includes/class-wp-date-query.php | Builds a query string for comparing time values (hour, minute, second). |
| [wp\_load\_core\_site\_options()](../../functions/wp_load_core_site_options) wp-includes/option.php | Loads and caches certain often requested site options if [is\_multisite()](../../functions/is_multisite) and a persistent cache is not being used. |
| [add\_option()](../../functions/add_option) wp-includes/option.php | Adds a new option. |
| [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. |
| [WP\_User\_Query::prepare\_query()](../wp_user_query/prepare_query) wp-includes/class-wp-user-query.php | Prepares the query variables. |
| [WP\_User\_Query::get\_search\_sql()](../wp_user_query/get_search_sql) wp-includes/class-wp-user-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| [wp\_insert\_user()](../../functions/wp_insert_user) wp-includes/user.php | Inserts a user into the database. |
| [count\_users()](../../functions/count_users) wp-includes/user.php | Counts number of users who have each of the user roles. |
| [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. |
| [WP\_Post::get\_instance()](../wp_post/get_instance) wp-includes/class-wp-post.php | Retrieve [WP\_Post](../wp_post) instance. |
| [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. |
| [wp\_delete\_attachment()](../../functions/wp_delete_attachment) wp-includes/post.php | Trashes or deletes an attachment. |
| [get\_pages()](../../functions/get_pages) wp-includes/post.php | Retrieves an array of pages (or hierarchical post type items). |
| [wp\_unique\_post\_slug()](../../functions/wp_unique_post_slug) wp-includes/post.php | Computes a unique slug for the post, when given the desired slug and some post details. |
| [wp\_untrash\_post\_comments()](../../functions/wp_untrash_post_comments) wp-includes/post.php | Restores comments for a post from the Trash. |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [wp\_trash\_post\_comments()](../../functions/wp_trash_post_comments) wp-includes/post.php | Moves comments for a post to the Trash. |
| [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. |
| [WP\_Rewrite::page\_uri\_index()](../wp_rewrite/page_uri_index) wp-includes/class-wp-rewrite.php | Retrieves all pages and attachments for pages URIs. |
| [redirect\_canonical()](../../functions/redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| [redirect\_guess\_404\_permalink()](../../functions/redirect_guess_404_permalink) wp-includes/canonical.php | Attempts to guess the correct URL for a 404 request based on query vars. |
| [\_wp\_upgrade\_revisions\_of\_post()](../../functions/_wp_upgrade_revisions_of_post) wp-includes/revision.php | Upgrades the revisions author, adds the current post as a revision and sets the revisions version to 1. |
| [wp\_get\_post\_autosave()](../../functions/wp_get_post_autosave) wp-includes/revision.php | Retrieves the autosaved data of the specified post. |
| [get\_most\_recent\_post\_of\_user()](../../functions/get_most_recent_post_of_user) wp-includes/ms-functions.php | Gets a user’s most recent post. |
| [wpmu\_activate\_signup()](../../functions/wpmu_activate_signup) wp-includes/ms-functions.php | Activates a signup. |
| [wpmu\_validate\_user\_signup()](../../functions/wpmu_validate_user_signup) wp-includes/ms-functions.php | Sanitizes and validates data required for a user sign-up. |
| [wpmu\_validate\_blog\_signup()](../../functions/wpmu_validate_blog_signup) wp-includes/ms-functions.php | Processes new site registrations. |
| [get\_admin\_users\_for\_domain()](../../functions/get_admin_users_for_domain) wp-includes/ms-deprecated.php | Get the admin for a domain/path combination. |
| [remove\_user\_from\_blog()](../../functions/remove_user_from_blog) wp-includes/ms-functions.php | Removes a user from a blog. |
| [get\_bookmark()](../../functions/get_bookmark) wp-includes/bookmark.php | Retrieves bookmark data. |
| [get\_bookmarks()](../../functions/get_bookmarks) wp-includes/bookmark.php | Retrieves the list of bookmarks. |
| [ms\_not\_installed()](../../functions/ms_not_installed) wp-includes/ms-load.php | Displays a failure message. |
| [get\_blog\_list()](../../functions/get_blog_list) wp-includes/ms-deprecated.php | Deprecated functionality to retrieve a list of all sites. |
| [get\_blog\_status()](../../functions/get_blog_status) wp-includes/ms-blogs.php | Get a blog details field. |
| [get\_last\_updated()](../../functions/get_last_updated) wp-includes/ms-blogs.php | Get a list of most recently updated blogs. |
| [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. |
| [wp\_xmlrpc\_server::mt\_getTrackbackPings()](../wp_xmlrpc_server/mt_gettrackbackpings) wp-includes/class-wp-xmlrpc-server.php | Retrieve trackbacks sent to a given post. |
| [wp\_xmlrpc\_server::pingback\_ping()](../wp_xmlrpc_server/pingback_ping) wp-includes/class-wp-xmlrpc-server.php | Retrieves a pingback and registers it. |
| [wp\_xmlrpc\_server::pingback\_extensions\_getPingbacks()](../wp_xmlrpc_server/pingback_extensions_getpingbacks) wp-includes/class-wp-xmlrpc-server.php | Retrieve array of URLs that pingbacked the given URL. |
| [wpdb::\_insert\_replace\_helper()](_insert_replace_helper) wp-includes/class-wpdb.php | Helper function for insert and replace. |
| [wpdb::update()](update) wp-includes/class-wpdb.php | Updates a row in the table. |
| [wpdb::delete()](delete) wp-includes/class-wpdb.php | Deletes a row in the table. |
| [wpdb::set\_charset()](set_charset) wp-includes/class-wpdb.php | Sets the connection’s character set. |
| [trackback()](../../functions/trackback) wp-includes/comment.php | Sends a Trackback. |
| [WP\_Comment\_Query::get\_search\_sql()](../wp_comment_query/get_search_sql) wp-includes/class-wp-comment-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| [wp\_update\_comment\_count\_now()](../../functions/wp_update_comment_count_now) wp-includes/comment.php | Updates the comment count for the post. |
| [do\_trackbacks()](../../functions/do_trackbacks) wp-includes/comment.php | Performs trackbacks. |
| [wp\_delete\_comment()](../../functions/wp_delete_comment) wp-includes/comment.php | Trashes or deletes a comment. |
| [get\_lastcommentmodified()](../../functions/get_lastcommentmodified) wp-includes/comment.php | Retrieves the date the last comment was modified. |
| [wp\_allow\_comment()](../../functions/wp_allow_comment) wp-includes/comment.php | Validates whether this comment is allowed to be made. |
| [check\_comment()](../../functions/check_comment) wp-includes/comment.php | Checks whether a comment passes internal checks to be allowed to add. |
| [delete\_metadata()](../../functions/delete_metadata) wp-includes/meta.php | Deletes metadata for the specified object. |
| [get\_metadata\_by\_mid()](../../functions/get_metadata_by_mid) wp-includes/meta.php | Retrieves metadata by meta ID. |
| [add\_metadata()](../../functions/add_metadata) wp-includes/meta.php | Adds metadata for the specified object. |
| [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. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Formalized the existing and already documented `...$args` parameter by updating the function signature. The second parameter was changed from `$args` to `...$args`. |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
| programming_docs |
wordpress wpdb::db_server_info(): string|false wpdb::db\_server\_info(): string|false
======================================
Retrieves full database server information.
string|false Server info on success, false on failure.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function db_server_info() {
if ( $this->use_mysqli ) {
$server_info = mysqli_get_server_info( $this->dbh );
} else {
$server_info = mysql_get_server_info( $this->dbh );
}
return $server_info;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Site\_Health::prepare\_sql\_data()](../wp_site_health/prepare_sql_data) wp-admin/includes/class-wp-site-health.php | Runs the SQL version checks. |
| [dbDelta()](../../functions/dbdelta) wp-admin/includes/upgrade.php | Modifies the database based on specified SQL statements. |
| [wpdb::has\_cap()](has_cap) wp-includes/class-wpdb.php | Determines whether the database or WPDB supports a particular feature. |
| [wpdb::db\_version()](db_version) wp-includes/class-wpdb.php | Retrieves the database server version. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress wpdb::get_var( string|null $query = null, int $x, int $y ): string|null wpdb::get\_var( string|null $query = null, int $x, int $y ): string|null
========================================================================
Retrieves one variable from the database.
Executes a SQL query and returns the value from the SQL result.
If the SQL result contains more than one column and/or more than one row, the value in the column and row specified is returned. If $query is null, the value in the specified column and row from the previous SQL result is returned.
`$query` string|null Optional SQL query. Defaults to null, use the result from the previous query. Default: `null`
`$x` int Optional Column of value to return. Indexed from 0. `$y` int Optional Row of value to return. Indexed from 0. string|null Database query result (as string), or null on failure.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function get_var( $query = null, $x = 0, $y = 0 ) {
$this->func_call = "\$db->get_var(\"$query\", $x, $y)";
if ( $query ) {
if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
$this->check_current_query = false;
}
$this->query( $query );
}
// Extract var out of cached results based on x,y vals.
if ( ! empty( $this->last_result[ $y ] ) ) {
$values = array_values( get_object_vars( $this->last_result[ $y ] ) );
}
// If there is a value return it, else return null.
return ( isset( $values[ $x ] ) && '' !== $values[ $x ] ) ? $values[ $x ] : null;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::check\_safe\_collation()](check_safe_collation) wp-includes/class-wpdb.php | Checks if the query is accessing a collation considered safe on the current version of MySQL. |
| [wpdb::query()](query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| Used By | Description |
| --- | --- |
| [wp\_update\_user\_counts()](../../functions/wp_update_user_counts) wp-includes/user.php | Updates the total count of users on the site. |
| [\_wp\_batch\_update\_comment\_type()](../../functions/_wp_batch_update_comment_type) wp-includes/comment.php | Updates the comment type for a batch of comments. |
| [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::prepare\_sql\_data()](../wp_site_health/prepare_sql_data) wp-admin/includes/class-wp-site-health.php | Runs the SQL version checks. |
| [is\_site\_meta\_supported()](../../functions/is_site_meta_supported) wp-includes/functions.php | Determines whether site meta is enabled. |
| [\_find\_post\_by\_old\_slug()](../../functions/_find_post_by_old_slug) wp-includes/query.php | Find the post ID for redirecting an old slug. |
| [\_find\_post\_by\_old\_date()](../../functions/_find_post_by_old_date) wp-includes/query.php | Find the post ID for redirecting an old date. |
| [wp\_check\_comment\_flood()](../../functions/wp_check_comment_flood) wp-includes/comment.php | Checks whether comment flooding is occurring. |
| [WP\_Term\_Query::get\_terms()](../wp_term_query/get_terms) wp-includes/class-wp-term-query.php | Retrieves the query results. |
| [WP\_Network\_Query::set\_found\_networks()](../wp_network_query/set_found_networks) wp-includes/class-wp-network-query.php | Populates found\_networks and max\_num\_pages properties for the current query if the limit clause was used. |
| [WP\_Network\_Query::get\_network\_ids()](../wp_network_query/get_network_ids) wp-includes/class-wp-network-query.php | Used internally to get a list of network IDs matching the query vars. |
| [WP\_Comment\_Query::set\_found\_comments()](../wp_comment_query/set_found_comments) wp-includes/class-wp-comment-query.php | Populates found\_comments and max\_num\_pages properties for the current query if the limit clause was used. |
| [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\_Site\_Query::set\_found\_sites()](../wp_site_query/set_found_sites) wp-includes/class-wp-site-query.php | Populates found\_sites and max\_num\_pages properties for the current query if the limit clause was used. |
| [wp\_term\_is\_shared()](../../functions/wp_term_is_shared) wp-includes/taxonomy.php | Determines whether a term is shared between multiple taxonomies. |
| [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. |
| [network\_step2()](../../functions/network_step2) wp-admin/includes/network.php | Prints step 2 for Network installation process. |
| [display\_setup\_form()](../../functions/display_setup_form) wp-admin/install.php | Displays installer setup form. |
| [network\_domain\_check()](../../functions/network_domain_check) wp-admin/includes/network.php | Check for an existing network. |
| [WP\_User\_Search::query()](../wp_user_search/query) wp-admin/includes/deprecated.php | Executes the user search query. |
| [populate\_network()](../../functions/populate_network) wp-admin/includes/schema.php | Populate network settings. |
| [maybe\_disable\_link\_manager()](../../functions/maybe_disable_link_manager) wp-admin/includes/upgrade.php | Disables the Link Manager on upgrade if, at the time of upgrade, no links exist in the DB. |
| [pre\_schema\_upgrade()](../../functions/pre_schema_upgrade) wp-admin/includes/upgrade.php | Runs before the schema is upgraded. |
| [maybe\_create\_table()](../../functions/maybe_create_table) wp-admin/includes/upgrade.php | Creates a table in the database, if it doesn’t already exist. |
| [upgrade\_network()](../../functions/upgrade_network) wp-admin/includes/upgrade.php | Executes network-level upgrade routines. |
| [update\_gallery\_tab()](../../functions/update_gallery_tab) wp-admin/includes/media.php | Adds the gallery tab back to the tabs array if post has image attachments. |
| [post\_exists()](../../functions/post_exists) wp-admin/includes/post.php | Determines if a post exists based on title, content, date and type. |
| [comment\_exists()](../../functions/comment_exists) wp-admin/includes/comment.php | Determines if a comment exists based on author and date. |
| [WP\_Posts\_List\_Table::\_\_construct()](../wp_posts_list_table/__construct) wp-admin/includes/class-wp-posts-list-table.php | Constructor. |
| [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. |
| [get\_calendar()](../../functions/get_calendar) wp-includes/general-template.php | Displays calendar with days that have posts as links. |
| [WP\_Query::set\_found\_posts()](../wp_query/set_found_posts) wp-includes/class-wp-query.php | Set up the amount of found posts and the number of pages (if limit clause was used) for the current query. |
| [is\_blog\_installed()](../../functions/is_blog_installed) wp-includes/functions.php | Determines whether WordPress is already installed. |
| [do\_enclose()](../../functions/do_enclose) wp-includes/functions.php | Checks content for video and audio links to add as enclosures. |
| [\_update\_post\_term\_count()](../../functions/_update_post_term_count) wp-includes/taxonomy.php | Updates term count based on object types of the current taxonomy. |
| [\_update\_generic\_term\_count()](../../functions/_update_generic_term_count) wp-includes/taxonomy.php | Updates term count based on number of objects. |
| [wp\_unique\_term\_slug()](../../functions/wp_unique_term_slug) wp-includes/taxonomy.php | Makes term slug unique, if it isn’t already. |
| [wp\_update\_term()](../../functions/wp_update_term) wp-includes/taxonomy.php | Updates term based on arguments provided. |
| [wp\_insert\_term()](../../functions/wp_insert_term) wp-includes/taxonomy.php | Adds a new term to the database. |
| [wp\_set\_object\_terms()](../../functions/wp_set_object_terms) wp-includes/taxonomy.php | Creates term and taxonomy relationships. |
| [wp\_delete\_term()](../../functions/wp_delete_term) wp-includes/taxonomy.php | Removes a term from the database. |
| [get\_adjacent\_post()](../../functions/get_adjacent_post) wp-includes/link-template.php | Retrieves the adjacent post. |
| [ms\_allowed\_http\_request\_hosts()](../../functions/ms_allowed_http_request_hosts) wp-includes/http.php | Adds any domain in a multisite installation for safe HTTP requests to the allowed list. |
| [WP\_User\_Query::query()](../wp_user_query/query) wp-includes/class-wp-user-query.php | Executes the query, with the current variables. |
| [wp\_insert\_user()](../../functions/wp_insert_user) wp-includes/user.php | Inserts a user into the database. |
| [count\_user\_posts()](../../functions/count_user_posts) wp-includes/user.php | Gets the number of posts a user has written. |
| [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. |
| [\_get\_last\_post\_time()](../../functions/_get_last_post_time) wp-includes/post.php | Gets the timestamp of the last time any post was modified or published. |
| [wp\_unique\_post\_slug()](../../functions/wp_unique_post_slug) wp-includes/post.php | Computes a unique slug for the post, when given the desired slug and some post details. |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [wp\_count\_attachments()](../../functions/wp_count_attachments) wp-includes/post.php | Counts number of attachments for the mime type(s). |
| [redirect\_canonical()](../../functions/redirect_canonical) wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| [redirect\_guess\_404\_permalink()](../../functions/redirect_guess_404_permalink) wp-includes/canonical.php | Attempts to guess the correct URL for a 404 request based on query vars. |
| [update\_posts\_count()](../../functions/update_posts_count) wp-includes/ms-functions.php | Updates a blog’s post count. |
| [wpmu\_validate\_blog\_signup()](../../functions/wpmu_validate_blog_signup) wp-includes/ms-functions.php | Processes new site registrations. |
| [ms\_not\_installed()](../../functions/ms_not_installed) wp-includes/ms-load.php | Displays a failure message. |
| [get\_blog\_list()](../../functions/get_blog_list) wp-includes/ms-deprecated.php | Deprecated functionality to retrieve a list of all sites. |
| [get\_blog\_status()](../../functions/get_blog_status) wp-includes/ms-blogs.php | Get a blog details field. |
| [wp\_xmlrpc\_server::pingback\_ping()](../wp_xmlrpc_server/pingback_ping) wp-includes/class-wp-xmlrpc-server.php | Retrieves a pingback and registers it. |
| [wpdb::get\_col()](get_col) wp-includes/class-wpdb.php | Retrieves one column from the database. |
| [wp\_update\_comment\_count\_now()](../../functions/wp_update_comment_count_now) wp-includes/comment.php | Updates the comment count for the post. |
| [get\_lastcommentmodified()](../../functions/get_lastcommentmodified) wp-includes/comment.php | Retrieves the date the last comment was modified. |
| [wp\_allow\_comment()](../../functions/wp_allow_comment) wp-includes/comment.php | Validates whether this comment is allowed to be made. |
| [check\_comment()](../../functions/check_comment) wp-includes/comment.php | Checks whether a comment passes internal checks to be allowed to add. |
| [add\_metadata()](../../functions/add_metadata) wp-includes/meta.php | Adds metadata for the specified object. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wpdb::set_charset( mysqli|resource $dbh, string $charset = null, string $collate = null ) wpdb::set\_charset( mysqli|resource $dbh, string $charset = null, string $collate = null )
==========================================================================================
Sets the connection’s character set.
`$dbh` mysqli|resource Required The connection returned by `mysqli_connect()` or `mysql_connect()`. `$charset` string Optional The character set. Default: `null`
`$collate` string Optional The collation. Default: `null`
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function set_charset( $dbh, $charset = null, $collate = null ) {
if ( ! isset( $charset ) ) {
$charset = $this->charset;
}
if ( ! isset( $collate ) ) {
$collate = $this->collate;
}
if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
$set_charset_succeeded = true;
if ( $this->use_mysqli ) {
if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
$set_charset_succeeded = mysqli_set_charset( $dbh, $charset );
}
if ( $set_charset_succeeded ) {
$query = $this->prepare( 'SET NAMES %s', $charset );
if ( ! empty( $collate ) ) {
$query .= $this->prepare( ' COLLATE %s', $collate );
}
mysqli_query( $dbh, $query );
}
} else {
if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
$set_charset_succeeded = mysql_set_charset( $charset, $dbh );
}
if ( $set_charset_succeeded ) {
$query = $this->prepare( 'SET NAMES %s', $charset );
if ( ! empty( $collate ) ) {
$query .= $this->prepare( ' COLLATE %s', $collate );
}
mysql_query( $query, $dbh );
}
}
}
}
```
| Uses | Description |
| --- | --- |
| [wpdb::has\_cap()](has_cap) wp-includes/class-wpdb.php | Determines whether the database or WPDB supports a particular feature. |
| [wpdb::prepare()](prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [wpdb::db\_connect()](db_connect) wp-includes/class-wpdb.php | Connects to and selects database. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress wpdb::get_col( string|null $query = null, int $x ): array wpdb::get\_col( string|null $query = null, int $x ): array
==========================================================
Retrieves one column from the database.
Executes a SQL query and returns the column from the SQL result.
If the SQL result contains more than one column, the column specified is returned.
If $query is null, the specified column from the previous SQL result is returned.
`$query` string|null Optional SQL query. Defaults to previous query. Default: `null`
`$x` int Optional Column to return. Indexed from 0. array Database query result. Array indexed from 0 by SQL result row number.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function get_col( $query = null, $x = 0 ) {
if ( $query ) {
if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
$this->check_current_query = false;
}
$this->query( $query );
}
$new_array = array();
// Extract the column values.
if ( $this->last_result ) {
for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
$new_array[ $i ] = $this->get_var( null, $x, $i );
}
}
return $new_array;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::check\_safe\_collation()](check_safe_collation) wp-includes/class-wpdb.php | Checks if the query is accessing a collation considered safe on the current version of MySQL. |
| [wpdb::query()](query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| [wpdb::get\_var()](get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| Used By | Description |
| --- | --- |
| [\_wp\_batch\_update\_comment\_type()](../../functions/_wp_batch_update_comment_type) wp-includes/comment.php | Updates the comment type for a batch of comments. |
| [wp\_delete\_site()](../../functions/wp_delete_site) wp-includes/ms-site.php | Deletes a site from the database. |
| [WP\_Network\_Query::get\_network\_ids()](../wp_network_query/get_network_ids) wp-includes/class-wp-network-query.php | Used internally to get a list of network IDs matching the query vars. |
| [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\_get\_users\_with\_no\_role()](../../functions/wp_get_users_with_no_role) wp-includes/user.php | Gets the user IDs of all users with no role on this site. |
| [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. |
| [maybe\_drop\_column()](../../functions/maybe_drop_column) wp-admin/install-helper.php | Drops column from database table, if it exists. |
| [export\_wp()](../../functions/export_wp) wp-admin/includes/export.php | Generates the WXR export file for download. |
| [WP\_User\_Search::query()](../wp_user_search/query) wp-admin/includes/deprecated.php | Executes the user search query. |
| [get\_author\_user\_ids()](../../functions/get_author_user_ids) wp-admin/includes/deprecated.php | Get all user IDs. |
| [get\_editable\_user\_ids()](../../functions/get_editable_user_ids) wp-admin/includes/deprecated.php | Gets the IDs of any users who can edit posts. |
| [get\_nonauthor\_user\_ids()](../../functions/get_nonauthor_user_ids) wp-admin/includes/deprecated.php | Gets all users who are not authors. |
| [wpmu\_delete\_user()](../../functions/wpmu_delete_user) wp-admin/includes/ms.php | Delete a user from the network and remove from all sites. |
| [populate\_options()](../../functions/populate_options) wp-admin/includes/schema.php | Create WordPress options and set the default values. |
| [maybe\_create\_table()](../../functions/maybe_create_table) wp-admin/includes/upgrade.php | Creates a table in the database, if it doesn’t already exist. |
| [maybe\_add\_column()](../../functions/maybe_add_column) wp-admin/includes/upgrade.php | Adds column to a database table, if it doesn’t already exist. |
| [wp\_delete\_user()](../../functions/wp_delete_user) wp-admin/includes/user.php | Remove user and optionally reassign posts and links to another user. |
| [meta\_form()](../../functions/meta_form) wp-admin/includes/template.php | Prints the form in the Custom Fields meta box. |
| [WP\_MS\_Sites\_List\_Table::prepare\_items()](../wp_ms_sites_list_table/prepare_items) wp-admin/includes/class-wp-ms-sites-list-table.php | Prepares the list of sites for display. |
| [get\_meta\_keys()](../../functions/get_meta_keys) wp-admin/includes/post.php | Returns a list of previously defined keys. |
| [get\_available\_post\_mime\_types()](../../functions/get_available_post_mime_types) wp-includes/post.php | Gets all available post MIME types for a given post type. |
| [\_wp\_delete\_orphaned\_draft\_menu\_items()](../../functions/_wp_delete_orphaned_draft_menu_items) wp-admin/includes/nav-menu.php | Deletes orphaned draft menu items |
| [get\_usermeta()](../../functions/get_usermeta) wp-includes/deprecated.php | Retrieve user metadata. |
| [WP\_Query::get\_posts()](../wp_query/get_posts) wp-includes/class-wp-query.php | Retrieves an array of posts based on query variables. |
| [do\_enclose()](../../functions/do_enclose) wp-includes/functions.php | Checks content for video and audio links to add as enclosures. |
| [wp\_set\_object\_terms()](../../functions/wp_set_object_terms) wp-includes/taxonomy.php | Creates term and taxonomy relationships. |
| [wp\_delete\_term()](../../functions/wp_delete_term) wp-includes/taxonomy.php | Removes a term from the database. |
| [get\_objects\_in\_term()](../../functions/get_objects_in_term) wp-includes/taxonomy.php | Retrieves object IDs of valid taxonomy and term. |
| [WP\_User\_Query::query()](../wp_user_query/query) wp-includes/class-wp-user-query.php | Executes the query, with the current variables. |
| [count\_users()](../../functions/count_users) wp-includes/user.php | Counts number of users who have each of the user roles. |
| [wp\_delete\_auto\_drafts()](../../functions/wp_delete_auto_drafts) wp-includes/post.php | Deletes auto-drafts for new posts that are > 7 days old. |
| [wp\_delete\_attachment()](../../functions/wp_delete_attachment) wp-includes/post.php | Trashes or deletes an attachment. |
| [get\_all\_page\_ids()](../../functions/get_all_page_ids) wp-includes/post.php | Gets a list of page IDs. |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [remove\_user\_from\_blog()](../../functions/remove_user_from_blog) wp-includes/ms-functions.php | Removes a user from a blog. |
| [is\_multi\_author()](../../functions/is_multi_author) wp-includes/author-template.php | Determines whether this site has more than one author. |
| [wp\_delete\_comment()](../../functions/wp_delete_comment) wp-includes/comment.php | Trashes or deletes a comment. |
| [delete\_metadata()](../../functions/delete_metadata) wp-includes/meta.php | Deletes metadata for the specified object. |
| [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. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
| programming_docs |
wordpress wpdb::replace( string $table, array $data, array|string $format = null ): int|false wpdb::replace( string $table, array $data, array|string $format = null ): int|false
===================================================================================
Replaces a row in the table.
Examples:
```
wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
```
* [wpdb::prepare()](prepare)
* wpdb::$field\_types
* [wp\_set\_wpdb\_vars()](../../functions/wp_set_wpdb_vars)
`$table` string Required Table name. `$data` array Required Data to insert (in column => value pairs).
Both $data columns and $data values should be "raw" (neither should be SQL escaped).
Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case. `$format` array|string Optional An array of formats to be mapped to each of the value in $data.
If string, that format will be used for all of the values in $data.
A format is one of `'%d'`, `'%f'`, `'%s'` (integer, float, string).
If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field\_types. Default: `null`
int|false The number of rows affected, or false on error.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function replace( $table, $data, $format = null ) {
return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::\_insert\_replace\_helper()](_insert_replace_helper) wp-includes/class-wpdb.php | Helper function for insert and replace. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wpdb::get_table_charset( string $table ): string|WP_Error wpdb::get\_table\_charset( string $table ): string|WP\_Error
============================================================
Retrieves the character set for the given table.
`$table` string Required Table name. string|[WP\_Error](../wp_error) Table character set, [WP\_Error](../wp_error) object if it couldn't be found.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
protected function get_table_charset( $table ) {
$tablekey = strtolower( $table );
/**
* Filters the table charset value before the DB is checked.
*
* Returning a non-null value from the filter will effectively short-circuit
* checking the DB for the charset, returning that value instead.
*
* @since 4.2.0
*
* @param string|WP_Error|null $charset The character set to use, WP_Error object
* if it couldn't be found. Default null.
* @param string $table The name of the table being checked.
*/
$charset = apply_filters( 'pre_get_table_charset', null, $table );
if ( null !== $charset ) {
return $charset;
}
if ( isset( $this->table_charset[ $tablekey ] ) ) {
return $this->table_charset[ $tablekey ];
}
$charsets = array();
$columns = array();
$table_parts = explode( '.', $table );
$table = '`' . implode( '`.`', $table_parts ) . '`';
$results = $this->get_results( "SHOW FULL COLUMNS FROM $table" );
if ( ! $results ) {
return new WP_Error( 'wpdb_get_table_charset_failure', __( 'Could not retrieve table charset.' ) );
}
foreach ( $results as $column ) {
$columns[ strtolower( $column->Field ) ] = $column;
}
$this->col_meta[ $tablekey ] = $columns;
foreach ( $columns as $column ) {
if ( ! empty( $column->Collation ) ) {
list( $charset ) = explode( '_', $column->Collation );
// If the current connection can't support utf8mb4 characters, let's only send 3-byte utf8 characters.
if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
$charset = 'utf8';
}
$charsets[ strtolower( $charset ) ] = true;
}
list( $type ) = explode( '(', $column->Type );
// A binary/blob means the whole query gets treated like this.
if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ), true ) ) {
$this->table_charset[ $tablekey ] = 'binary';
return 'binary';
}
}
// utf8mb3 is an alias for utf8.
if ( isset( $charsets['utf8mb3'] ) ) {
$charsets['utf8'] = true;
unset( $charsets['utf8mb3'] );
}
// Check if we have more than one charset in play.
$count = count( $charsets );
if ( 1 === $count ) {
$charset = key( $charsets );
} elseif ( 0 === $count ) {
// No charsets, assume this table can store whatever.
$charset = false;
} else {
// More than one charset. Remove latin1 if present and recalculate.
unset( $charsets['latin1'] );
$count = count( $charsets );
if ( 1 === $count ) {
// Only one charset (besides latin1).
$charset = key( $charsets );
} elseif ( 2 === $count && isset( $charsets['utf8'], $charsets['utf8mb4'] ) ) {
// Two charsets, but they're utf8 and utf8mb4, use utf8.
$charset = 'utf8';
} else {
// Two mixed character sets. ascii.
$charset = 'ascii';
}
}
$this->table_charset[ $tablekey ] = $charset;
return $charset;
}
```
[apply\_filters( 'pre\_get\_table\_charset', string|WP\_Error|null $charset, string $table )](../../hooks/pre_get_table_charset)
Filters the table charset value before the DB is checked.
| Uses | Description |
| --- | --- |
| [wpdb::has\_cap()](has_cap) wp-includes/class-wpdb.php | Determines whether the database or WPDB supports a particular feature. |
| [\_\_()](../../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. |
| [wpdb::get\_results()](get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [wpdb::get\_col\_length()](get_col_length) wp-includes/class-wpdb.php | Retrieves the maximum string length allowed in a given column. |
| [wpdb::get\_col\_charset()](get_col_charset) wp-includes/class-wpdb.php | Retrieves the character set for the given column. |
| [wpdb::check\_safe\_collation()](check_safe_collation) wp-includes/class-wpdb.php | Checks if the query is accessing a collation considered safe on the current version of MySQL. |
| [wpdb::strip\_invalid\_text\_from\_query()](strip_invalid_text_from_query) wp-includes/class-wpdb.php | Strips any invalid characters from the query. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress wpdb::get_row( string|null $query = null, string $output = OBJECT, int $y ): array|object|null|void wpdb::get\_row( string|null $query = null, string $output = OBJECT, int $y ): array|object|null|void
====================================================================================================
Retrieves one row from the database.
Executes a SQL query and returns the row from the SQL result.
`$query` string|null Optional SQL query. Default: `null`
`$output` string Optional The required return type. One of OBJECT, ARRAY\_A, or ARRAY\_N, which correspond to an stdClass object, an associative array, or a numeric array, respectively. Default: `OBJECT`
`$y` int Optional Row to return. Indexed from 0. array|object|null|void Database query result in format specified by $output or null on failure.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
$this->func_call = "\$db->get_row(\"$query\",$output,$y)";
if ( $query ) {
if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
$this->check_current_query = false;
}
$this->query( $query );
} else {
return null;
}
if ( ! isset( $this->last_result[ $y ] ) ) {
return null;
}
if ( OBJECT === $output ) {
return $this->last_result[ $y ] ? $this->last_result[ $y ] : null;
} elseif ( ARRAY_A === $output ) {
return $this->last_result[ $y ] ? get_object_vars( $this->last_result[ $y ] ) : null;
} elseif ( ARRAY_N === $output ) {
return $this->last_result[ $y ] ? array_values( get_object_vars( $this->last_result[ $y ] ) ) : null;
} elseif ( OBJECT === strtoupper( $output ) ) {
// Back compat for OBJECT being previously case-insensitive.
return $this->last_result[ $y ] ? $this->last_result[ $y ] : null;
} else {
$this->print_error( ' $db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N' );
}
}
```
| Uses | Description |
| --- | --- |
| [wpdb::check\_safe\_collation()](check_safe_collation) wp-includes/class-wpdb.php | Checks if the query is accessing a collation considered safe on the current version of MySQL. |
| [wpdb::query()](query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| [wpdb::print\_error()](print_error) wp-includes/class-wpdb.php | Prints SQL/DB error. |
| Used By | Description |
| --- | --- |
| [WP\_Debug\_Data::get\_mysql\_var()](../wp_debug_data/get_mysql_var) wp-admin/includes/class-wp-debug-data.php | Returns the value of a MySQL system variable. |
| [wp\_delete\_attachment\_files()](../../functions/wp_delete_attachment_files) wp-includes/post.php | Deletes all files that belong to the given attachment. |
| [WP\_Site::get\_instance()](../wp_site/get_instance) wp-includes/class-wp-site.php | Retrieves a site from the database by its ID. |
| [WP\_Network::get\_instance()](../wp_network/get_instance) wp-includes/class-wp-network.php | Retrieves a network from the database by its ID. |
| [WP\_Comment::get\_instance()](../wp_comment/get_instance) wp-includes/class-wp-comment.php | Retrieves a [WP\_Comment](../wp_comment) instance. |
| [delete\_network\_option()](../../functions/delete_network_option) wp-includes/option.php | Removes a network option by name. |
| [get\_network\_option()](../../functions/get_network_option) wp-includes/option.php | Retrieves a network’s option value based on the option name. |
| [wpdb::strip\_invalid\_text()](strip_invalid_text) wp-includes/class-wpdb.php | Strips any invalid characters based on value/charset pairs. |
| [maybe\_convert\_table\_to\_utf8mb4()](../../functions/maybe_convert_table_to_utf8mb4) wp-admin/includes/upgrade.php | If a table only contains utf8 or utf8mb4 columns, convert it to utf8mb4. |
| [allow\_subdirectory\_install()](../../functions/allow_subdirectory_install) wp-admin/includes/network.php | Allow subdirectory installation. |
| [WP\_User::get\_data\_by()](../wp_user/get_data_by) wp-includes/class-wp-user.php | Returns only the main user fields. |
| [get\_calendar()](../../functions/get_calendar) wp-includes/general-template.php | Displays calendar with days that have posts as links. |
| [delete\_usermeta()](../../functions/delete_usermeta) wp-includes/deprecated.php | Remove user meta data. |
| [update\_usermeta()](../../functions/update_usermeta) wp-includes/deprecated.php | Update metadata of user. |
| [wp\_insert\_term()](../../functions/wp_insert_term) wp-includes/taxonomy.php | Adds a new term to the database. |
| [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. |
| [count\_users()](../../functions/count_users) wp-includes/user.php | Counts number of users who have each of the user roles. |
| [WP\_Post::get\_instance()](../wp_post/get_instance) wp-includes/class-wp-post.php | Retrieve [WP\_Post](../wp_post) instance. |
| [wp\_delete\_attachment()](../../functions/wp_delete_attachment) wp-includes/post.php | Trashes or deletes an attachment. |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [get\_most\_recent\_post\_of\_user()](../../functions/get_most_recent_post_of_user) wp-includes/ms-functions.php | Gets a user’s most recent post. |
| [wpmu\_activate\_signup()](../../functions/wpmu_activate_signup) wp-includes/ms-functions.php | Activates a signup. |
| [wpmu\_validate\_user\_signup()](../../functions/wpmu_validate_user_signup) wp-includes/ms-functions.php | Sanitizes and validates data required for a user sign-up. |
| [wpmu\_validate\_blog\_signup()](../../functions/wpmu_validate_blog_signup) wp-includes/ms-functions.php | Processes new site registrations. |
| [get\_bookmark()](../../functions/get_bookmark) wp-includes/bookmark.php | Retrieves bookmark data. |
| [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. |
| [get\_metadata\_by\_mid()](../../functions/get_metadata_by_mid) wp-includes/meta.php | Retrieves metadata by meta ID. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wpdb::__set( string $name, mixed $value ) wpdb::\_\_set( string $name, mixed $value )
===========================================
Makes private properties settable for backward compatibility.
`$name` string Required The private member to set. `$value` mixed Required The value to set. File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function __set( $name, $value ) {
$protected_members = array(
'col_meta',
'table_charset',
'check_current_query',
);
if ( in_array( $name, $protected_members, true ) ) {
return;
}
$this->$name = $value;
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress wpdb::get_col_charset( string $table, string $column ): string|false|WP_Error wpdb::get\_col\_charset( string $table, string $column ): string|false|WP\_Error
================================================================================
Retrieves the character set for the given column.
`$table` string Required Table name. `$column` string Required Column name. string|false|[WP\_Error](../wp_error) Column character set as a string. False if the column has no character set. [WP\_Error](../wp_error) object if there was an error.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function get_col_charset( $table, $column ) {
$tablekey = strtolower( $table );
$columnkey = strtolower( $column );
/**
* Filters the column charset value before the DB is checked.
*
* Passing a non-null value to the filter will short-circuit
* checking the DB for the charset, returning that value instead.
*
* @since 4.2.0
*
* @param string|null $charset The character set to use. Default null.
* @param string $table The name of the table being checked.
* @param string $column The name of the column being checked.
*/
$charset = apply_filters( 'pre_get_col_charset', null, $table, $column );
if ( null !== $charset ) {
return $charset;
}
// Skip this entirely if this isn't a MySQL database.
if ( empty( $this->is_mysql ) ) {
return false;
}
if ( empty( $this->table_charset[ $tablekey ] ) ) {
// This primes column information for us.
$table_charset = $this->get_table_charset( $table );
if ( is_wp_error( $table_charset ) ) {
return $table_charset;
}
}
// If still no column information, return the table charset.
if ( empty( $this->col_meta[ $tablekey ] ) ) {
return $this->table_charset[ $tablekey ];
}
// If this column doesn't exist, return the table charset.
if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
return $this->table_charset[ $tablekey ];
}
// Return false when it's not a string column.
if ( empty( $this->col_meta[ $tablekey ][ $columnkey ]->Collation ) ) {
return false;
}
list( $charset ) = explode( '_', $this->col_meta[ $tablekey ][ $columnkey ]->Collation );
return $charset;
}
```
[apply\_filters( 'pre\_get\_col\_charset', string|null $charset, string $table, string $column )](../../hooks/pre_get_col_charset)
Filters the column charset value before the DB is checked.
| Uses | Description |
| --- | --- |
| [wpdb::get\_table\_charset()](get_table_charset) wp-includes/class-wpdb.php | Retrieves the character set for the given table. |
| [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 |
| --- | --- |
| [wpdb::strip\_invalid\_text\_for\_column()](strip_invalid_text_for_column) wp-includes/class-wpdb.php | Strips any invalid characters from the string for a given table and column. |
| [wpdb::process\_field\_charsets()](process_field_charsets) wp-includes/class-wpdb.php | Adds field charsets to field/value/format arrays generated by [wpdb::process\_field\_formats()](process_field_formats). |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress wpdb::show_errors( bool $show = true ): bool wpdb::show\_errors( bool $show = true ): bool
=============================================
Enables showing of database errors.
This function should be used only to enable showing of errors.
[wpdb::hide\_errors()](hide_errors) should be used instead for hiding errors.
* [wpdb::hide\_errors()](hide_errors)
`$show` bool Optional Whether to show errors. Default: `true`
bool Whether showing of errors was previously active.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function show_errors( $show = true ) {
$errors = $this->show_errors;
$this->show_errors = $show;
return $errors;
}
```
| Used By | Description |
| --- | --- |
| [drop\_index()](../../functions/drop_index) wp-admin/includes/upgrade.php | Drops a specified index from a table. |
| [wpdb::\_\_construct()](__construct) wp-includes/class-wpdb.php | Connects to the database server and selects a database. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wpdb::__get( string $name ): mixed wpdb::\_\_get( string $name ): mixed
====================================
Makes private properties readable for backward compatibility.
`$name` string Required The private member to get, and optionally process. mixed The private member.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function __get( $name ) {
if ( 'col_info' === $name ) {
$this->load_col_info();
}
return $this->$name;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::load\_col\_info()](load_col_info) wp-includes/class-wpdb.php | Loads the column metadata from the last query. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
| programming_docs |
wordpress wpdb::flush() wpdb::flush()
=============
Kills cached query results.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function flush() {
$this->last_result = array();
$this->col_info = null;
$this->last_query = null;
$this->rows_affected = 0;
$this->num_rows = 0;
$this->last_error = '';
if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
mysqli_free_result( $this->result );
$this->result = null;
// Sanity check before using the handle.
if ( empty( $this->dbh ) || ! ( $this->dbh instanceof mysqli ) ) {
return;
}
// Clear out any results from a multi-query.
while ( mysqli_more_results( $this->dbh ) ) {
mysqli_next_result( $this->dbh );
}
} elseif ( is_resource( $this->result ) ) {
mysql_free_result( $this->result );
}
}
```
| Used By | Description |
| --- | --- |
| [wpdb::query()](query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wpdb::print_error( string $str = '' ): void|false wpdb::print\_error( string $str = '' ): void|false
==================================================
Prints SQL/DB error.
`$str` string Optional The error to display. Default: `''`
void|false Void if the showing of errors is enabled, false if disabled.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function print_error( $str = '' ) {
global $EZSQL_ERROR;
if ( ! $str ) {
if ( $this->use_mysqli ) {
$str = mysqli_error( $this->dbh );
} else {
$str = mysql_error( $this->dbh );
}
}
$EZSQL_ERROR[] = array(
'query' => $this->last_query,
'error_str' => $str,
);
if ( $this->suppress_errors ) {
return false;
}
$caller = $this->get_caller();
if ( $caller ) {
// Not translated, as this will only appear in the error log.
$error_str = sprintf( 'WordPress database error %1$s for query %2$s made by %3$s', $str, $this->last_query, $caller );
} else {
$error_str = sprintf( 'WordPress database error %1$s for query %2$s', $str, $this->last_query );
}
error_log( $error_str );
// Are we showing errors?
if ( ! $this->show_errors ) {
return false;
}
wp_load_translations_early();
// If there is an error then take note of it.
if ( is_multisite() ) {
$msg = sprintf(
"%s [%s]\n%s\n",
__( 'WordPress database error:' ),
$str,
$this->last_query
);
if ( defined( 'ERRORLOGFILE' ) ) {
error_log( $msg, 3, ERRORLOGFILE );
}
if ( defined( 'DIEONDBERROR' ) ) {
wp_die( $msg );
}
} else {
$str = htmlspecialchars( $str, ENT_QUOTES );
$query = htmlspecialchars( $this->last_query, ENT_QUOTES );
printf(
'<div id="error"><p class="wpdberror"><strong>%s</strong> [%s]<br /><code>%s</code></p></div>',
__( 'WordPress database error:' ),
$str,
$query
);
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_load\_translations\_early()](../../functions/wp_load_translations_early) wp-includes/load.php | Attempt an early load of translations. |
| [wpdb::get\_caller()](get_caller) wp-includes/class-wpdb.php | Retrieves a comma-separated list of the names of the functions that called [wpdb](../wpdb). |
| [\_\_()](../../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. |
| Used By | Description |
| --- | --- |
| [wpdb::query()](query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| [wpdb::get\_row()](get_row) wp-includes/class-wpdb.php | Retrieves one row from the database. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wpdb::_weak_escape( string $string ): string wpdb::\_weak\_escape( string $string ): string
==============================================
This method has been deprecated. Use [wpdb::prepare()](prepare) instead.
Do not use, deprecated.
Use [esc\_sql()](../../functions/esc_sql) or [wpdb::prepare()](prepare) instead.
* [wpdb::prepare()](prepare)
* [esc\_sql()](../../functions/esc_sql)
`$string` string Required string
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function _weak_escape( $string ) {
if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) ) {
_deprecated_function( __METHOD__, '3.6.0', 'wpdb::prepare() or esc_sql()' );
}
return addslashes( $string );
}
```
| 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 |
| --- | --- |
| [wpdb::escape()](escape) wp-includes/class-wpdb.php | Do not use, deprecated. |
| Version | Description |
| --- | --- |
| [3.6.0](https://developer.wordpress.org/reference/since/3.6.0/) | Use [wpdb::prepare()](prepare) |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress wpdb::tables( string $scope = 'all', bool $prefix = true, int $blog_id ): string[] wpdb::tables( string $scope = 'all', bool $prefix = true, int $blog\_id ): string[]
===================================================================================
Returns an array of WordPress tables.
Also allows for the `CUSTOM_USER_TABLE` and `CUSTOM_USER_META_TABLE` to override the WordPress users and usermeta tables that would otherwise be determined by the prefix.
The `$scope` argument can take one of the following:
* ‘all’ – returns ‘all’ and ‘global’ tables. No old tables are returned.
* ‘blog’ – returns the blog-level tables for the queried blog.
* ‘global’ – returns the global tables for the installation, returning multisite tables only on multisite.
* ‘ms\_global’ – returns the multisite global tables, regardless if current installation is multisite.
* ‘old’ – returns tables which are deprecated.
`$scope` string Optional Possible values include `'all'`, `'global'`, `'ms_global'`, `'blog'`, or `'old'` tables. Default `'all'`. Default: `'all'`
`$prefix` bool Optional Whether to include table prefixes. If blog prefix is requested, then the custom users and usermeta tables will be mapped. Default: `true`
`$blog_id` int Optional The blog\_id to prefix. Used only when prefix is requested.
Defaults to `wpdb::$blogid`. string[] Table names. When a prefix is requested, the key is the unprefixed table name.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
switch ( $scope ) {
case 'all':
$tables = array_merge( $this->global_tables, $this->tables );
if ( is_multisite() ) {
$tables = array_merge( $tables, $this->ms_global_tables );
}
break;
case 'blog':
$tables = $this->tables;
break;
case 'global':
$tables = $this->global_tables;
if ( is_multisite() ) {
$tables = array_merge( $tables, $this->ms_global_tables );
}
break;
case 'ms_global':
$tables = $this->ms_global_tables;
break;
case 'old':
$tables = $this->old_tables;
if ( is_multisite() ) {
$tables = array_merge( $tables, $this->old_ms_global_tables );
}
break;
default:
return array();
}
if ( $prefix ) {
if ( ! $blog_id ) {
$blog_id = $this->blogid;
}
$blog_prefix = $this->get_blog_prefix( $blog_id );
$base_prefix = $this->base_prefix;
$global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
foreach ( $tables as $k => $table ) {
if ( in_array( $table, $global_tables, true ) ) {
$tables[ $table ] = $base_prefix . $table;
} else {
$tables[ $table ] = $blog_prefix . $table;
}
unset( $tables[ $k ] );
}
if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) ) {
$tables['users'] = CUSTOM_USER_TABLE;
}
if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) ) {
$tables['usermeta'] = CUSTOM_USER_META_TABLE;
}
}
return $tables;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_blog\_prefix()](get_blog_prefix) wp-includes/class-wpdb.php | Gets blog prefix. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| Used By | Description |
| --- | --- |
| [wp\_uninitialize\_site()](../../functions/wp_uninitialize_site) wp-includes/ms-site.php | Runs the uninitialization routine for a given site. |
| [upgrade\_network()](../../functions/upgrade_network) wp-admin/includes/upgrade.php | Executes network-level upgrade routines. |
| [dbDelta()](../../functions/dbdelta) wp-admin/includes/upgrade.php | Modifies the database based on specified SQL statements. |
| [is\_blog\_installed()](../../functions/is_blog_installed) wp-includes/functions.php | Determines whether WordPress is already installed. |
| [ms\_not\_installed()](../../functions/ms_not_installed) wp-includes/ms-load.php | Displays a failure message. |
| [wpdb::set\_prefix()](set_prefix) wp-includes/class-wpdb.php | Sets the table prefix for the WordPress tables. |
| [wpdb::set\_blog\_id()](set_blog_id) wp-includes/class-wpdb.php | Sets blog ID. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | `old` now includes deprecated multisite global tables only on multisite. |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wpdb::supports_collation(): bool wpdb::supports\_collation(): bool
=================================
This method has been deprecated. Use [wpdb::has\_cap()](has_cap) instead.
Determines whether the database supports collation.
Called when WordPress is generating the table scheme.
Use `wpdb::has_cap( 'collation' )`.
bool True if collation is supported, false if not.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function supports_collation() {
_deprecated_function( __FUNCTION__, '3.5.0', 'wpdb::has_cap( \'collation\' )' );
return $this->has_cap( 'collation' );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::has\_cap()](has_cap) wp-includes/class-wpdb.php | Determines whether the database or WPDB supports a particular feature. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Use [wpdb::has\_cap()](has_cap) |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
wordpress wpdb::remove_placeholder_escape( string $query ): string wpdb::remove\_placeholder\_escape( string $query ): string
==========================================================
Removes the placeholder escape strings from a query.
`$query` string Required The query from which the placeholder will be removed. string The query with the placeholder removed.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function remove_placeholder_escape( $query ) {
return str_replace( $this->placeholder_escape(), '%', $query );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::placeholder\_escape()](placeholder_escape) wp-includes/class-wpdb.php | Generates and returns a placeholder escape string for use in queries returned by ::prepare(). |
| Used By | Description |
| --- | --- |
| [WP\_Query::generate\_cache\_key()](../wp_query/generate_cache_key) wp-includes/class-wp-query.php | Generate cache key. |
| Version | Description |
| --- | --- |
| [4.8.3](https://developer.wordpress.org/reference/since/4.8.3/) | Introduced. |
wordpress wpdb::check_ascii( string $string ): bool wpdb::check\_ascii( string $string ): bool
==========================================
Checks if a string is ASCII.
The negative regex is faster for non-ASCII strings, as it allows the search to finish as soon as it encounters a non-ASCII character.
`$string` string Required String to check. bool True if ASCII, false if not.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
protected function check_ascii( $string ) {
if ( function_exists( 'mb_check_encoding' ) ) {
if ( mb_check_encoding( $string, 'ASCII' ) ) {
return true;
}
} elseif ( ! preg_match( '/[^\x00-\x7F]/', $string ) ) {
return true;
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [wpdb::check\_safe\_collation()](check_safe_collation) wp-includes/class-wpdb.php | Checks if the query is accessing a collation considered safe on the current version of MySQL. |
| [wpdb::strip\_invalid\_text()](strip_invalid_text) wp-includes/class-wpdb.php | Strips any invalid characters based on value/charset pairs. |
| [wpdb::query()](query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress wpdb::check_safe_collation( string $query ): bool wpdb::check\_safe\_collation( string $query ): bool
===================================================
Checks if the query is accessing a collation considered safe on the current version of MySQL.
`$query` string Required The query to check. bool True if the collation is safe, false if it isn't.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
protected function check_safe_collation( $query ) {
if ( $this->checking_collation ) {
return true;
}
// We don't need to check the collation for queries that don't read data.
$query = ltrim( $query, "\r\n\t (" );
if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $query ) ) {
return true;
}
// All-ASCII queries don't need extra checking.
if ( $this->check_ascii( $query ) ) {
return true;
}
$table = $this->get_table_from_query( $query );
if ( ! $table ) {
return false;
}
$this->checking_collation = true;
$collation = $this->get_table_charset( $table );
$this->checking_collation = false;
// Tables with no collation, or latin1 only, don't need extra checking.
if ( false === $collation || 'latin1' === $collation ) {
return true;
}
$table = strtolower( $table );
if ( empty( $this->col_meta[ $table ] ) ) {
return false;
}
// If any of the columns don't have one of these collations, it needs more sanity checking.
$safe_collations = array(
'utf8_bin',
'utf8_general_ci',
'utf8mb3_bin',
'utf8mb3_general_ci',
'utf8mb4_bin',
'utf8mb4_general_ci',
);
foreach ( $this->col_meta[ $table ] as $col ) {
if ( empty( $col->Collation ) ) {
continue;
}
if ( ! in_array( $col->Collation, $safe_collations, true ) ) {
return false;
}
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_table\_from\_query()](get_table_from_query) wp-includes/class-wpdb.php | Finds the first table name referenced in a query. |
| [wpdb::check\_ascii()](check_ascii) wp-includes/class-wpdb.php | Checks if a string is ASCII. |
| [wpdb::get\_table\_charset()](get_table_charset) wp-includes/class-wpdb.php | Retrieves the character set for the given table. |
| Used By | Description |
| --- | --- |
| [wpdb::get\_var()](get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| [wpdb::get\_row()](get_row) wp-includes/class-wpdb.php | Retrieves one row from the database. |
| [wpdb::get\_col()](get_col) wp-includes/class-wpdb.php | Retrieves one column from the database. |
| [wpdb::get\_results()](get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress wpdb::has_cap( string $db_cap ): bool wpdb::has\_cap( string $db\_cap ): bool
=======================================
Determines whether the database or WPDB supports a particular feature.
Capability sniffs for the database server and current version of WPDB.
Database sniffs are based on the version of MySQL the site is using.
WPDB sniffs are added as new features are introduced to allow theme and plugin developers to determine feature support. This is to account for drop-ins which may introduce feature support at a different time to WordPress.
* [wpdb::db\_version()](db_version)
`$db_cap` string Required The feature to check for. Accepts `'collation'`, `'group_concat'`, `'subqueries'`, `'set_charset'`, `'utf8mb4'`, or `'utf8mb4_520'`. bool True when the database feature is supported, false otherwise.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function has_cap( $db_cap ) {
$db_version = $this->db_version();
$db_server_info = $this->db_server_info();
// Account for MariaDB version being prefixed with '5.5.5-' on older PHP versions.
if ( '5.5.5' === $db_version && str_contains( $db_server_info, 'MariaDB' )
&& PHP_VERSION_ID < 80016 // PHP 8.0.15 or older.
) {
// Strip the '5.5.5-' prefix and set the version to the correct value.
$db_server_info = preg_replace( '/^5\.5\.5-(.*)/', '$1', $db_server_info );
$db_version = preg_replace( '/[^0-9.].*/', '', $db_server_info );
}
switch ( strtolower( $db_cap ) ) {
case 'collation': // @since 2.5.0
case 'group_concat': // @since 2.7.0
case 'subqueries': // @since 2.7.0
return version_compare( $db_version, '4.1', '>=' );
case 'set_charset':
return version_compare( $db_version, '5.0.7', '>=' );
case 'utf8mb4': // @since 4.1.0
if ( version_compare( $db_version, '5.5.3', '<' ) ) {
return false;
}
if ( $this->use_mysqli ) {
$client_version = mysqli_get_client_info();
} else {
$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( $client_version, 'mysqlnd' ) ) {
$client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $client_version );
return version_compare( $client_version, '5.0.9', '>=' );
} else {
return version_compare( $client_version, '5.5.3', '>=' );
}
case 'utf8mb4_520': // @since 4.6.0
return version_compare( $db_version, '5.6', '>=' );
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::db\_server\_info()](db_server_info) wp-includes/class-wpdb.php | Retrieves full database server information. |
| [wpdb::db\_version()](db_version) wp-includes/class-wpdb.php | Retrieves the database server version. |
| Used By | Description |
| --- | --- |
| [wpdb::determine\_charset()](determine_charset) wp-includes/class-wpdb.php | Determines the best charset and collation to use given a charset and collation. |
| [wpdb::get\_table\_charset()](get_table_charset) wp-includes/class-wpdb.php | Retrieves the character set for the given table. |
| [wpdb::supports\_collation()](supports_collation) wp-includes/class-wpdb.php | Determines whether the database supports collation. |
| [wpdb::set\_charset()](set_charset) wp-includes/class-wpdb.php | Sets the connection’s character set. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Added support for the `'utf8mb4_520'` feature. |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Added support for the `'utf8mb4'` feature. |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
| programming_docs |
wordpress wpdb::__isset( string $name ): bool wpdb::\_\_isset( string $name ): bool
=====================================
Makes private properties check-able for backward compatibility.
`$name` string Required The private member to check. bool If the member is set or not.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function __isset( $name ) {
return isset( $this->$name );
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress wpdb::query( string $query ): int|bool wpdb::query( string $query ): int|bool
======================================
Performs a database query, using current database connection.
More information can be found on the documentation page.
`$query` string Required Database query. int|bool Boolean true for CREATE, ALTER, TRUNCATE and DROP queries. Number of rows affected/selected for all other queries. Boolean false on error.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function query( $query ) {
if ( ! $this->ready ) {
$this->check_current_query = true;
return false;
}
/**
* Filters the database query.
*
* Some queries are made before the plugins have been loaded,
* and thus cannot be filtered with this method.
*
* @since 2.1.0
*
* @param string $query Database query.
*/
$query = apply_filters( 'query', $query );
if ( ! $query ) {
$this->insert_id = 0;
return false;
}
$this->flush();
// Log how the function was called.
$this->func_call = "\$db->query(\"$query\")";
// If we're writing to the database, make sure the query will write safely.
if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
$stripped_query = $this->strip_invalid_text_from_query( $query );
// strip_invalid_text_from_query() can perform queries, so we need
// to flush again, just to make sure everything is clear.
$this->flush();
if ( $stripped_query !== $query ) {
$this->insert_id = 0;
$this->last_query = $query;
wp_load_translations_early();
$this->last_error = __( 'WordPress database error: Could not perform query because it contains invalid data.' );
return false;
}
}
$this->check_current_query = true;
// Keep track of the last query for debug.
$this->last_query = $query;
$this->_do_query( $query );
// Database server has gone away, try to reconnect.
$mysql_errno = 0;
if ( ! empty( $this->dbh ) ) {
if ( $this->use_mysqli ) {
if ( $this->dbh instanceof mysqli ) {
$mysql_errno = mysqli_errno( $this->dbh );
} else {
// $dbh is defined, but isn't a real connection.
// Something has gone horribly wrong, let's try a reconnect.
$mysql_errno = 2006;
}
} else {
if ( is_resource( $this->dbh ) ) {
$mysql_errno = mysql_errno( $this->dbh );
} else {
$mysql_errno = 2006;
}
}
}
if ( empty( $this->dbh ) || 2006 === $mysql_errno ) {
if ( $this->check_connection() ) {
$this->_do_query( $query );
} else {
$this->insert_id = 0;
return false;
}
}
// If there is an error then take note of it.
if ( $this->use_mysqli ) {
if ( $this->dbh instanceof mysqli ) {
$this->last_error = mysqli_error( $this->dbh );
} else {
$this->last_error = __( 'Unable to retrieve the error message from MySQL' );
}
} else {
if ( is_resource( $this->dbh ) ) {
$this->last_error = mysql_error( $this->dbh );
} else {
$this->last_error = __( 'Unable to retrieve the error message from MySQL' );
}
}
if ( $this->last_error ) {
// Clear insert_id on a subsequent failed insert.
if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
$this->insert_id = 0;
}
$this->print_error();
return false;
}
if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
$return_val = $this->result;
} elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
if ( $this->use_mysqli ) {
$this->rows_affected = mysqli_affected_rows( $this->dbh );
} else {
$this->rows_affected = mysql_affected_rows( $this->dbh );
}
// Take note of the insert_id.
if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
if ( $this->use_mysqli ) {
$this->insert_id = mysqli_insert_id( $this->dbh );
} else {
$this->insert_id = mysql_insert_id( $this->dbh );
}
}
// Return number of rows affected.
$return_val = $this->rows_affected;
} else {
$num_rows = 0;
if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
while ( $row = mysqli_fetch_object( $this->result ) ) {
$this->last_result[ $num_rows ] = $row;
$num_rows++;
}
} elseif ( is_resource( $this->result ) ) {
while ( $row = mysql_fetch_object( $this->result ) ) {
$this->last_result[ $num_rows ] = $row;
$num_rows++;
}
}
// Log and return the number of rows selected.
$this->num_rows = $num_rows;
$return_val = $num_rows;
}
return $return_val;
}
```
[apply\_filters( 'query', string $query )](../../hooks/query)
Filters the database query.
| Uses | Description |
| --- | --- |
| [wpdb::check\_ascii()](check_ascii) wp-includes/class-wpdb.php | Checks if a string is ASCII. |
| [wpdb::strip\_invalid\_text\_from\_query()](strip_invalid_text_from_query) wp-includes/class-wpdb.php | Strips any invalid characters from the query. |
| [wp\_load\_translations\_early()](../../functions/wp_load_translations_early) wp-includes/load.php | Attempt an early load of translations. |
| [wpdb::\_do\_query()](_do_query) wp-includes/class-wpdb.php | Internal function to perform the mysql\_query() call. |
| [wpdb::check\_connection()](check_connection) wp-includes/class-wpdb.php | Checks that the connection to the database is still up. If not, try to reconnect. |
| [wpdb::flush()](flush) wp-includes/class-wpdb.php | Kills cached query results. |
| [wpdb::print\_error()](print_error) wp-includes/class-wpdb.php | Prints SQL/DB error. |
| [\_\_()](../../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\_batch\_update\_comment\_type()](../../functions/_wp_batch_update_comment_type) wp-includes/comment.php | Updates the comment type for a batch of comments. |
| [wp\_uninitialize\_site()](../../functions/wp_uninitialize_site) wp-includes/ms-site.php | Runs the uninitialization routine for a given site. |
| [populate\_network\_meta()](../../functions/populate_network_meta) wp-admin/includes/schema.php | Creates WordPress network meta and sets the default values. |
| [populate\_site\_meta()](../../functions/populate_site_meta) wp-admin/includes/schema.php | Creates WordPress site meta and sets the default values. |
| [delete\_expired\_transients()](../../functions/delete_expired_transients) wp-includes/option.php | Deletes all expired transients. |
| [WP\_Upgrader::create\_lock()](../wp_upgrader/create_lock) wp-admin/includes/class-wp-upgrader.php | Creates a lock using WordPress options. |
| [\_wp\_batch\_split\_terms()](../../functions/_wp_batch_split_terms) wp-includes/taxonomy.php | Splits a batch of shared taxonomy terms. |
| [wp\_media\_attach\_action()](../../functions/wp_media_attach_action) wp-admin/includes/media.php | Encapsulates the logic for Attach/Detach actions. |
| [maybe\_convert\_table\_to\_utf8mb4()](../../functions/maybe_convert_table_to_utf8mb4) wp-admin/includes/upgrade.php | If a table only contains utf8 or utf8mb4 columns, convert it to utf8mb4. |
| [maybe\_drop\_column()](../../functions/maybe_drop_column) wp-admin/install-helper.php | Drops column from database table, if it exists. |
| [populate\_options()](../../functions/populate_options) wp-admin/includes/schema.php | Create WordPress options and set the default values. |
| [pre\_schema\_upgrade()](../../functions/pre_schema_upgrade) wp-admin/includes/upgrade.php | Runs before the schema is upgraded. |
| [maybe\_create\_table()](../../functions/maybe_create_table) wp-admin/includes/upgrade.php | Creates a table in the database, if it doesn’t already exist. |
| [maybe\_add\_column()](../../functions/maybe_add_column) wp-admin/includes/upgrade.php | Adds column to a database table, if it doesn’t already exist. |
| [upgrade\_network()](../../functions/upgrade_network) wp-admin/includes/upgrade.php | Executes network-level upgrade routines. |
| [drop\_index()](../../functions/drop_index) wp-admin/includes/upgrade.php | Drops a specified index from a table. |
| [add\_clean\_index()](../../functions/add_clean_index) wp-admin/includes/upgrade.php | Adds an index to a specified table. |
| [dbDelta()](../../functions/dbdelta) wp-admin/includes/upgrade.php | Modifies the database based on specified SQL statements. |
| [wp\_install\_defaults()](../../functions/wp_install_defaults) wp-admin/includes/upgrade.php | Creates the initial content for a newly-installed site. |
| [delete\_usermeta()](../../functions/delete_usermeta) wp-includes/deprecated.php | Remove user meta data. |
| [wp\_set\_object\_terms()](../../functions/wp_set_object_terms) wp-includes/taxonomy.php | Creates term and taxonomy relationships. |
| [wp\_remove\_object\_terms()](../../functions/wp_remove_object_terms) wp-includes/taxonomy.php | Removes term(s) associated with a given object. |
| [add\_option()](../../functions/add_option) wp-includes/option.php | Adds a new option. |
| [wp\_untrash\_post\_comments()](../../functions/wp_untrash_post_comments) wp-includes/post.php | Restores comments for a post from the Trash. |
| [\_wp\_upgrade\_revisions\_of\_post()](../../functions/_wp_upgrade_revisions_of_post) wp-includes/revision.php | Upgrades the revisions author, adds the current post as a revision and sets the revisions version to 1. |
| [remove\_user\_from\_blog()](../../functions/remove_user_from_blog) wp-includes/ms-functions.php | Removes a user from a blog. |
| [wpdb::\_insert\_replace\_helper()](_insert_replace_helper) wp-includes/class-wpdb.php | Helper function for insert and replace. |
| [wpdb::update()](update) wp-includes/class-wpdb.php | Updates a row in the table. |
| [wpdb::delete()](delete) wp-includes/class-wpdb.php | Deletes a row in the table. |
| [wpdb::get\_var()](get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| [wpdb::get\_row()](get_row) wp-includes/class-wpdb.php | Retrieves one row from the database. |
| [wpdb::get\_col()](get_col) wp-includes/class-wpdb.php | Retrieves one column from the database. |
| [wpdb::get\_results()](get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| [trackback()](../../functions/trackback) wp-includes/comment.php | Sends a Trackback. |
| [do\_trackbacks()](../../functions/do_trackbacks) wp-includes/comment.php | Performs trackbacks. |
| [delete\_metadata()](../../functions/delete_metadata) wp-includes/meta.php | Deletes metadata for the specified object. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wpdb::load_col_info() wpdb::load\_col\_info()
=======================
Loads the column metadata from the last query.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
protected function load_col_info() {
if ( $this->col_info ) {
return;
}
if ( $this->use_mysqli ) {
$num_fields = mysqli_num_fields( $this->result );
for ( $i = 0; $i < $num_fields; $i++ ) {
$this->col_info[ $i ] = mysqli_fetch_field( $this->result );
}
} else {
$num_fields = mysql_num_fields( $this->result );
for ( $i = 0; $i < $num_fields; $i++ ) {
$this->col_info[ $i ] = mysql_fetch_field( $this->result, $i );
}
}
}
```
| Used By | Description |
| --- | --- |
| [wpdb::get\_col\_info()](get_col_info) wp-includes/class-wpdb.php | Retrieves column metadata from the last query. |
| [wpdb::\_\_get()](__get) wp-includes/class-wpdb.php | Makes private properties readable for backward compatibility. |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress wpdb::placeholder_escape(): string wpdb::placeholder\_escape(): string
===================================
Generates and returns a placeholder escape string for use in queries returned by ::prepare().
string String to escape placeholders.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function placeholder_escape() {
static $placeholder;
if ( ! $placeholder ) {
// If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
$algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
// Old WP installs may not have AUTH_SALT defined.
$salt = defined( 'AUTH_SALT' ) && AUTH_SALT ? AUTH_SALT : (string) rand();
$placeholder = '{' . hash_hmac( $algo, uniqid( $salt, true ), $salt ) . '}';
}
/*
* Add the filter to remove the placeholder escaper. Uses priority 0, so that anything
* else attached to this filter will receive the query with the placeholder string removed.
*/
if ( false === has_filter( 'query', array( $this, 'remove_placeholder_escape' ) ) ) {
add_filter( 'query', array( $this, 'remove_placeholder_escape' ), 0 );
}
return $placeholder;
}
```
| Uses | Description |
| --- | --- |
| [has\_filter()](../../functions/has_filter) wp-includes/plugin.php | Checks if any filter has been registered for a hook. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Query::generate\_cache\_key()](../wp_query/generate_cache_key) wp-includes/class-wp-query.php | Generate cache key. |
| [wpdb::add\_placeholder\_escape()](add_placeholder_escape) wp-includes/class-wpdb.php | Adds a placeholder escape string, to escape anything that resembles a printf() placeholder. |
| [wpdb::remove\_placeholder\_escape()](remove_placeholder_escape) wp-includes/class-wpdb.php | Removes the placeholder escape strings from a query. |
| Version | Description |
| --- | --- |
| [4.8.3](https://developer.wordpress.org/reference/since/4.8.3/) | Introduced. |
wordpress wpdb::set_blog_id( int $blog_id, int $network_id ): int wpdb::set\_blog\_id( int $blog\_id, int $network\_id ): int
===========================================================
Sets blog ID.
`$blog_id` int Required `$network_id` int Optional int Previous blog ID.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function set_blog_id( $blog_id, $network_id = 0 ) {
if ( ! empty( $network_id ) ) {
$this->siteid = $network_id;
}
$old_blog_id = $this->blogid;
$this->blogid = $blog_id;
$this->prefix = $this->get_blog_prefix();
foreach ( $this->tables( 'blog' ) as $table => $prefixed_table ) {
$this->$table = $prefixed_table;
}
foreach ( $this->tables( 'old' ) as $table => $prefixed_table ) {
$this->$table = $prefixed_table;
}
return $old_blog_id;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::tables()](tables) wp-includes/class-wpdb.php | Returns an array of WordPress tables. |
| [wpdb::get\_blog\_prefix()](get_blog_prefix) wp-includes/class-wpdb.php | Gets blog prefix. |
| Used By | Description |
| --- | --- |
| [wp\_get\_db\_schema()](../../functions/wp_get_db_schema) wp-admin/includes/schema.php | Retrieve the SQL for creating database tables. |
| [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) . |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wpdb::close(): bool wpdb::close(): bool
===================
Closes the current database connection.
bool True if the connection was successfully closed, false if it wasn't, or if the connection doesn't exist.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function close() {
if ( ! $this->dbh ) {
return false;
}
if ( $this->use_mysqli ) {
$closed = mysqli_close( $this->dbh );
} else {
$closed = mysql_close( $this->dbh );
}
if ( $closed ) {
$this->dbh = null;
$this->ready = false;
$this->has_connected = false;
}
return $closed;
}
```
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress wpdb::get_blog_prefix( int $blog_id = null ): string wpdb::get\_blog\_prefix( int $blog\_id = null ): string
=======================================================
Gets blog prefix.
`$blog_id` int Optional Default: `null`
string Blog prefix.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function get_blog_prefix( $blog_id = null ) {
if ( is_multisite() ) {
if ( null === $blog_id ) {
$blog_id = $this->blogid;
}
$blog_id = (int) $blog_id;
if ( defined( 'MULTISITE' ) && ( 0 === $blog_id || 1 === $blog_id ) ) {
return $this->base_prefix;
} else {
return $this->base_prefix . $blog_id . '_';
}
} else {
return $this->base_prefix;
}
}
```
| Uses | Description |
| --- | --- |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| Used By | Description |
| --- | --- |
| [wp\_register\_persisted\_preferences\_meta()](../../functions/wp_register_persisted_preferences_meta) wp-includes/user.php | Registers the user meta property for persisted preferences. |
| [wp\_initialize\_site()](../../functions/wp_initialize_site) wp-includes/ms-site.php | Runs the initialization routine for a given site. |
| [wp\_default\_packages\_inline\_scripts()](../../functions/wp_default_packages_inline_scripts) wp-includes/script-loader.php | Adds inline scripts required for the WordPress JavaScript packages. |
| [WP\_User::for\_site()](../wp_user/for_site) wp-includes/class-wp-user.php | Sets the site to operate on. Defaults to the current site. |
| [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\_get\_users\_with\_no\_role()](../../functions/wp_get_users_with_no_role) wp-includes/user.php | Gets the user IDs of all users with no role on this site. |
| [get\_author\_user\_ids()](../../functions/get_author_user_ids) wp-admin/includes/deprecated.php | Get all user IDs. |
| [get\_editable\_user\_ids()](../../functions/get_editable_user_ids) wp-admin/includes/deprecated.php | Gets the IDs of any users who can edit posts. |
| [get\_nonauthor\_user\_ids()](../../functions/get_nonauthor_user_ids) wp-admin/includes/deprecated.php | Gets all users who are not authors. |
| [WP\_User::update\_user\_level\_from\_caps()](../wp_user/update_user_level_from_caps) wp-includes/class-wp-user.php | Updates the maximum user level for the user. |
| [WP\_User::remove\_all\_caps()](../wp_user/remove_all_caps) wp-includes/class-wp-user.php | Removes all of the capabilities of the user. |
| [WP\_User::\_init\_caps()](../wp_user/_init_caps) wp-includes/class-wp-user.php | Sets up capability object properties. |
| [get\_users\_of\_blog()](../../functions/get_users_of_blog) wp-includes/deprecated.php | Get users for the site. |
| [WP\_User\_Query::prepare\_query()](../wp_user_query/prepare_query) wp-includes/class-wp-user-query.php | Prepares the query variables. |
| [update\_user\_option()](../../functions/update_user_option) wp-includes/user.php | Updates user option with global blog capability. |
| [delete\_user\_option()](../../functions/delete_user_option) wp-includes/user.php | Deletes user option with global blog capability. |
| [count\_users()](../../functions/count_users) wp-includes/user.php | Counts number of users who have each of the user roles. |
| [get\_user\_option()](../../functions/get_user_option) wp-includes/user.php | Retrieves user option that can be either per Site or per Network. |
| [is\_user\_option\_local()](../../functions/is_user_option_local) wp-includes/ms-deprecated.php | Check whether a usermeta key has to do with the current blog. |
| [get\_most\_recent\_post\_of\_user()](../../functions/get_most_recent_post_of_user) wp-includes/ms-functions.php | Gets a user’s most recent post. |
| [install\_blog()](../../functions/install_blog) wp-includes/ms-deprecated.php | Install an empty blog. |
| [wpmu\_validate\_blog\_signup()](../../functions/wpmu_validate_blog_signup) wp-includes/ms-functions.php | Processes new site registrations. |
| [get\_blog\_list()](../../functions/get_blog_list) wp-includes/ms-deprecated.php | Deprecated functionality to retrieve a list of all sites. |
| [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) . |
| [wpdb::tables()](tables) wp-includes/class-wpdb.php | Returns an array of WordPress tables. |
| [wpdb::set\_prefix()](set_prefix) wp-includes/class-wpdb.php | Sets the table prefix for the WordPress tables. |
| [wpdb::set\_blog\_id()](set_blog_id) wp-includes/class-wpdb.php | Sets blog ID. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
| programming_docs |
wordpress wpdb::hide_errors(): bool wpdb::hide\_errors(): bool
==========================
Disables showing of database errors.
By default database errors are not shown.
* [wpdb::show\_errors()](show_errors)
bool Whether showing of errors was previously active.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function hide_errors() {
$show = $this->show_errors;
$this->show_errors = false;
return $show;
}
```
| Used By | Description |
| --- | --- |
| [drop\_index()](../../functions/drop_index) wp-admin/includes/upgrade.php | Drops a specified index from a table. |
| Version | Description |
| --- | --- |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wpdb::timer_stop(): float wpdb::timer\_stop(): float
==========================
Stops the debugging timer.
float Total time spent on the query, in seconds.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function timer_stop() {
return ( microtime( true ) - $this->time_start );
}
```
| Used By | Description |
| --- | --- |
| [wpdb::\_do\_query()](_do_query) wp-includes/class-wpdb.php | Internal function to perform the mysql\_query() call. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wpdb::strip_invalid_text( array $data ): array|WP_Error wpdb::strip\_invalid\_text( array $data ): array|WP\_Error
==========================================================
Strips any invalid characters based on value/charset pairs.
`$data` array Required Array of value arrays. Each value array has the keys `'value'` and `'charset'`.
An optional `'ascii'` key can be set to false to avoid redundant ASCII checks. array|[WP\_Error](../wp_error) The $data parameter, with invalid characters removed from each value.
This works as a passthrough: any additional keys such as `'field'` are retained in each value array. If we cannot remove invalid characters, a [WP\_Error](../wp_error) object is returned.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
protected function strip_invalid_text( $data ) {
$db_check_string = false;
foreach ( $data as &$value ) {
$charset = $value['charset'];
if ( is_array( $value['length'] ) ) {
$length = $value['length']['length'];
$truncate_by_byte_length = 'byte' === $value['length']['type'];
} else {
$length = false;
// Since we have no length, we'll never truncate. Initialize the variable to false.
// True would take us through an unnecessary (for this case) codepath below.
$truncate_by_byte_length = false;
}
// There's no charset to work with.
if ( false === $charset ) {
continue;
}
// Column isn't a string.
if ( ! is_string( $value['value'] ) ) {
continue;
}
$needs_validation = true;
if (
// latin1 can store any byte sequence.
'latin1' === $charset
||
// ASCII is always OK.
( ! isset( $value['ascii'] ) && $this->check_ascii( $value['value'] ) )
) {
$truncate_by_byte_length = true;
$needs_validation = false;
}
if ( $truncate_by_byte_length ) {
mbstring_binary_safe_encoding();
if ( false !== $length && strlen( $value['value'] ) > $length ) {
$value['value'] = substr( $value['value'], 0, $length );
}
reset_mbstring_encoding();
if ( ! $needs_validation ) {
continue;
}
}
// utf8 can be handled by regex, which is a bunch faster than a DB lookup.
if ( ( 'utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset ) && function_exists( 'mb_strlen' ) ) {
$regex = '/
(
(?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
| [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
| \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
| [\xE1-\xEC][\x80-\xBF]{2}
| \xED[\x80-\x9F][\x80-\xBF]
| [\xEE-\xEF][\x80-\xBF]{2}';
if ( 'utf8mb4' === $charset ) {
$regex .= '
| \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
| [\xF1-\xF3][\x80-\xBF]{3}
| \xF4[\x80-\x8F][\x80-\xBF]{2}
';
}
$regex .= '){1,40} # ...one or more times
)
| . # anything else
/x';
$value['value'] = preg_replace( $regex, '$1', $value['value'] );
if ( false !== $length && mb_strlen( $value['value'], 'UTF-8' ) > $length ) {
$value['value'] = mb_substr( $value['value'], 0, $length, 'UTF-8' );
}
continue;
}
// We couldn't use any local conversions, send it to the DB.
$value['db'] = true;
$db_check_string = true;
}
unset( $value ); // Remove by reference.
if ( $db_check_string ) {
$queries = array();
foreach ( $data as $col => $value ) {
if ( ! empty( $value['db'] ) ) {
// We're going to need to truncate by characters or bytes, depending on the length value we have.
if ( isset( $value['length']['type'] ) && 'byte' === $value['length']['type'] ) {
// Using binary causes LEFT() to truncate by bytes.
$charset = 'binary';
} else {
$charset = $value['charset'];
}
if ( $this->charset ) {
$connection_charset = $this->charset;
} else {
if ( $this->use_mysqli ) {
$connection_charset = mysqli_character_set_name( $this->dbh );
} else {
$connection_charset = mysql_client_encoding();
}
}
if ( is_array( $value['length'] ) ) {
$length = sprintf( '%.0f', $value['length']['length'] );
$queries[ $col ] = $this->prepare( "CONVERT( LEFT( CONVERT( %s USING $charset ), $length ) USING $connection_charset )", $value['value'] );
} elseif ( 'binary' !== $charset ) {
// If we don't have a length, there's no need to convert binary - it will always return the same result.
$queries[ $col ] = $this->prepare( "CONVERT( CONVERT( %s USING $charset ) USING $connection_charset )", $value['value'] );
}
unset( $data[ $col ]['db'] );
}
}
$sql = array();
foreach ( $queries as $column => $query ) {
if ( ! $query ) {
continue;
}
$sql[] = $query . " AS x_$column";
}
$this->check_current_query = false;
$row = $this->get_row( 'SELECT ' . implode( ', ', $sql ), ARRAY_A );
if ( ! $row ) {
return new WP_Error( 'wpdb_strip_invalid_text_failure', __( 'Could not strip invalid text.' ) );
}
foreach ( array_keys( $data ) as $column ) {
if ( isset( $row[ "x_$column" ] ) ) {
$data[ $column ]['value'] = $row[ "x_$column" ];
}
}
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::check\_ascii()](check_ascii) wp-includes/class-wpdb.php | Checks if a string is ASCII. |
| [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. |
| [wpdb::get\_row()](get_row) wp-includes/class-wpdb.php | Retrieves one row from the database. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wpdb::prepare()](prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [wpdb::strip\_invalid\_text\_for\_column()](strip_invalid_text_for_column) wp-includes/class-wpdb.php | Strips any invalid characters from the string for a given table and column. |
| [wpdb::strip\_invalid\_text\_from\_query()](strip_invalid_text_from_query) wp-includes/class-wpdb.php | Strips any invalid characters from the query. |
| [wpdb::process\_fields()](process_fields) wp-includes/class-wpdb.php | Processes arrays of field/value pairs and field formats. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress wpdb::determine_charset( string $charset, string $collate ): array wpdb::determine\_charset( string $charset, string $collate ): array
===================================================================
Determines the best charset and collation to use given a charset and collation.
For example, when able, utf8mb4 should be used instead of utf8.
`$charset` string Required The character set to check. `$collate` string Required The collation to check. array The most appropriate character set and collation to use.
* `charset`stringCharacter set.
* `collate`stringCollation.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function determine_charset( $charset, $collate ) {
if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) {
return compact( 'charset', 'collate' );
}
if ( 'utf8' === $charset && $this->has_cap( 'utf8mb4' ) ) {
$charset = 'utf8mb4';
}
if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
$charset = 'utf8';
$collate = str_replace( 'utf8mb4_', 'utf8_', $collate );
}
if ( 'utf8mb4' === $charset ) {
// _general_ is outdated, so we can upgrade it to _unicode_, instead.
if ( ! $collate || 'utf8_general_ci' === $collate ) {
$collate = 'utf8mb4_unicode_ci';
} else {
$collate = str_replace( 'utf8_', 'utf8mb4_', $collate );
}
}
// _unicode_520_ is a better collation, we should use that when it's available.
if ( $this->has_cap( 'utf8mb4_520' ) && 'utf8mb4_unicode_ci' === $collate ) {
$collate = 'utf8mb4_unicode_520_ci';
}
return compact( 'charset', 'collate' );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::has\_cap()](has_cap) wp-includes/class-wpdb.php | Determines whether the database or WPDB supports a particular feature. |
| Used By | Description |
| --- | --- |
| [wpdb::init\_charset()](init_charset) wp-includes/class-wpdb.php | Sets $this->charset and $this->collate. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress wpdb::__construct( string $dbuser, string $dbpassword, string $dbname, string $dbhost ) wpdb::\_\_construct( string $dbuser, string $dbpassword, string $dbname, string $dbhost )
=========================================================================================
Connects to the database server and selects a database.
Does the actual setting up of the class properties and connection to the database.
`$dbuser` string Required Database user. `$dbpassword` string Required Database password. `$dbname` string Required Database name. `$dbhost` string Required Database host. File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
if ( WP_DEBUG && WP_DEBUG_DISPLAY ) {
$this->show_errors();
}
// Use the `mysqli` extension if it exists unless `WP_USE_EXT_MYSQL` is defined as true.
if ( function_exists( 'mysqli_connect' ) ) {
$this->use_mysqli = true;
if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
$this->use_mysqli = ! WP_USE_EXT_MYSQL;
}
}
$this->dbuser = $dbuser;
$this->dbpassword = $dbpassword;
$this->dbname = $dbname;
$this->dbhost = $dbhost;
// wp-config.php creation will manually connect when ready.
if ( defined( 'WP_SETUP_CONFIG' ) ) {
return;
}
$this->db_connect();
}
```
| Uses | Description |
| --- | --- |
| [wpdb::show\_errors()](show_errors) wp-includes/class-wpdb.php | Enables showing of database errors. |
| [wpdb::db\_connect()](db_connect) wp-includes/class-wpdb.php | Connects to and selects database. |
| Used By | Description |
| --- | --- |
| [require\_wp\_db()](../../functions/require_wp_db) wp-includes/load.php | Load the database class file and instantiate the `$wpdb` global. |
| Version | Description |
| --- | --- |
| [2.0.8](https://developer.wordpress.org/reference/since/2.0.8/) | Introduced. |
wordpress wpdb::get_col_length( string $table, string $column ): array|false|WP_Error wpdb::get\_col\_length( string $table, string $column ): array|false|WP\_Error
==============================================================================
Retrieves the maximum string length allowed in a given column.
The length may either be specified as a byte length or a character length.
`$table` string Required Table name. `$column` string Required Column name. array|false|[WP\_Error](../wp_error) Array of column length information, false if the column has no length (for example, numeric column), [WP\_Error](../wp_error) object if there was an error.
* `length`intThe column length.
* `type`stringOne of `'byte'` or `'char'`
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function get_col_length( $table, $column ) {
$tablekey = strtolower( $table );
$columnkey = strtolower( $column );
// Skip this entirely if this isn't a MySQL database.
if ( empty( $this->is_mysql ) ) {
return false;
}
if ( empty( $this->col_meta[ $tablekey ] ) ) {
// This primes column information for us.
$table_charset = $this->get_table_charset( $table );
if ( is_wp_error( $table_charset ) ) {
return $table_charset;
}
}
if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
return false;
}
$typeinfo = explode( '(', $this->col_meta[ $tablekey ][ $columnkey ]->Type );
$type = strtolower( $typeinfo[0] );
if ( ! empty( $typeinfo[1] ) ) {
$length = trim( $typeinfo[1], ')' );
} else {
$length = false;
}
switch ( $type ) {
case 'char':
case 'varchar':
return array(
'type' => 'char',
'length' => (int) $length,
);
case 'binary':
case 'varbinary':
return array(
'type' => 'byte',
'length' => (int) $length,
);
case 'tinyblob':
case 'tinytext':
return array(
'type' => 'byte',
'length' => 255, // 2^8 - 1
);
case 'blob':
case 'text':
return array(
'type' => 'byte',
'length' => 65535, // 2^16 - 1
);
case 'mediumblob':
case 'mediumtext':
return array(
'type' => 'byte',
'length' => 16777215, // 2^24 - 1
);
case 'longblob':
case 'longtext':
return array(
'type' => 'byte',
'length' => 4294967295, // 2^32 - 1
);
default:
return false;
}
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_table\_charset()](get_table_charset) wp-includes/class-wpdb.php | Retrieves the character set for the given table. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [wp\_get\_comment\_fields\_max\_lengths()](../../functions/wp_get_comment_fields_max_lengths) wp-includes/comment.php | Retrieves the maximum character lengths for the comment form fields. |
| [wpdb::process\_field\_lengths()](process_field_lengths) wp-includes/class-wpdb.php | For string fields, records the maximum string length that field can safely save. |
| [wpdb::strip\_invalid\_text\_for\_column()](strip_invalid_text_for_column) wp-includes/class-wpdb.php | Strips any invalid characters from the string for a given table and column. |
| Version | Description |
| --- | --- |
| [4.2.1](https://developer.wordpress.org/reference/since/4.2.1/) | Introduced. |
wordpress wpdb::process_fields( string $table, array $data, mixed $format ): array|false wpdb::process\_fields( string $table, array $data, mixed $format ): array|false
===============================================================================
Processes arrays of field/value pairs and field formats.
This is a helper method for [wpdb](../wpdb)’s CRUD methods, which take field/value pairs for inserts, updates, and where clauses. This method first pairs each value with a format. Then it determines the charset of that field, using that to determine if any invalid text would be stripped. If text is stripped, then field processing is rejected and the query fails.
`$table` string Required Table name. `$data` array Required Field/value pair. `$format` mixed Required Format for each field. array|false An array of fields that contain paired value and formats.
False for invalid values.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
protected function process_fields( $table, $data, $format ) {
$data = $this->process_field_formats( $data, $format );
if ( false === $data ) {
return false;
}
$data = $this->process_field_charsets( $data, $table );
if ( false === $data ) {
return false;
}
$data = $this->process_field_lengths( $data, $table );
if ( false === $data ) {
return false;
}
$converted_data = $this->strip_invalid_text( $data );
if ( $data !== $converted_data ) {
$problem_fields = array();
foreach ( $data as $field => $value ) {
if ( $value !== $converted_data[ $field ] ) {
$problem_fields[] = $field;
}
}
wp_load_translations_early();
if ( 1 === count( $problem_fields ) ) {
$this->last_error = sprintf(
/* translators: %s: Database field where the error occurred. */
__( 'WordPress database error: Processing the value for the following field failed: %s. The supplied value may be too long or contains invalid data.' ),
reset( $problem_fields )
);
} else {
$this->last_error = sprintf(
/* translators: %s: Database fields where the error occurred. */
__( 'WordPress database error: Processing the values for the following fields failed: %s. The supplied values may be too long or contain invalid data.' ),
implode( ', ', $problem_fields )
);
}
return false;
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::process\_field\_lengths()](process_field_lengths) wp-includes/class-wpdb.php | For string fields, records the maximum string length that field can safely save. |
| [wpdb::strip\_invalid\_text()](strip_invalid_text) wp-includes/class-wpdb.php | Strips any invalid characters based on value/charset pairs. |
| [wpdb::process\_field\_formats()](process_field_formats) wp-includes/class-wpdb.php | Prepares arrays of value/format pairs as passed to [wpdb](../wpdb) CRUD methods. |
| [wpdb::process\_field\_charsets()](process_field_charsets) wp-includes/class-wpdb.php | Adds field charsets to field/value/format arrays generated by [wpdb::process\_field\_formats()](process_field_formats). |
| [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. |
| Used By | Description |
| --- | --- |
| [wpdb::\_insert\_replace\_helper()](_insert_replace_helper) wp-includes/class-wpdb.php | Helper function for insert and replace. |
| [wpdb::update()](update) wp-includes/class-wpdb.php | Updates a row in the table. |
| [wpdb::delete()](delete) wp-includes/class-wpdb.php | Deletes a row in the table. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
| programming_docs |
wordpress wpdb::bail( string $message, string $error_code = '500' ): void|false wpdb::bail( string $message, string $error\_code = '500' ): void|false
======================================================================
Wraps errors in a nice header and footer and dies.
Will not die if wpdb::$show\_errors is false.
`$message` string Required The error message. `$error_code` string Optional A computer-readable string to identify the error.
Default `'500'`. Default: `'500'`
void|false Void if the showing of errors is enabled, false if disabled.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function bail( $message, $error_code = '500' ) {
if ( $this->show_errors ) {
$error = '';
if ( $this->use_mysqli ) {
if ( $this->dbh instanceof mysqli ) {
$error = mysqli_error( $this->dbh );
} elseif ( mysqli_connect_errno() ) {
$error = mysqli_connect_error();
}
} else {
if ( is_resource( $this->dbh ) ) {
$error = mysql_error( $this->dbh );
} else {
$error = mysql_error();
}
}
if ( $error ) {
$message = '<p><code>' . $error . "</code></p>\n" . $message;
}
wp_die( $message );
} else {
if ( class_exists( 'WP_Error', false ) ) {
$this->error = new WP_Error( $error_code, $message );
} else {
$this->error = $message;
}
return false;
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [wpdb::check\_connection()](check_connection) wp-includes/class-wpdb.php | Checks that the connection to the database is still up. If not, try to reconnect. |
| [wpdb::select()](select) wp-includes/class-wpdb.php | Selects a database using the current or provided database connection. |
| [wpdb::db\_connect()](db_connect) wp-includes/class-wpdb.php | Connects to and selects database. |
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress wpdb::escape( string|array $data ): string|array wpdb::escape( string|array $data ): string|array
================================================
This method has been deprecated. Use [wpdb::prepare()](prepare) instead.
Do not use, deprecated.
Use [esc\_sql()](../../functions/esc_sql) or [wpdb::prepare()](prepare) instead.
* [wpdb::prepare()](prepare)
* [esc\_sql()](../../functions/esc_sql)
`$data` string|array Required Data to escape. string|array Escaped data, in the same type as supplied.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function escape( $data ) {
if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) ) {
_deprecated_function( __METHOD__, '3.6.0', 'wpdb::prepare() or esc_sql()' );
}
if ( is_array( $data ) ) {
foreach ( $data as $k => $v ) {
if ( is_array( $v ) ) {
$data[ $k ] = $this->escape( $v, 'recursive' );
} else {
$data[ $k ] = $this->_weak_escape( $v, 'internal' );
}
}
} else {
$data = $this->_weak_escape( $data, 'internal' );
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::\_weak\_escape()](_weak_escape) wp-includes/class-wpdb.php | Do not use, deprecated. |
| [wpdb::escape()](escape) wp-includes/class-wpdb.php | Do not use, deprecated. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Used By | Description |
| --- | --- |
| [wpdb::escape()](escape) wp-includes/class-wpdb.php | Do not use, deprecated. |
| Version | Description |
| --- | --- |
| [3.6.0](https://developer.wordpress.org/reference/since/3.6.0/) | Use [wpdb::prepare()](prepare) |
| [0.71](https://developer.wordpress.org/reference/since/0.71/) | Introduced. |
wordpress wpdb::_escape( string|array $data ): string|array wpdb::\_escape( string|array $data ): string|array
==================================================
Escapes data. Works on arrays.
`$data` string|array Required Data to escape. string|array Escaped data, in the same type as supplied.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function _escape( $data ) {
if ( is_array( $data ) ) {
foreach ( $data as $k => $v ) {
if ( is_array( $v ) ) {
$data[ $k ] = $this->_escape( $v );
} else {
$data[ $k ] = $this->_real_escape( $v );
}
}
} else {
$data = $this->_real_escape( $data );
}
return $data;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::\_escape()](_escape) wp-includes/class-wpdb.php | Escapes data. Works on arrays. |
| [wpdb::\_real\_escape()](_real_escape) wp-includes/class-wpdb.php | Real escape, using mysqli\_real\_escape\_string() or mysql\_real\_escape\_string(). |
| Used By | Description |
| --- | --- |
| [WP\_Network\_Query::get\_network\_ids()](../wp_network_query/get_network_ids) wp-includes/class-wp-network-query.php | Used internally to get a list of network IDs matching the query vars. |
| [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. |
| [esc\_sql()](../../functions/esc_sql) wp-includes/formatting.php | Escapes data for use in a MySQL query. |
| [wpdb::\_escape()](_escape) wp-includes/class-wpdb.php | Escapes data. Works on arrays. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress wpdb::escape_by_ref( string $string ) wpdb::escape\_by\_ref( string $string )
=======================================
Escapes content by reference for insertion into the database, for security.
`$string` string Required String to escape. File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function escape_by_ref( &$string ) {
if ( ! is_float( $string ) ) {
$string = $this->_real_escape( $string );
}
}
```
| Uses | Description |
| --- | --- |
| [wpdb::\_real\_escape()](_real_escape) wp-includes/class-wpdb.php | Real escape, using mysqli\_real\_escape\_string() or mysql\_real\_escape\_string(). |
| Version | Description |
| --- | --- |
| [2.3.0](https://developer.wordpress.org/reference/since/2.3.0/) | Introduced. |
wordpress wpdb::add_placeholder_escape( string $query ): string wpdb::add\_placeholder\_escape( string $query ): string
=======================================================
Adds a placeholder escape string, to escape anything that resembles a printf() placeholder.
`$query` string Required The query to escape. string The query with the placeholder escape string inserted where necessary.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function add_placeholder_escape( $query ) {
/*
* To prevent returning anything that even vaguely resembles a placeholder,
* we clobber every % we can find.
*/
return str_replace( '%', $this->placeholder_escape(), $query );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::placeholder\_escape()](placeholder_escape) wp-includes/class-wpdb.php | Generates and returns a placeholder escape string for use in queries returned by ::prepare(). |
| Used By | Description |
| --- | --- |
| [wpdb::\_real\_escape()](_real_escape) wp-includes/class-wpdb.php | Real escape, using mysqli\_real\_escape\_string() or mysql\_real\_escape\_string(). |
| [wpdb::prepare()](prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Version | Description |
| --- | --- |
| [4.8.3](https://developer.wordpress.org/reference/since/4.8.3/) | Introduced. |
wordpress wpdb::delete( string $table, array $where, array|string $where_format = null ): int|false wpdb::delete( string $table, array $where, array|string $where\_format = null ): int|false
==========================================================================================
Deletes a row in the table.
Examples:
```
wpdb::delete( 'table', array( 'ID' => 1 ) )
wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
```
* [wpdb::prepare()](prepare)
* wpdb::$field\_types
* [wp\_set\_wpdb\_vars()](../../functions/wp_set_wpdb_vars)
`$table` string Required Table name. `$where` array Required A named array of WHERE clauses (in column => value pairs).
Multiple clauses will be joined with ANDs.
Both $where columns and $where values should be "raw".
Sending a null value will create an IS NULL comparison - the corresponding format will be ignored in this case. `$where_format` array|string Optional An array of formats to be mapped to each of the values in $where.
If string, that format will be used for all of the items in $where.
A format is one of `'%d'`, `'%f'`, `'%s'` (integer, float, string).
If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field\_types. Default: `null`
int|false The number of rows deleted, or false on error.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function delete( $table, $where, $where_format = null ) {
if ( ! is_array( $where ) ) {
return false;
}
$where = $this->process_fields( $table, $where, $where_format );
if ( false === $where ) {
return false;
}
$conditions = array();
$values = array();
foreach ( $where as $field => $value ) {
if ( is_null( $value['value'] ) ) {
$conditions[] = "`$field` IS NULL";
continue;
}
$conditions[] = "`$field` = " . $value['format'];
$values[] = $value['value'];
}
$conditions = implode( ' AND ', $conditions );
$sql = "DELETE FROM `$table` WHERE $conditions";
$this->check_current_query = false;
return $this->query( $this->prepare( $sql, $values ) );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::process\_fields()](process_fields) wp-includes/class-wpdb.php | Processes arrays of field/value pairs and field formats. |
| [wpdb::query()](query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| [wpdb::prepare()](prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [wp\_delete\_signup\_on\_user\_delete()](../../functions/wp_delete_signup_on_user_delete) wp-includes/ms-functions.php | Deletes an associated signup entry when a user is deleted from the database. |
| [wp\_delete\_site()](../../functions/wp_delete_site) wp-includes/ms-site.php | Deletes a site from the database. |
| [delete\_network\_option()](../../functions/delete_network_option) wp-includes/option.php | Removes a network option by name. |
| [wpmu\_delete\_user()](../../functions/wpmu_delete_user) wp-admin/includes/ms.php | Delete a user from the network and remove from all sites. |
| [wp\_install\_defaults()](../../functions/wp_install_defaults) wp-admin/includes/upgrade.php | Creates the initial content for a newly-installed site. |
| [wp\_delete\_user()](../../functions/wp_delete_user) wp-admin/includes/user.php | Remove user and optionally reassign posts and links to another user. |
| [wp\_delete\_link()](../../functions/wp_delete_link) wp-admin/includes/bookmark.php | Deletes a specified link from the database. |
| [wp\_insert\_term()](../../functions/wp_insert_term) wp-includes/taxonomy.php | Adds a new term to the database. |
| [wp\_delete\_term()](../../functions/wp_delete_term) wp-includes/taxonomy.php | Removes a term from the database. |
| [delete\_option()](../../functions/delete_option) wp-includes/option.php | Removes option by name. Prevents removal of protected WordPress options. |
| [wp\_delete\_attachment()](../../functions/wp_delete_attachment) wp-includes/post.php | Trashes or deletes an attachment. |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [wpmu\_validate\_user\_signup()](../../functions/wpmu_validate_user_signup) wp-includes/ms-functions.php | Sanitizes and validates data required for a user sign-up. |
| [wpmu\_validate\_blog\_signup()](../../functions/wpmu_validate_blog_signup) wp-includes/ms-functions.php | Processes new site registrations. |
| [wp\_delete\_comment()](../../functions/wp_delete_comment) wp-includes/comment.php | Trashes or deletes a comment. |
| [delete\_metadata\_by\_mid()](../../functions/delete_metadata_by_mid) wp-includes/meta.php | Deletes metadata by meta ID. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress wpdb::strip_invalid_text_for_column( string $table, string $column, string $value ): string|WP_Error wpdb::strip\_invalid\_text\_for\_column( string $table, string $column, string $value ): string|WP\_Error
=========================================================================================================
Strips any invalid characters from the string for a given table and column.
`$table` string Required Table name. `$column` string Required Column name. `$value` string Required The text to check. string|[WP\_Error](../wp_error) The converted string, or a [WP\_Error](../wp_error) object if the conversion fails.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function strip_invalid_text_for_column( $table, $column, $value ) {
if ( ! is_string( $value ) ) {
return $value;
}
$charset = $this->get_col_charset( $table, $column );
if ( ! $charset ) {
// Not a string column.
return $value;
} elseif ( is_wp_error( $charset ) ) {
// Bail on real errors.
return $charset;
}
$data = array(
$column => array(
'value' => $value,
'charset' => $charset,
'length' => $this->get_col_length( $table, $column ),
),
);
$data = $this->strip_invalid_text( $data );
if ( is_wp_error( $data ) ) {
return $data;
}
return $data[ $column ]['value'];
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_col\_length()](get_col_length) wp-includes/class-wpdb.php | Retrieves the maximum string length allowed in a given column. |
| [wpdb::get\_col\_charset()](get_col_charset) wp-includes/class-wpdb.php | Retrieves the character set for the given column. |
| [wpdb::strip\_invalid\_text()](strip_invalid_text) wp-includes/class-wpdb.php | Strips any invalid characters based on value/charset pairs. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [edit\_post()](../../functions/edit_post) wp-admin/includes/post.php | Updates an existing post with values provided in `$_POST`. |
| [sanitize\_option()](../../functions/sanitize_option) wp-includes/formatting.php | Sanitizes various option values based on the nature of the option. |
| [wp\_new\_comment()](../../functions/wp_new_comment) wp-includes/comment.php | Adds a new comment to the database. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress wpdb::_insert_replace_helper( string $table, array $data, array|string $format = null, string $type = 'INSERT' ): int|false wpdb::\_insert\_replace\_helper( string $table, array $data, array|string $format = null, string $type = 'INSERT' ): int|false
==============================================================================================================================
Helper function for insert and replace.
Runs an insert or replace query based on $type argument.
* [wpdb::prepare()](prepare)
* wpdb::$field\_types
* [wp\_set\_wpdb\_vars()](../../functions/wp_set_wpdb_vars)
`$table` string Required Table name. `$data` array Required Data to insert (in column => value pairs).
Both $data columns and $data values should be "raw" (neither should be SQL escaped).
Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case. `$format` array|string Optional An array of formats to be mapped to each of the value in $data.
If string, that format will be used for all of the values in $data.
A format is one of `'%d'`, `'%f'`, `'%s'` (integer, float, string).
If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field\_types. Default: `null`
`$type` string Optional Type of operation. Possible values include `'INSERT'` or `'REPLACE'`.
Default `'INSERT'`. Default: `'INSERT'`
int|false The number of rows affected, or false on error.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
$this->insert_id = 0;
if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ), true ) ) {
return false;
}
$data = $this->process_fields( $table, $data, $format );
if ( false === $data ) {
return false;
}
$formats = array();
$values = array();
foreach ( $data as $value ) {
if ( is_null( $value['value'] ) ) {
$formats[] = 'NULL';
continue;
}
$formats[] = $value['format'];
$values[] = $value['value'];
}
$fields = '`' . implode( '`, `', array_keys( $data ) ) . '`';
$formats = implode( ', ', $formats );
$sql = "$type INTO `$table` ($fields) VALUES ($formats)";
$this->check_current_query = false;
return $this->query( $this->prepare( $sql, $values ) );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::process\_fields()](process_fields) wp-includes/class-wpdb.php | Processes arrays of field/value pairs and field formats. |
| [wpdb::query()](query) wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| [wpdb::prepare()](prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [wpdb::insert()](insert) wp-includes/class-wpdb.php | Inserts a row into the table. |
| [wpdb::replace()](replace) wp-includes/class-wpdb.php | Replaces a row in the table. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress wpdb::_real_escape( string $string ): string wpdb::\_real\_escape( string $string ): string
==============================================
Real escape, using mysqli\_real\_escape\_string() or mysql\_real\_escape\_string().
* [mysqli\_real\_escape\_string()](../../functions/mysqli_real_escape_string)
* [mysql\_real\_escape\_string()](../../functions/mysql_real_escape_string)
`$string` string Required String to escape. string Escaped string.
File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/)
```
public function _real_escape( $string ) {
if ( ! is_scalar( $string ) ) {
return '';
}
if ( $this->dbh ) {
if ( $this->use_mysqli ) {
$escaped = mysqli_real_escape_string( $this->dbh, $string );
} else {
$escaped = mysql_real_escape_string( $string, $this->dbh );
}
} else {
$class = get_class( $this );
wp_load_translations_early();
/* translators: %s: Database access abstraction class, usually wpdb or a class extending wpdb. */
_doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );
$escaped = addslashes( $string );
}
return $this->add_placeholder_escape( $escaped );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::add\_placeholder\_escape()](add_placeholder_escape) wp-includes/class-wpdb.php | Adds a placeholder escape string, to escape anything that resembles a printf() placeholder. |
| [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 |
| --- | --- |
| [wpdb::\_escape()](_escape) wp-includes/class-wpdb.php | Escapes data. Works on arrays. |
| [wpdb::escape\_by\_ref()](escape_by_ref) wp-includes/class-wpdb.php | Escapes content by reference for insertion into the database, for security. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Community_Events::get_cached_events(): array|false WP\_Community\_Events::get\_cached\_events(): array|false
=========================================================
Gets cached events.
array|false An array containing `location` and `events` items on success, false on failure.
File: `wp-admin/includes/class-wp-community-events.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-community-events.php/)
```
public function get_cached_events() {
$transient_key = $this->get_events_transient_key( $this->user_location );
if ( ! $transient_key ) {
return false;
}
$cached_response = get_site_transient( $transient_key );
if ( isset( $cached_response['events'] ) ) {
$cached_response['events'] = $this->trim_events( $cached_response['events'] );
}
return $cached_response;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Community\_Events::trim\_events()](trim_events) wp-admin/includes/class-wp-community-events.php | Prepares the event list for presentation. |
| [WP\_Community\_Events::get\_events\_transient\_key()](get_events_transient_key) wp-admin/includes/class-wp-community-events.php | Generates a transient key based on user location. |
| [get\_site\_transient()](../../functions/get_site_transient) wp-includes/option.php | Retrieves the value of a site transient. |
| Used By | Description |
| --- | --- |
| [WP\_Community\_Events::get\_events()](get_events) wp-admin/includes/class-wp-community-events.php | Gets data about events near a particular location. |
| Version | Description |
| --- | --- |
| [5.5.2](https://developer.wordpress.org/reference/since/5.5.2/) | Response no longer contains formatted date field. They're added in `wp.communityEvents.populateDynamicEventFields()` now. |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Community_Events::get_events( string $location_search = '', string $timezone = '' ): array|WP_Error WP\_Community\_Events::get\_events( string $location\_search = '', string $timezone = '' ): array|WP\_Error
===========================================================================================================
Gets data about events near a particular location.
Cached events will be immediately returned if the `user_location` property is set for the current user, and cached events exist for that location.
Otherwise, this method sends a request to the w.org Events API with location data. The API will send back a recognized location based on the data, along with nearby events.
The browser’s request for events is proxied with this method, rather than having the browser make the request directly to api.wordpress.org, because it allows results to be cached server-side and shared with other users and sites in the network. This makes the process more efficient, since increasing the number of visits that get cached data means users don’t have to wait as often; if the user’s browser made the request directly, it would also need to make a second request to WP in order to pass the data for caching. Having WP make the request also introduces the opportunity to anonymize the IP before sending it to w.org, which mitigates possible privacy concerns.
`$location_search` string Optional City name to help determine the location.
e.g., "Seattle". Default: `''`
`$timezone` string Optional Timezone to help determine the location.
Default: `''`
array|[WP\_Error](../wp_error) A [WP\_Error](../wp_error) on failure; an array with location and events on success.
File: `wp-admin/includes/class-wp-community-events.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-community-events.php/)
```
public function get_events( $location_search = '', $timezone = '' ) {
$cached_events = $this->get_cached_events();
if ( ! $location_search && $cached_events ) {
return $cached_events;
}
// Include an unmodified $wp_version.
require ABSPATH . WPINC . '/version.php';
$api_url = 'http://api.wordpress.org/events/1.0/';
$request_args = $this->get_request_args( $location_search, $timezone );
$request_args['user-agent'] = 'WordPress/' . $wp_version . '; ' . home_url( '/' );
if ( wp_http_supports( array( 'ssl' ) ) ) {
$api_url = set_url_scheme( $api_url, 'https' );
}
$response = wp_remote_get( $api_url, $request_args );
$response_code = wp_remote_retrieve_response_code( $response );
$response_body = json_decode( wp_remote_retrieve_body( $response ), true );
$response_error = null;
if ( is_wp_error( $response ) ) {
$response_error = $response;
} elseif ( 200 !== $response_code ) {
$response_error = new WP_Error(
'api-error',
/* translators: %d: Numeric HTTP status code, e.g. 400, 403, 500, 504, etc. */
sprintf( __( 'Invalid API response code (%d).' ), $response_code )
);
} elseif ( ! isset( $response_body['location'], $response_body['events'] ) ) {
$response_error = new WP_Error(
'api-invalid-response',
isset( $response_body['error'] ) ? $response_body['error'] : __( 'Unknown API error.' )
);
}
if ( is_wp_error( $response_error ) ) {
return $response_error;
} else {
$expiration = false;
if ( isset( $response_body['ttl'] ) ) {
$expiration = $response_body['ttl'];
unset( $response_body['ttl'] );
}
/*
* The IP in the response is usually the same as the one that was sent
* in the request, but in some cases it is different. In those cases,
* it's important to reset it back to the IP from the request.
*
* For example, if the IP sent in the request is private (e.g., 192.168.1.100),
* then the API will ignore that and use the corresponding public IP instead,
* and the public IP will get returned. If the public IP were saved, though,
* then get_cached_events() would always return `false`, because the transient
* would be generated based on the public IP when saving the cache, but generated
* based on the private IP when retrieving the cache.
*/
if ( ! empty( $response_body['location']['ip'] ) ) {
$response_body['location']['ip'] = $request_args['body']['ip'];
}
/*
* The API doesn't return a description for latitude/longitude requests,
* but the description is already saved in the user location, so that
* one can be used instead.
*/
if ( $this->coordinates_match( $request_args['body'], $response_body['location'] ) && empty( $response_body['location']['description'] ) ) {
$response_body['location']['description'] = $this->user_location['description'];
}
/*
* Store the raw response, because events will expire before the cache does.
* The response will need to be processed every page load.
*/
$this->cache_events( $response_body, $expiration );
$response_body['events'] = $this->trim_events( $response_body['events'] );
return $response_body;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Community\_Events::trim\_events()](trim_events) wp-admin/includes/class-wp-community-events.php | Prepares the event list for presentation. |
| [WP\_Community\_Events::get\_cached\_events()](get_cached_events) wp-admin/includes/class-wp-community-events.php | Gets cached events. |
| [WP\_Community\_Events::get\_request\_args()](get_request_args) wp-admin/includes/class-wp-community-events.php | Builds an array of args to use in an HTTP request to the w.org Events API. |
| [WP\_Community\_Events::coordinates\_match()](coordinates_match) wp-admin/includes/class-wp-community-events.php | Test if two pairs of latitude/longitude coordinates match each other. |
| [WP\_Community\_Events::cache\_events()](cache_events) wp-admin/includes/class-wp-community-events.php | Caches an array of events data from the Events API. |
| [set\_url\_scheme()](../../functions/set_url_scheme) wp-includes/link-template.php | Sets the scheme for a URL. |
| [wp\_http\_supports()](../../functions/wp_http_supports) wp-includes/http.php | Determines if there is an HTTP Transport that can process this request. |
| [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\_body()](../../functions/wp_remote_retrieve_body) wp-includes/http.php | Retrieve only the body from the raw response. |
| [\_\_()](../../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. |
| [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.2](https://developer.wordpress.org/reference/since/5.5.2/) | Response no longer contains formatted date field. They're added in `wp.communityEvents.populateDynamicEventFields()` now. |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Community_Events::cache_events( array $events, int|false $expiration = false ): bool WP\_Community\_Events::cache\_events( array $events, int|false $expiration = false ): bool
==========================================================================================
Caches an array of events data from the Events API.
`$events` array Required Response body from the API request. `$expiration` int|false Optional Amount of time to cache the events. Defaults to false. Default: `false`
bool true if events were cached; false if not.
File: `wp-admin/includes/class-wp-community-events.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-community-events.php/)
```
protected function cache_events( $events, $expiration = false ) {
$set = false;
$transient_key = $this->get_events_transient_key( $events['location'] );
$cache_expiration = $expiration ? absint( $expiration ) : HOUR_IN_SECONDS * 12;
if ( $transient_key ) {
$set = set_site_transient( $transient_key, $events, $cache_expiration );
}
return $set;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Community\_Events::get\_events\_transient\_key()](get_events_transient_key) wp-admin/includes/class-wp-community-events.php | Generates a transient key based on user location. |
| [set\_site\_transient()](../../functions/set_site_transient) wp-includes/option.php | Sets/updates the value of a site transient. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Used By | Description |
| --- | --- |
| [WP\_Community\_Events::get\_events()](get_events) wp-admin/includes/class-wp-community-events.php | Gets data about events near a particular location. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Community_Events::get_unsafe_client_ip(): string|false WP\_Community\_Events::get\_unsafe\_client\_ip(): string|false
==============================================================
Determines the user’s actual IP address and attempts to partially anonymize an IP address by converting it to a network ID.
Geolocating the network ID usually returns a similar location as the actual IP, but provides some privacy for the user.
$\_SERVER[‘REMOTE\_ADDR’] cannot be used in all cases, such as when the user is making their request through a proxy, or when the web server is behind a proxy. In those cases, $\_SERVER[‘REMOTE\_ADDR’] is set to the proxy address rather than the user’s actual address.
Modified from <https://stackoverflow.com/a/2031935/450127>, MIT license.
Modified from <https://github.com/geertw/php-ip-anonymizer>, MIT license.
SECURITY WARNING: This function is *NOT* intended to be used in circumstances where the authenticity of the IP address matters. This does *NOT* guarantee that the returned address is valid or accurate, and it can be easily spoofed.
string|false The anonymized address on success; the given address or false on failure.
File: `wp-admin/includes/class-wp-community-events.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-community-events.php/)
```
public static function get_unsafe_client_ip() {
$client_ip = false;
// In order of preference, with the best ones for this purpose first.
$address_headers = array(
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR',
);
foreach ( $address_headers as $header ) {
if ( array_key_exists( $header, $_SERVER ) ) {
/*
* HTTP_X_FORWARDED_FOR can contain a chain of comma-separated
* addresses. The first one is the original client. It can't be
* trusted for authenticity, but we don't need to for this purpose.
*/
$address_chain = explode( ',', $_SERVER[ $header ] );
$client_ip = trim( $address_chain[0] );
break;
}
}
if ( ! $client_ip ) {
return false;
}
$anon_ip = wp_privacy_anonymize_ip( $client_ip, true );
if ( '0.0.0.0' === $anon_ip || '::' === $anon_ip ) {
return false;
}
return $anon_ip;
}
```
| Uses | Description |
| --- | --- |
| [wp\_privacy\_anonymize\_ip()](../../functions/wp_privacy_anonymize_ip) wp-includes/functions.php | Returns an anonymized IPv4 or IPv6 address. |
| Used By | Description |
| --- | --- |
| [wp\_localize\_community\_events()](../../functions/wp_localize_community_events) wp-includes/script-loader.php | Localizes community events data that needs to be passed to dashboard.js. |
| [WP\_Community\_Events::get\_request\_args()](get_request_args) wp-admin/includes/class-wp-community-events.php | Builds an array of args to use in an HTTP request to the w.org Events API. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Community_Events::get_events_transient_key( array $location ): string|false WP\_Community\_Events::get\_events\_transient\_key( array $location ): string|false
===================================================================================
Generates a transient key based on user location.
This could be reduced to a one-liner in the calling functions, but it’s intentionally a separate function because it’s called from multiple functions, and having it abstracted keeps the logic consistent and DRY, which is less prone to errors.
`$location` array Required Should contain `'latitude'` and `'longitude'` indexes. string|false Transient key on success, false on failure.
File: `wp-admin/includes/class-wp-community-events.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-community-events.php/)
```
protected function get_events_transient_key( $location ) {
$key = false;
if ( isset( $location['ip'] ) ) {
$key = 'community-events-' . md5( $location['ip'] );
} elseif ( isset( $location['latitude'], $location['longitude'] ) ) {
$key = 'community-events-' . md5( $location['latitude'] . $location['longitude'] );
}
return $key;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Community\_Events::cache\_events()](cache_events) wp-admin/includes/class-wp-community-events.php | Caches an array of events data from the Events API. |
| [WP\_Community\_Events::get\_cached\_events()](get_cached_events) wp-admin/includes/class-wp-community-events.php | Gets cached events. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Community_Events::coordinates_match( array $a, array $b ): bool WP\_Community\_Events::coordinates\_match( array $a, array $b ): bool
=====================================================================
Test if two pairs of latitude/longitude coordinates match each other.
`$a` array Required The first pair, with indexes `'latitude'` and `'longitude'`. `$b` array Required The second pair, with indexes `'latitude'` and `'longitude'`. bool True if they match, false if they don't.
File: `wp-admin/includes/class-wp-community-events.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-community-events.php/)
```
protected function coordinates_match( $a, $b ) {
if ( ! isset( $a['latitude'], $a['longitude'], $b['latitude'], $b['longitude'] ) ) {
return false;
}
return $a['latitude'] === $b['latitude'] && $a['longitude'] === $b['longitude'];
}
```
| Used By | Description |
| --- | --- |
| [WP\_Community\_Events::get\_events()](get_events) wp-admin/includes/class-wp-community-events.php | Gets data about events near a particular location. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Community_Events::format_event_data_time( array $response_body ): array WP\_Community\_Events::format\_event\_data\_time( array $response\_body ): array
================================================================================
This method has been deprecated. No longer used in core instead.
Adds formatted date and time items for each event in an API response.
This has to be called after the data is pulled from the cache, because the cached events are shared by all users. If it was called before storing the cache, then all users would see the events in the localized data/time of the user who triggered the cache refresh, rather than their own.
`$response_body` array Required The response which contains the events. array The response with dates and times formatted.
File: `wp-admin/includes/class-wp-community-events.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-community-events.php/)
```
protected function format_event_data_time( $response_body ) {
_deprecated_function(
__METHOD__,
'5.5.2',
'This is no longer used by core, and only kept for backward compatibility.'
);
if ( isset( $response_body['events'] ) ) {
foreach ( $response_body['events'] as $key => $event ) {
$timestamp = strtotime( $event['date'] );
/*
* The `date_format` option is not used because it's important
* in this context to keep the day of the week in the formatted date,
* so that users can tell at a glance if the event is on a day they
* are available, without having to open the link.
*/
/* translators: Date format for upcoming events on the dashboard. Include the day of the week. See https://www.php.net/manual/datetime.format.php */
$formatted_date = date_i18n( __( 'l, M j, Y' ), $timestamp );
$formatted_time = date_i18n( get_option( 'time_format' ), $timestamp );
if ( isset( $event['end_date'] ) ) {
$end_timestamp = strtotime( $event['end_date'] );
$formatted_end_date = date_i18n( __( 'l, M j, Y' ), $end_timestamp );
if ( 'meetup' !== $event['type'] && $formatted_end_date !== $formatted_date ) {
/* translators: Upcoming events month format. See https://www.php.net/manual/datetime.format.php */
$start_month = date_i18n( _x( 'F', 'upcoming events month format' ), $timestamp );
$end_month = date_i18n( _x( 'F', 'upcoming events month format' ), $end_timestamp );
if ( $start_month === $end_month ) {
$formatted_date = sprintf(
/* translators: Date string for upcoming events. 1: Month, 2: Starting day, 3: Ending day, 4: Year. */
__( '%1$s %2$d–%3$d, %4$d' ),
$start_month,
/* translators: Upcoming events day format. See https://www.php.net/manual/datetime.format.php */
date_i18n( _x( 'j', 'upcoming events day format' ), $timestamp ),
date_i18n( _x( 'j', 'upcoming events day format' ), $end_timestamp ),
/* translators: Upcoming events year format. See https://www.php.net/manual/datetime.format.php */
date_i18n( _x( 'Y', 'upcoming events year format' ), $timestamp )
);
} else {
$formatted_date = sprintf(
/* translators: Date string for upcoming events. 1: Starting month, 2: Starting day, 3: Ending month, 4: Ending day, 5: Year. */
__( '%1$s %2$d – %3$s %4$d, %5$d' ),
$start_month,
date_i18n( _x( 'j', 'upcoming events day format' ), $timestamp ),
$end_month,
date_i18n( _x( 'j', 'upcoming events day format' ), $end_timestamp ),
date_i18n( _x( 'Y', 'upcoming events year format' ), $timestamp )
);
}
$formatted_date = wp_maybe_decline_date( $formatted_date, 'F j, Y' );
}
}
$response_body['events'][ $key ]['formatted_date'] = $formatted_date;
$response_body['events'][ $key ]['formatted_time'] = $formatted_time;
}
}
return $response_body;
}
```
| Uses | Description |
| --- | --- |
| [wp\_maybe\_decline\_date()](../../functions/wp_maybe_decline_date) wp-includes/functions.php | Determines if the date should be declined. |
| [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. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | No longer used in core. |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Community_Events::__construct( int $user_id, false|array $user_location = false ) WP\_Community\_Events::\_\_construct( int $user\_id, false|array $user\_location = false )
==========================================================================================
Constructor for [WP\_Community\_Events](../wp_community_events).
`$user_id` int Required WP user ID. `$user_location` false|array Optional Stored location data for the user. false to pass no location.
* `description`stringThe name of the location
* `latitude`stringThe latitude in decimal degrees notation, without the degree symbol. e.g.: 47.615200.
* `longitude`stringThe longitude in decimal degrees notation, without the degree symbol. e.g.: -122.341100.
* `country`stringThe ISO 3166-1 alpha-2 country code. e.g.: BR
Default: `false`
File: `wp-admin/includes/class-wp-community-events.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-community-events.php/)
```
public function __construct( $user_id, $user_location = false ) {
$this->user_id = absint( $user_id );
$this->user_location = $user_location;
}
```
| Uses | Description |
| --- | --- |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Used By | Description |
| --- | --- |
| [wp\_localize\_community\_events()](../../functions/wp_localize_community_events) wp-includes/script-loader.php | Localizes community events data that needs to be passed to dashboard.js. |
| [wp\_ajax\_get\_community\_events()](../../functions/wp_ajax_get_community_events) wp-admin/includes/ajax-actions.php | Handles Ajax requests for community events |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Community_Events::get_request_args( string $search = '', string $timezone = '' ): array WP\_Community\_Events::get\_request\_args( string $search = '', string $timezone = '' ): array
==============================================================================================
Builds an array of args to use in an HTTP request to the w.org Events API.
`$search` string Optional City search string. Default: `''`
`$timezone` string Optional Timezone string. Default: `''`
array The request args.
File: `wp-admin/includes/class-wp-community-events.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-community-events.php/)
```
protected function get_request_args( $search = '', $timezone = '' ) {
$args = array(
'number' => 5, // Get more than three in case some get trimmed out.
'ip' => self::get_unsafe_client_ip(),
);
/*
* Include the minimal set of necessary arguments, in order to increase the
* chances of a cache-hit on the API side.
*/
if ( empty( $search ) && isset( $this->user_location['latitude'], $this->user_location['longitude'] ) ) {
$args['latitude'] = $this->user_location['latitude'];
$args['longitude'] = $this->user_location['longitude'];
} else {
$args['locale'] = get_user_locale( $this->user_id );
if ( $timezone ) {
$args['timezone'] = $timezone;
}
if ( $search ) {
$args['location'] = $search;
}
}
// Wrap the args in an array compatible with the second parameter of `wp_remote_get()`.
return array(
'body' => $args,
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Community\_Events::get\_unsafe\_client\_ip()](get_unsafe_client_ip) wp-admin/includes/class-wp-community-events.php | Determines the user’s actual IP address and attempts to partially anonymize an IP address by converting it to a network ID. |
| [get\_user\_locale()](../../functions/get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| Used By | Description |
| --- | --- |
| [WP\_Community\_Events::get\_events()](get_events) wp-admin/includes/class-wp-community-events.php | Gets data about events near a particular location. |
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Community_Events::maybe_log_events_response( string $message, array $details ) WP\_Community\_Events::maybe\_log\_events\_response( string $message, array $details )
======================================================================================
This method has been deprecated. Use a plugin instead. See #41217 for an example.
Logs responses to Events API requests.
`$message` string Required A description of what occurred. `$details` array Required Details that provide more context for the log entry. File: `wp-admin/includes/class-wp-community-events.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-community-events.php/)
```
protected function maybe_log_events_response( $message, $details ) {
_deprecated_function( __METHOD__, '4.9.0' );
if ( ! WP_DEBUG_LOG ) {
return;
}
error_log(
sprintf(
'%s: %s. Details: %s',
__METHOD__,
trim( $message, '.' ),
wp_json_encode( $details )
)
);
}
```
| Uses | Description |
| --- | --- |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [\_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/) | Use a plugin instead. See #41217 for an example. |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Community_Events::trim_events( array $events ): array WP\_Community\_Events::trim\_events( array $events ): array
===========================================================
Prepares the event list for presentation.
Discards expired events, and makes WordCamps "sticky." Attendees need more advanced notice about WordCamps than they do for meetups, so camps should appear in the list sooner. If a WordCamp is coming up, the API will "stick" it in the response, even if it wouldn’t otherwise appear. When that happens, the event will be at the end of the list, and will need to be moved into a higher position, so that it doesn’t get trimmed off.
`$events` array Required The events that will be prepared. array The response body with events trimmed.
File: `wp-admin/includes/class-wp-community-events.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-community-events.php/)
```
protected function trim_events( array $events ) {
$future_events = array();
foreach ( $events as $event ) {
/*
* The API's `date` and `end_date` fields are in the _event's_ local timezone, but UTC is needed so
* it can be converted to the _user's_ local time.
*/
$end_time = (int) $event['end_unix_timestamp'];
if ( time() < $end_time ) {
// Decode HTML entities from the event title.
$event['title'] = html_entity_decode( $event['title'], ENT_QUOTES, 'UTF-8' );
array_push( $future_events, $event );
}
}
$future_wordcamps = array_filter(
$future_events,
static function( $wordcamp ) {
return 'wordcamp' === $wordcamp['type'];
}
);
$future_wordcamps = array_values( $future_wordcamps ); // Remove gaps in indices.
$trimmed_events = array_slice( $future_events, 0, 3 );
$trimmed_event_types = wp_list_pluck( $trimmed_events, 'type' );
// Make sure the soonest upcoming WordCamp is pinned in the list.
if ( $future_wordcamps && ! in_array( 'wordcamp', $trimmed_event_types, true ) ) {
array_pop( $trimmed_events );
array_push( $trimmed_events, $future_wordcamps[0] );
}
return $trimmed_events;
}
```
| 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. |
| Used By | Description |
| --- | --- |
| [WP\_Community\_Events::get\_events()](get_events) wp-admin/includes/class-wp-community-events.php | Gets data about events near a particular location. |
| [WP\_Community\_Events::get\_cached\_events()](get_cached_events) wp-admin/includes/class-wp-community-events.php | Gets cached events. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Decode HTML entities from the event title. |
| [5.5.2](https://developer.wordpress.org/reference/since/5.5.2/) | Accepts and returns only the events, rather than an entire HTTP response. |
| [4.9.7](https://developer.wordpress.org/reference/since/4.9.7/) | Stick a WordCamp to the final list. |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
wordpress WP_Widget_Tag_Cloud::form( array $instance ) WP\_Widget\_Tag\_Cloud::form( array $instance )
===============================================
Outputs the Tag Cloud widget settings form.
`$instance` array Required Current settings. File: `wp-includes/widgets/class-wp-widget-tag-cloud.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-tag-cloud.php/)
```
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
$count = isset( $instance['count'] ) ? (bool) $instance['count'] : false;
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input type="text" class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
$taxonomies = get_taxonomies( array( 'show_tagcloud' => true ), 'object' );
$current_taxonomy = $this->_get_current_taxonomy( $instance );
switch ( count( $taxonomies ) ) {
// No tag cloud supporting taxonomies found, display error message.
case 0:
?>
<input type="hidden" id="<?php echo $this->get_field_id( 'taxonomy' ); ?>" name="<?php echo $this->get_field_name( 'taxonomy' ); ?>" value="" />
<p>
<?php _e( 'The tag cloud will not be displayed since there are no taxonomies that support the tag cloud widget.' ); ?>
</p>
<?php
break;
// Just a single tag cloud supporting taxonomy found, no need to display a select.
case 1:
$keys = array_keys( $taxonomies );
$taxonomy = reset( $keys );
?>
<input type="hidden" id="<?php echo $this->get_field_id( 'taxonomy' ); ?>" name="<?php echo $this->get_field_name( 'taxonomy' ); ?>" value="<?php echo esc_attr( $taxonomy ); ?>" />
<?php
break;
// More than one tag cloud supporting taxonomy found, display a select.
default:
?>
<p>
<label for="<?php echo $this->get_field_id( 'taxonomy' ); ?>"><?php _e( 'Taxonomy:' ); ?></label>
<select class="widefat" id="<?php echo $this->get_field_id( 'taxonomy' ); ?>" name="<?php echo $this->get_field_name( 'taxonomy' ); ?>">
<?php foreach ( $taxonomies as $taxonomy => $tax ) : ?>
<option value="<?php echo esc_attr( $taxonomy ); ?>" <?php selected( $taxonomy, $current_taxonomy ); ?>>
<?php echo esc_html( $tax->labels->name ); ?>
</option>
<?php endforeach; ?>
</select>
</p>
<?php
}
if ( count( $taxonomies ) > 0 ) {
?>
<p>
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" <?php checked( $count, true ); ?> />
<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php _e( 'Show tag counts' ); ?></label>
</p>
<?php
}
}
```
| Uses | Description |
| --- | --- |
| [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. |
| [WP\_Widget\_Tag\_Cloud::\_get\_current\_taxonomy()](_get_current_taxonomy) wp-includes/widgets/class-wp-widget-tag-cloud.php | Retrieves the taxonomy for the current Tag cloud widget instance. |
| [get\_taxonomies()](../../functions/get_taxonomies) wp-includes/taxonomy.php | Retrieves a list of registered taxonomy names or objects. |
| [\_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. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Tag_Cloud::update( array $new_instance, array $old_instance ): array WP\_Widget\_Tag\_Cloud::update( array $new\_instance, array $old\_instance ): array
===================================================================================
Handles updating settings for the current Tag Cloud 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 Settings to save or bool false to cancel saving.
File: `wp-includes/widgets/class-wp-widget-tag-cloud.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-tag-cloud.php/)
```
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = sanitize_text_field( $new_instance['title'] );
$instance['count'] = ! empty( $new_instance['count'] ) ? 1 : 0;
$instance['taxonomy'] = stripslashes( $new_instance['taxonomy'] );
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_Tag_Cloud::_get_current_taxonomy( array $instance ): string WP\_Widget\_Tag\_Cloud::\_get\_current\_taxonomy( array $instance ): string
===========================================================================
Retrieves the taxonomy for the current Tag cloud widget instance.
`$instance` array Required Current settings. string Name of the current taxonomy if set, otherwise `'post_tag'`.
File: `wp-includes/widgets/class-wp-widget-tag-cloud.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-tag-cloud.php/)
```
public function _get_current_taxonomy( $instance ) {
if ( ! empty( $instance['taxonomy'] ) && taxonomy_exists( $instance['taxonomy'] ) ) {
return $instance['taxonomy'];
}
return 'post_tag';
}
```
| Uses | Description |
| --- | --- |
| [taxonomy\_exists()](../../functions/taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| Used By | Description |
| --- | --- |
| [WP\_Widget\_Tag\_Cloud::widget()](widget) wp-includes/widgets/class-wp-widget-tag-cloud.php | Outputs the content for the current Tag Cloud widget instance. |
| [WP\_Widget\_Tag\_Cloud::form()](form) wp-includes/widgets/class-wp-widget-tag-cloud.php | Outputs the Tag Cloud widget settings form. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Widget_Tag_Cloud::__construct() WP\_Widget\_Tag\_Cloud::\_\_construct()
=======================================
Sets up a new Tag Cloud widget instance.
File: `wp-includes/widgets/class-wp-widget-tag-cloud.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-tag-cloud.php/)
```
public function __construct() {
$widget_ops = array(
'description' => __( 'A cloud of your most used tags.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
parent::__construct( 'tag_cloud', __( 'Tag Cloud' ), $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_Tag_Cloud::widget( array $args, array $instance ) WP\_Widget\_Tag\_Cloud::widget( array $args, array $instance )
==============================================================
Outputs the content for the current Tag Cloud widget instance.
`$args` array Required Display arguments including `'before_title'`, `'after_title'`, `'before_widget'`, and `'after_widget'`. `$instance` array Required Settings for the current Tag Cloud widget instance. File: `wp-includes/widgets/class-wp-widget-tag-cloud.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-tag-cloud.php/)
```
public function widget( $args, $instance ) {
$current_taxonomy = $this->_get_current_taxonomy( $instance );
if ( ! empty( $instance['title'] ) ) {
$title = $instance['title'];
} else {
if ( 'post_tag' === $current_taxonomy ) {
$title = __( 'Tags' );
} else {
$tax = get_taxonomy( $current_taxonomy );
$title = $tax->labels->name;
}
}
$default_title = $title;
$show_count = ! empty( $instance['count'] );
$tag_cloud = wp_tag_cloud(
/**
* Filters the taxonomy used in the Tag Cloud widget.
*
* @since 2.8.0
* @since 3.0.0 Added taxonomy drop-down.
* @since 4.9.0 Added the `$instance` parameter.
*
* @see wp_tag_cloud()
*
* @param array $args Args used for the tag cloud widget.
* @param array $instance Array of settings for the current widget.
*/
apply_filters(
'widget_tag_cloud_args',
array(
'taxonomy' => $current_taxonomy,
'echo' => false,
'show_count' => $show_count,
),
$instance
)
);
if ( empty( $tag_cloud ) ) {
return;
}
/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
echo $args['before_widget'];
if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
}
$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 ) . '">';
}
echo '<div class="tagcloud">';
echo $tag_cloud;
echo "</div>\n";
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\_tag\_cloud\_args', array $args, array $instance )](../../hooks/widget_tag_cloud_args)
Filters the taxonomy used in the Tag Cloud widget.
[apply\_filters( 'widget\_title', string $title, array $instance, mixed $id\_base )](../../hooks/widget_title)
Filters the widget title.
| Uses | Description |
| --- | --- |
| [wp\_tag\_cloud()](../../functions/wp_tag_cloud) wp-includes/category-template.php | Displays a tag cloud. |
| [WP\_Widget\_Tag\_Cloud::\_get\_current\_taxonomy()](_get_current_taxonomy) wp-includes/widgets/class-wp-widget-tag-cloud.php | Retrieves the taxonomy for the current Tag cloud widget instance. |
| [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\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [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. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress Theme_Upgrader_Skin::after() Theme\_Upgrader\_Skin::after()
==============================
Action to perform following a single theme update.
File: `wp-admin/includes/class-theme-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-upgrader-skin.php/)
```
public function after() {
$this->decrement_update_count( 'theme' );
$update_actions = array();
$theme_info = $this->upgrader->theme_info();
if ( $theme_info ) {
$name = $theme_info->display( 'Name' );
$stylesheet = $this->upgrader->result['destination_name'];
$template = $theme_info->get_template();
$activate_link = add_query_arg(
array(
'action' => 'activate',
'template' => urlencode( $template ),
'stylesheet' => urlencode( $stylesheet ),
),
admin_url( 'themes.php' )
);
$activate_link = wp_nonce_url( $activate_link, 'switch-theme_' . $stylesheet );
$customize_url = add_query_arg(
array(
'theme' => urlencode( $stylesheet ),
'return' => urlencode( admin_url( 'themes.php' ) ),
),
admin_url( 'customize.php' )
);
if ( get_stylesheet() === $stylesheet ) {
if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) {
$update_actions['preview'] = sprintf(
'<a href="%s" class="hide-if-no-customize load-customize">' .
'<span aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></a>',
esc_url( $customize_url ),
__( 'Customize' ),
/* translators: %s: Theme name. */
sprintf( __( 'Customize “%s”' ), $name )
);
}
} elseif ( current_user_can( 'switch_themes' ) ) {
if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) {
$update_actions['preview'] = sprintf(
'<a href="%s" class="hide-if-no-customize load-customize">' .
'<span aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></a>',
esc_url( $customize_url ),
__( 'Live Preview' ),
/* translators: %s: Theme name. */
sprintf( __( 'Live Preview “%s”' ), $name )
);
}
$update_actions['activate'] = sprintf(
'<a href="%s" class="activatelink">' .
'<span aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></a>',
esc_url( $activate_link ),
__( 'Activate' ),
/* translators: %s: Theme name. */
sprintf( _x( 'Activate “%s”', 'theme' ), $name )
);
}
if ( ! $this->result || is_wp_error( $this->result ) || is_network_admin() ) {
unset( $update_actions['preview'], $update_actions['activate'] );
}
}
$update_actions['themes_page'] = sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'themes.php' ),
__( 'Go to Themes page' )
);
/**
* Filters the list of action links available following a single theme update.
*
* @since 2.8.0
*
* @param string[] $update_actions Array of theme action links.
* @param string $theme Theme directory name.
*/
$update_actions = apply_filters( 'update_theme_complete_actions', $update_actions, $this->theme );
if ( ! empty( $update_actions ) ) {
$this->feedback( implode( ' | ', (array) $update_actions ) );
}
}
```
[apply\_filters( 'update\_theme\_complete\_actions', string[] $update\_actions, string $theme )](../../hooks/update_theme_complete_actions)
Filters the list of action links available following a single theme update.
| Uses | Description |
| --- | --- |
| [get\_stylesheet()](../../functions/get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [is\_network\_admin()](../../functions/is_network_admin) wp-includes/load.php | Determines whether the current request is for the network administrative interface. |
| [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. |
| [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\_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. |
| [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 |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress Theme_Upgrader_Skin::__construct( array $args = array() ) Theme\_Upgrader\_Skin::\_\_construct( array $args = array() )
=============================================================
Constructor.
Sets up the theme upgrader skin.
`$args` array Optional The theme upgrader skin arguments to override default options. Default: `array()`
File: `wp-admin/includes/class-theme-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-upgrader-skin.php/)
```
public function __construct( $args = array() ) {
$defaults = array(
'url' => '',
'theme' => '',
'nonce' => '',
'title' => __( 'Update Theme' ),
);
$args = wp_parse_args( $args, $defaults );
$this->theme = $args['theme'];
parent::__construct( $args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Upgrader\_Skin::\_\_construct()](../wp_upgrader_skin/__construct) wp-admin/includes/class-wp-upgrader-skin.php | Constructor. |
| [\_\_()](../../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 |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress PO::read_line( resource $f, string $action = 'read' ): bool PO::read\_line( resource $f, string $action = 'read' ): bool
============================================================
`$f` resource Required `$action` string Optional Default: `'read'`
bool
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public function read_line( $f, $action = 'read' ) {
static $last_line = '';
static $use_last_line = false;
if ( 'clear' === $action ) {
$last_line = '';
return true;
}
if ( 'put-back' === $action ) {
$use_last_line = true;
return true;
}
$line = $use_last_line ? $last_line : fgets( $f );
$line = ( "\r\n" === substr( $line, -2 ) ) ? rtrim( $line, "\r\n" ) . "\n" : $line;
$last_line = $line;
$use_last_line = false;
return $line;
}
```
| Used By | Description |
| --- | --- |
| [PO::read\_entry()](read_entry) wp-includes/pomo/po.php | |
| [PO::import\_from\_file()](import_from_file) wp-includes/pomo/po.php | |
wordpress PO::is_final( string $context ): bool PO::is\_final( string $context ): bool
======================================
Helper function for read\_entry
`$context` string Required bool
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
protected static function is_final( $context ) {
return ( 'msgstr' === $context ) || ( 'msgstr_plural' === $context );
}
```
| Used By | Description |
| --- | --- |
| [PO::read\_entry()](read_entry) wp-includes/pomo/po.php | |
wordpress PO::export_headers(): string PO::export\_headers(): string
=============================
Exports headers to a PO entry
string msgid/msgstr PO entry for this PO file headers, doesn't contain newline at the end
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public function export_headers() {
$header_string = '';
foreach ( $this->headers as $header => $value ) {
$header_string .= "$header: $value\n";
}
$poified = PO::poify( $header_string );
if ( $this->comments_before_headers ) {
$before_headers = $this->prepend_each_line( rtrim( $this->comments_before_headers ) . "\n", '# ' );
} else {
$before_headers = '';
}
return rtrim( "{$before_headers}msgid \"\"\nmsgstr $poified" );
}
```
| Uses | Description |
| --- | --- |
| [PO::poify()](poify) wp-includes/pomo/po.php | Formats a string in PO-style |
| [PO::prepend\_each\_line()](prepend_each_line) wp-includes/pomo/po.php | Inserts $with in the beginning of every new line of $string and returns the modified string |
| Used By | Description |
| --- | --- |
| [PO::export()](export) wp-includes/pomo/po.php | Exports the whole PO file as a string |
wordpress PO::read_entry( resource $f, int $lineno ): null|false|array PO::read\_entry( resource $f, int $lineno ): null|false|array
=============================================================
`$f` resource Required `$lineno` int Required null|false|array
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public function read_entry( $f, $lineno = 0 ) {
$entry = new Translation_Entry();
// Where were we in the last step.
// Can be: comment, msgctxt, msgid, msgid_plural, msgstr, msgstr_plural.
$context = '';
$msgstr_index = 0;
while ( true ) {
$lineno++;
$line = PO::read_line( $f );
if ( ! $line ) {
if ( feof( $f ) ) {
if ( self::is_final( $context ) ) {
break;
} elseif ( ! $context ) { // We haven't read a line and EOF came.
return null;
} else {
return false;
}
} else {
return false;
}
}
if ( "\n" === $line ) {
continue;
}
$line = trim( $line );
if ( preg_match( '/^#/', $line, $m ) ) {
// The comment is the start of a new entry.
if ( self::is_final( $context ) ) {
PO::read_line( $f, 'put-back' );
$lineno--;
break;
}
// Comments have to be at the beginning.
if ( $context && 'comment' !== $context ) {
return false;
}
// Add comment.
$this->add_comment_to_entry( $entry, $line );
} elseif ( preg_match( '/^msgctxt\s+(".*")/', $line, $m ) ) {
if ( self::is_final( $context ) ) {
PO::read_line( $f, 'put-back' );
$lineno--;
break;
}
if ( $context && 'comment' !== $context ) {
return false;
}
$context = 'msgctxt';
$entry->context .= PO::unpoify( $m[1] );
} elseif ( preg_match( '/^msgid\s+(".*")/', $line, $m ) ) {
if ( self::is_final( $context ) ) {
PO::read_line( $f, 'put-back' );
$lineno--;
break;
}
if ( $context && 'msgctxt' !== $context && 'comment' !== $context ) {
return false;
}
$context = 'msgid';
$entry->singular .= PO::unpoify( $m[1] );
} elseif ( preg_match( '/^msgid_plural\s+(".*")/', $line, $m ) ) {
if ( 'msgid' !== $context ) {
return false;
}
$context = 'msgid_plural';
$entry->is_plural = true;
$entry->plural .= PO::unpoify( $m[1] );
} elseif ( preg_match( '/^msgstr\s+(".*")/', $line, $m ) ) {
if ( 'msgid' !== $context ) {
return false;
}
$context = 'msgstr';
$entry->translations = array( PO::unpoify( $m[1] ) );
} elseif ( preg_match( '/^msgstr\[(\d+)\]\s+(".*")/', $line, $m ) ) {
if ( 'msgid_plural' !== $context && 'msgstr_plural' !== $context ) {
return false;
}
$context = 'msgstr_plural';
$msgstr_index = $m[1];
$entry->translations[ $m[1] ] = PO::unpoify( $m[2] );
} elseif ( preg_match( '/^".*"$/', $line ) ) {
$unpoified = PO::unpoify( $line );
switch ( $context ) {
case 'msgid':
$entry->singular .= $unpoified;
break;
case 'msgctxt':
$entry->context .= $unpoified;
break;
case 'msgid_plural':
$entry->plural .= $unpoified;
break;
case 'msgstr':
$entry->translations[0] .= $unpoified;
break;
case 'msgstr_plural':
$entry->translations[ $msgstr_index ] .= $unpoified;
break;
default:
return false;
}
} else {
return false;
}
}
$have_translations = false;
foreach ( $entry->translations as $t ) {
if ( $t || ( '0' === $t ) ) {
$have_translations = true;
break;
}
}
if ( false === $have_translations ) {
$entry->translations = array();
}
return array(
'entry' => $entry,
'lineno' => $lineno,
);
}
```
| Uses | Description |
| --- | --- |
| [PO::is\_final()](is_final) wp-includes/pomo/po.php | Helper function for read\_entry |
| [Translation\_Entry::\_\_construct()](../translation_entry/__construct) wp-includes/pomo/entry.php | |
| [PO::read\_line()](read_line) wp-includes/pomo/po.php | |
| [PO::add\_comment\_to\_entry()](add_comment_to_entry) wp-includes/pomo/po.php | |
| [PO::unpoify()](unpoify) wp-includes/pomo/po.php | Gives back the original string from a PO-formatted string |
| Used By | Description |
| --- | --- |
| [PO::import\_from\_file()](import_from_file) wp-includes/pomo/po.php | |
wordpress PO::set_comment_before_headers( string $text ) PO::set\_comment\_before\_headers( string $text )
=================================================
Text to include as a comment before the start of the PO contents
Doesn’t need to include # in the beginning of lines, these are added automatically
`$text` string Required Text to include as a comment. File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public function set_comment_before_headers( $text ) {
$this->comments_before_headers = $text;
}
```
wordpress PO::export_entry( Translation_Entry $entry ): string|false PO::export\_entry( Translation\_Entry $entry ): string|false
============================================================
Builds a string from the entry for inclusion in PO file
`$entry` [Translation\_Entry](../translation_entry) Required the entry to convert to po string. string|false PO-style formatted string for the entry or false if the entry is empty
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public static function export_entry( $entry ) {
if ( null === $entry->singular || '' === $entry->singular ) {
return false;
}
$po = array();
if ( ! empty( $entry->translator_comments ) ) {
$po[] = PO::comment_block( $entry->translator_comments );
}
if ( ! empty( $entry->extracted_comments ) ) {
$po[] = PO::comment_block( $entry->extracted_comments, '.' );
}
if ( ! empty( $entry->references ) ) {
$po[] = PO::comment_block( implode( ' ', $entry->references ), ':' );
}
if ( ! empty( $entry->flags ) ) {
$po[] = PO::comment_block( implode( ', ', $entry->flags ), ',' );
}
if ( $entry->context ) {
$po[] = 'msgctxt ' . PO::poify( $entry->context );
}
$po[] = 'msgid ' . PO::poify( $entry->singular );
if ( ! $entry->is_plural ) {
$translation = empty( $entry->translations ) ? '' : $entry->translations[0];
$translation = PO::match_begin_and_end_newlines( $translation, $entry->singular );
$po[] = 'msgstr ' . PO::poify( $translation );
} else {
$po[] = 'msgid_plural ' . PO::poify( $entry->plural );
$translations = empty( $entry->translations ) ? array( '', '' ) : $entry->translations;
foreach ( $translations as $i => $translation ) {
$translation = PO::match_begin_and_end_newlines( $translation, $entry->plural );
$po[] = "msgstr[$i] " . PO::poify( $translation );
}
}
return implode( "\n", $po );
}
```
| Uses | Description |
| --- | --- |
| [PO::match\_begin\_and\_end\_newlines()](match_begin_and_end_newlines) wp-includes/pomo/po.php | |
| [PO::comment\_block()](comment_block) wp-includes/pomo/po.php | Prepare a text as a comment — wraps the lines and prepends # and a special character to each line |
| [PO::poify()](poify) wp-includes/pomo/po.php | Formats a string in PO-style |
wordpress PO::add_comment_to_entry( Translation_Entry $entry, string $po_comment_line ) PO::add\_comment\_to\_entry( Translation\_Entry $entry, string $po\_comment\_line )
===================================================================================
`$entry` [Translation\_Entry](../translation_entry) Required `$po_comment_line` string Required File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public function add_comment_to_entry( &$entry, $po_comment_line ) {
$first_two = substr( $po_comment_line, 0, 2 );
$comment = trim( substr( $po_comment_line, 2 ) );
if ( '#:' === $first_two ) {
$entry->references = array_merge( $entry->references, preg_split( '/\s+/', $comment ) );
} elseif ( '#.' === $first_two ) {
$entry->extracted_comments = trim( $entry->extracted_comments . "\n" . $comment );
} elseif ( '#,' === $first_two ) {
$entry->flags = array_merge( $entry->flags, preg_split( '/,\s*/', $comment ) );
} else {
$entry->translator_comments = trim( $entry->translator_comments . "\n" . $comment );
}
}
```
| Used By | Description |
| --- | --- |
| [PO::read\_entry()](read_entry) wp-includes/pomo/po.php | |
wordpress PO::import_from_file( string $filename ): bool PO::import\_from\_file( string $filename ): bool
================================================
`$filename` string Required bool
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public function import_from_file( $filename ) {
$f = fopen( $filename, 'r' );
if ( ! $f ) {
return false;
}
$lineno = 0;
while ( true ) {
$res = $this->read_entry( $f, $lineno );
if ( ! $res ) {
break;
}
if ( '' === $res['entry']->singular ) {
$this->set_headers( $this->make_headers( $res['entry']->translations[0] ) );
} else {
$this->add_entry( $res['entry'] );
}
}
PO::read_line( $f, 'clear' );
if ( false === $res ) {
return false;
}
if ( ! $this->headers && ! $this->entries ) {
return false;
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [PO::read\_entry()](read_entry) wp-includes/pomo/po.php | |
| [PO::read\_line()](read_line) wp-includes/pomo/po.php | |
wordpress PO::poify( string $string ): string PO::poify( string $string ): string
===================================
Formats a string in PO-style
`$string` string Required the string to format string the poified string
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public static function poify( $string ) {
$quote = '"';
$slash = '\\';
$newline = "\n";
$replaces = array(
"$slash" => "$slash$slash",
"$quote" => "$slash$quote",
"\t" => '\t',
);
$string = str_replace( array_keys( $replaces ), array_values( $replaces ), $string );
$po = $quote . implode( "{$slash}n{$quote}{$newline}{$quote}", explode( $newline, $string ) ) . $quote;
// Add empty string on first line for readbility.
if ( false !== strpos( $string, $newline ) &&
( substr_count( $string, $newline ) > 1 || substr( $string, -strlen( $newline ) ) !== $newline ) ) {
$po = "$quote$quote$newline$po";
}
// Remove empty strings.
$po = str_replace( "$newline$quote$quote", '', $po );
return $po;
}
```
| Used By | Description |
| --- | --- |
| [PO::export\_headers()](export_headers) wp-includes/pomo/po.php | Exports headers to a PO entry |
| [PO::export\_entry()](export_entry) wp-includes/pomo/po.php | Builds a string from the entry for inclusion in PO file |
| programming_docs |
wordpress PO::export_to_file( string $filename, bool $include_headers = true ): bool PO::export\_to\_file( string $filename, bool $include\_headers = true ): bool
=============================================================================
Same as {@link export}, but writes the result to a file
`$filename` string Required Where to write the PO string. `$include_headers` bool Optional Whether to include the headers in the export. Default: `true`
bool true on success, false on error
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public function export_to_file( $filename, $include_headers = true ) {
$fh = fopen( $filename, 'w' );
if ( false === $fh ) {
return false;
}
$export = $this->export( $include_headers );
$res = fwrite( $fh, $export );
if ( false === $res ) {
return false;
}
return fclose( $fh );
}
```
| Uses | Description |
| --- | --- |
| [PO::export()](export) wp-includes/pomo/po.php | Exports the whole PO file as a string |
wordpress PO::trim_quotes( string $s ): string PO::trim\_quotes( string $s ): string
=====================================
`$s` string Required string
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public static function trim_quotes( $s ) {
if ( '"' === substr( $s, 0, 1 ) ) {
$s = substr( $s, 1 );
}
if ( '"' === substr( $s, -1, 1 ) ) {
$s = substr( $s, 0, -1 );
}
return $s;
}
```
wordpress PO::export_entries(): string PO::export\_entries(): string
=============================
Exports all entries to PO format
string sequence of mgsgid/msgstr PO strings, doesn't containt newline at the end
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public function export_entries() {
// TODO: Sorting.
return implode( "\n\n", array_map( array( 'PO', 'export_entry' ), $this->entries ) );
}
```
| Used By | Description |
| --- | --- |
| [PO::export()](export) wp-includes/pomo/po.php | Exports the whole PO file as a string |
wordpress PO::comment_block( string $text, string $char = ' ' ) PO::comment\_block( string $text, string $char = ' ' )
======================================================
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.
Prepare a text as a comment — wraps the lines and prepends # and a special character to each line
`$text` string Required the comment text `$char` string Optional character to denote a special PO comment, like :, default is a space Default: `' '`
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public static function comment_block( $text, $char = ' ' ) {
$text = wordwrap( $text, PO_MAX_LINE_LEN - 3 );
return PO::prepend_each_line( $text, "#$char " );
}
```
| Uses | Description |
| --- | --- |
| [PO::prepend\_each\_line()](prepend_each_line) wp-includes/pomo/po.php | Inserts $with in the beginning of every new line of $string and returns the modified string |
| Used By | Description |
| --- | --- |
| [PO::export\_entry()](export_entry) wp-includes/pomo/po.php | Builds a string from the entry for inclusion in PO file |
wordpress PO::unpoify( string $string ): string PO::unpoify( string $string ): string
=====================================
Gives back the original string from a PO-formatted string
`$string` string Required PO-formatted string string enascaped string
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public static function unpoify( $string ) {
$escapes = array(
't' => "\t",
'n' => "\n",
'r' => "\r",
'\\' => '\\',
);
$lines = array_map( 'trim', explode( "\n", $string ) );
$lines = array_map( array( 'PO', 'trim_quotes' ), $lines );
$unpoified = '';
$previous_is_backslash = false;
foreach ( $lines as $line ) {
preg_match_all( '/./u', $line, $chars );
$chars = $chars[0];
foreach ( $chars as $char ) {
if ( ! $previous_is_backslash ) {
if ( '\\' === $char ) {
$previous_is_backslash = true;
} else {
$unpoified .= $char;
}
} else {
$previous_is_backslash = false;
$unpoified .= isset( $escapes[ $char ] ) ? $escapes[ $char ] : $char;
}
}
}
// Standardize the line endings on imported content, technically PO files shouldn't contain \r.
$unpoified = str_replace( array( "\r\n", "\r" ), "\n", $unpoified );
return $unpoified;
}
```
| Used By | Description |
| --- | --- |
| [PO::read\_entry()](read_entry) wp-includes/pomo/po.php | |
wordpress PO::match_begin_and_end_newlines( $translation, $original ) PO::match\_begin\_and\_end\_newlines( $translation, $original )
===============================================================
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public static function match_begin_and_end_newlines( $translation, $original ) {
if ( '' === $translation ) {
return $translation;
}
$original_begin = "\n" === substr( $original, 0, 1 );
$original_end = "\n" === substr( $original, -1 );
$translation_begin = "\n" === substr( $translation, 0, 1 );
$translation_end = "\n" === substr( $translation, -1 );
if ( $original_begin ) {
if ( ! $translation_begin ) {
$translation = "\n" . $translation;
}
} elseif ( $translation_begin ) {
$translation = ltrim( $translation, "\n" );
}
if ( $original_end ) {
if ( ! $translation_end ) {
$translation .= "\n";
}
} elseif ( $translation_end ) {
$translation = rtrim( $translation, "\n" );
}
return $translation;
}
```
| Used By | Description |
| --- | --- |
| [PO::export\_entry()](export_entry) wp-includes/pomo/po.php | Builds a string from the entry for inclusion in PO file |
wordpress PO::prepend_each_line( string $string, string $with ) PO::prepend\_each\_line( string $string, string $with )
=======================================================
Inserts $with in the beginning of every new line of $string and returns the modified string
`$string` string Required prepend lines in this string `$with` string Required prepend lines with this string File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public static function prepend_each_line( $string, $with ) {
$lines = explode( "\n", $string );
$append = '';
if ( "\n" === substr( $string, -1 ) && '' === end( $lines ) ) {
/*
* Last line might be empty because $string was terminated
* with a newline, remove it from the $lines array,
* we'll restore state by re-terminating the string at the end.
*/
array_pop( $lines );
$append = "\n";
}
foreach ( $lines as &$line ) {
$line = $with . $line;
}
unset( $line );
return implode( "\n", $lines ) . $append;
}
```
| Used By | Description |
| --- | --- |
| [PO::export\_headers()](export_headers) wp-includes/pomo/po.php | Exports headers to a PO entry |
| [PO::comment\_block()](comment_block) wp-includes/pomo/po.php | Prepare a text as a comment — wraps the lines and prepends # and a special character to each line |
wordpress PO::export( bool $include_headers = true ): string PO::export( bool $include\_headers = true ): string
===================================================
Exports the whole PO file as a string
`$include_headers` bool Optional whether to include the headers in the export Default: `true`
string ready for inclusion in PO file string for headers and all the enrtries
File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/)
```
public function export( $include_headers = true ) {
$res = '';
if ( $include_headers ) {
$res .= $this->export_headers();
$res .= "\n\n";
}
$res .= $this->export_entries();
return $res;
}
```
| Uses | Description |
| --- | --- |
| [PO::export\_headers()](export_headers) wp-includes/pomo/po.php | Exports headers to a PO entry |
| [PO::export\_entries()](export_entries) wp-includes/pomo/po.php | Exports all entries to PO format |
| Used By | Description |
| --- | --- |
| [PO::export\_to\_file()](export_to_file) wp-includes/pomo/po.php | Same as {@link export}, but writes the result to a file |
wordpress WP_REST_Global_Styles_Controller::get_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Global\_Styles\_Controller::get\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
===========================================================================================================
Returns the given global styles config.
`$request` [WP\_REST\_Request](../wp_rest_request) Required The request instance. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error)
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function get_item( $request ) {
$post = $this->get_post( $request['id'] );
if ( is_wp_error( $post ) ) {
return $post;
}
return $this->prepare_item_for_response( $post, $request );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Global\_Styles\_Controller::get\_post()](get_post) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Get the post, if the ID is valid. |
| [WP\_REST\_Global\_Styles\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Prepare a global styles config output for response. |
| [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_REST_Global_Styles_Controller::check_update_permission( WP_Post $post ): bool WP\_REST\_Global\_Styles\_Controller::check\_update\_permission( WP\_Post $post ): bool
=======================================================================================
Checks if a global style can be edited.
`$post` [WP\_Post](../wp_post) Required Post object. bool Whether the post can be edited.
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
protected function check_update_permission( $post ) {
return current_user_can( 'edit_post', $post->ID );
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Global\_Styles\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Checks if a given request has access to read a single global style. |
| [WP\_REST\_Global\_Styles\_Controller::update\_item\_permissions\_check()](update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Checks if a given request has access to write a single global styles config. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::prepare_item_for_response( WP_Post $post, WP_REST_Request $request ): WP_REST_Response WP\_REST\_Global\_Styles\_Controller::prepare\_item\_for\_response( WP\_Post $post, WP\_REST\_Request $request ): WP\_REST\_Response
====================================================================================================================================
Prepare a global styles config output for response.
`$post` [WP\_Post](../wp_post) Required Global Styles post 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-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function prepare_item_for_response( $post, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
$raw_config = json_decode( $post->post_content, true );
$is_global_styles_user_theme_json = isset( $raw_config['isGlobalStylesUserThemeJSON'] ) && true === $raw_config['isGlobalStylesUserThemeJSON'];
$config = array();
if ( $is_global_styles_user_theme_json ) {
$config = ( new WP_Theme_JSON( $raw_config, 'custom' ) )->get_raw_data();
}
// Base fields for every post.
$data = array();
$fields = $this->get_fields_for_response( $request );
if ( rest_is_field_included( 'id', $fields ) ) {
$data['id'] = $post->ID;
}
if ( rest_is_field_included( 'title', $fields ) ) {
$data['title'] = array();
}
if ( rest_is_field_included( 'title.raw', $fields ) ) {
$data['title']['raw'] = $post->post_title;
}
if ( rest_is_field_included( 'title.rendered', $fields ) ) {
add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
$data['title']['rendered'] = get_the_title( $post->ID );
remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
}
if ( rest_is_field_included( 'settings', $fields ) ) {
$data['settings'] = ! empty( $config['settings'] ) && $is_global_styles_user_theme_json ? $config['settings'] : new stdClass();
}
if ( rest_is_field_included( 'styles', $fields ) ) {
$data['styles'] = ! empty( $config['styles'] ) && $is_global_styles_user_theme_json ? $config['styles'] : new stdClass();
}
$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 ) ) {
$links = $this->prepare_links( $post->ID );
$response->add_links( $links );
if ( ! empty( $links['self']['href'] ) ) {
$actions = $this->get_available_actions();
$self = $links['self']['href'];
foreach ( $actions as $rel ) {
$response->add_link( $rel, $self );
}
}
}
return $response;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Global\_Styles\_Controller::prepare\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Prepares links for the request. |
| [WP\_REST\_Global\_Styles\_Controller::get\_available\_actions()](get_available_actions) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Get the link relations available for the post and current user. |
| [WP\_Theme\_JSON::\_\_construct()](../wp_theme_json/__construct) wp-includes/class-wp-theme-json.php | Constructor. |
| [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. |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| [get\_the\_title()](../../functions/get_the_title) wp-includes/post-template.php | Retrieves the post title. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Global\_Styles\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Returns the given global styles config. |
| [WP\_REST\_Global\_Styles\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Updates a single global style config. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::prepare_links( integer $id ): array WP\_REST\_Global\_Styles\_Controller::prepare\_links( integer $id ): array
==========================================================================
Prepares links for the request.
`$id` integer Required ID. array Links for the given post.
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
protected function prepare_links( $id ) {
$base = sprintf( '%s/%s', $this->namespace, $this->rest_base );
$links = array(
'self' => array(
'href' => rest_url( trailingslashit( $base ) . $id ),
),
);
return $links;
}
```
| Uses | Description |
| --- | --- |
| [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\_Global\_Styles\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Prepare a global styles config output for response. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::protected_title_format(): string WP\_REST\_Global\_Styles\_Controller::protected\_title\_format(): string
========================================================================
Overwrites the default protected title format.
By default, WordPress will show password protected posts with a title of "Protected: %s", as the REST API communicates the protected status of a post in a machine readable format, we remove the "Protected: " prefix.
string Protected title format.
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function protected_title_format() {
return '%s';
}
```
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::update_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Global\_Styles\_Controller::update\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
==============================================================================================================
Updates a single global style config.
`$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-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function update_item( $request ) {
$post_before = $this->get_post( $request['id'] );
if ( is_wp_error( $post_before ) ) {
return $post_before;
}
$changes = $this->prepare_item_for_database( $request );
$result = wp_update_post( wp_slash( (array) $changes ), true, false );
if ( is_wp_error( $result ) ) {
return $result;
}
$post = get_post( $request['id'] );
$fields_update = $this->update_additional_fields_for_object( $post, $request );
if ( is_wp_error( $fields_update ) ) {
return $fields_update;
}
wp_after_insert_post( $post, true, $post_before );
$response = $this->prepare_item_for_response( $post, $request );
return rest_ensure_response( $response );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Global\_Styles\_Controller::get\_post()](get_post) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Get the post, if the ID is valid. |
| [WP\_REST\_Global\_Styles\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Prepares a single global styles config for update. |
| [WP\_REST\_Global\_Styles\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Prepare a global styles config output for response. |
| [wp\_after\_insert\_post()](../../functions/wp_after_insert_post) wp-includes/post.php | Fires actions after a post, its terms and meta data has been saved. |
| [wp\_update\_post()](../../functions/wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [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. |
| programming_docs |
wordpress WP_REST_Global_Styles_Controller::get_theme_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Global\_Styles\_Controller::get\_theme\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
========================================================================================================================
Checks if a given request has access to read a single theme global styles config.
`$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-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function get_theme_item_permissions_check( $request ) {
// Verify if the current user has edit_theme_options capability.
// This capability is required to edit/view/delete templates.
if ( ! current_user_can( 'edit_theme_options' ) ) {
return new WP_Error(
'rest_cannot_manage_global_styles',
__( 'Sorry, you are not allowed to access the global styles 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. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::get_theme_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Global\_Styles\_Controller::get\_theme\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=========================================================================================================================
Checks if a given request has access to read a single theme global styles config.
`$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-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function get_theme_items_permissions_check( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
// Verify if the current user has edit_theme_options capability.
// This capability is required to edit/view/delete templates.
if ( ! current_user_can( 'edit_theme_options' ) ) {
return new WP_Error(
'rest_cannot_manage_global_styles',
__( 'Sorry, you are not allowed to access the global styles 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. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::get_theme_items( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Global\_Styles\_Controller::get\_theme\_items( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
===================================================================================================================
Returns the given theme global styles variations.
`$request` [WP\_REST\_Request](../wp_rest_request) Required The request instance. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error)
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function get_theme_items( $request ) {
if ( wp_get_theme()->get_stylesheet() !== $request['stylesheet'] ) {
// This endpoint only supports the active theme for now.
return new WP_Error(
'rest_theme_not_found',
__( 'Theme not found.' ),
array( 'status' => 404 )
);
}
$variations = WP_Theme_JSON_Resolver::get_style_variations();
$response = rest_ensure_response( $variations );
return $response;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Resolver::get\_style\_variations()](../wp_theme_json_resolver/get_style_variations) wp-includes/class-wp-theme-json-resolver.php | Returns the style variations defined by the theme. |
| [WP\_Theme::get\_stylesheet()](../wp_theme/get_stylesheet) wp-includes/class-wp-theme.php | Returns the directory name of the theme’s “stylesheet” files, inside the theme root. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [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. |
| [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_Global_Styles_Controller::prepare_item_for_database( WP_REST_Request $request ): stdClass WP\_REST\_Global\_Styles\_Controller::prepare\_item\_for\_database( WP\_REST\_Request $request ): stdClass
==========================================================================================================
Prepares a single global styles config for update.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. stdClass Changes to pass to wp\_update\_post.
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
protected function prepare_item_for_database( $request ) {
$changes = new stdClass();
$changes->ID = $request['id'];
$post = get_post( $request['id'] );
$existing_config = array();
if ( $post ) {
$existing_config = json_decode( $post->post_content, true );
$json_decoding_error = json_last_error();
if ( JSON_ERROR_NONE !== $json_decoding_error || ! isset( $existing_config['isGlobalStylesUserThemeJSON'] ) ||
! $existing_config['isGlobalStylesUserThemeJSON'] ) {
$existing_config = array();
}
}
if ( isset( $request['styles'] ) || isset( $request['settings'] ) ) {
$config = array();
if ( isset( $request['styles'] ) ) {
$config['styles'] = $request['styles'];
} elseif ( isset( $existing_config['styles'] ) ) {
$config['styles'] = $existing_config['styles'];
}
if ( isset( $request['settings'] ) ) {
$config['settings'] = $request['settings'];
} elseif ( isset( $existing_config['settings'] ) ) {
$config['settings'] = $existing_config['settings'];
}
$config['isGlobalStylesUserThemeJSON'] = true;
$config['version'] = WP_Theme_JSON::LATEST_SCHEMA;
$changes->post_content = wp_json_encode( $config );
}
// Post title.
if ( isset( $request['title'] ) ) {
if ( is_string( $request['title'] ) ) {
$changes->post_title = $request['title'];
} elseif ( ! empty( $request['title']['raw'] ) ) {
$changes->post_title = $request['title']['raw'];
}
}
return $changes;
}
```
| Uses | Description |
| --- | --- |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Global\_Styles\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Updates a single global style config. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::update_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Global\_Styles\_Controller::update\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
====================================================================================================================
Checks if a given request has access to write a single global styles config.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has write access for the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function update_item_permissions_check( $request ) {
$post = $this->get_post( $request['id'] );
if ( is_wp_error( $post ) ) {
return $post;
}
if ( $post && ! $this->check_update_permission( $post ) ) {
return new WP_Error(
'rest_cannot_edit',
__( 'Sorry, you are not allowed to edit this global style.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Global\_Styles\_Controller::get\_post()](get_post) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Get the post, if the ID is valid. |
| [WP\_REST\_Global\_Styles\_Controller::check\_update\_permission()](check_update_permission) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Checks if a global style can be edited. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [\_\_()](../../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.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::register_routes(): void WP\_REST\_Global\_Styles\_Controller::register\_routes(): void
==============================================================
Registers the controllers routes.
void
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/themes/(?P<stylesheet>[\/\s%\w\.\(\)\[\]\@_\-]+)/variations',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_theme_items' ),
'permission_callback' => array( $this, 'get_theme_items_permissions_check' ),
'args' => array(
'stylesheet' => array(
'description' => __( 'The theme identifier' ),
'type' => 'string',
),
),
),
)
);
// List themes global styles.
register_rest_route(
$this->namespace,
// The route.
sprintf(
'/%s/themes/(?P<stylesheet>%s)',
$this->rest_base,
// Matches theme's directory: `/themes/<subdirectory>/<theme>/` or `/themes/<theme>/`.
// Excludes invalid directory name characters: `/:<>*?"|`.
'[^\/:<>\*\?"\|]+(?:\/[^\/:<>\*\?"\|]+)?'
),
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_theme_item' ),
'permission_callback' => array( $this, 'get_theme_item_permissions_check' ),
'args' => array(
'stylesheet' => array(
'description' => __( 'The theme identifier' ),
'type' => 'string',
'sanitize_callback' => array( $this, '_sanitize_global_styles_callback' ),
),
),
),
)
);
// Lists/updates a single global style variation based on the given id.
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 template' ),
'type' => 'string',
'sanitize_callback' => array( $this, '_sanitize_global_styles_callback' ),
),
),
),
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.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::get_collection_params(): array WP\_REST\_Global\_Styles\_Controller::get\_collection\_params(): array
======================================================================
Retrieves the query params for the global styles collection.
array Collection parameters.
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function get_collection_params() {
return array();
}
```
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::check_read_permission( WP_Post $post ): bool WP\_REST\_Global\_Styles\_Controller::check\_read\_permission( WP\_Post $post ): bool
=====================================================================================
Checks if a global style can be read.
`$post` [WP\_Post](../wp_post) Required Post object. bool Whether the post can be read.
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
protected function check_read_permission( $post ) {
return current_user_can( 'read_post', $post->ID );
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Global\_Styles\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Checks if a given request has access to read a single global style. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::get_theme_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Global\_Styles\_Controller::get\_theme\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
==================================================================================================================
Returns the given theme global styles config.
`$request` [WP\_REST\_Request](../wp_rest_request) Required The request instance. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error)
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function get_theme_item( $request ) {
if ( wp_get_theme()->get_stylesheet() !== $request['stylesheet'] ) {
// This endpoint only supports the active theme for now.
return new WP_Error(
'rest_theme_not_found',
__( 'Theme not found.' ),
array( 'status' => 404 )
);
}
$theme = WP_Theme_JSON_Resolver::get_merged_data( 'theme' );
$data = array();
$fields = $this->get_fields_for_response( $request );
if ( rest_is_field_included( 'settings', $fields ) ) {
$data['settings'] = $theme->get_settings();
}
if ( rest_is_field_included( 'styles', $fields ) ) {
$raw_data = $theme->get_raw_data();
$data['styles'] = isset( $raw_data['styles'] ) ? $raw_data['styles'] : array();
}
$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 ) ) {
$links = array(
'self' => array(
'href' => rest_url( sprintf( '%s/%s/themes/%s', $this->namespace, $this->rest_base, $request['stylesheet'] ) ),
),
);
$response->add_links( $links );
}
return $response;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Resolver::get\_merged\_data()](../wp_theme_json_resolver/get_merged_data) wp-includes/class-wp-theme-json-resolver.php | Returns the data merged from multiple origins. |
| [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\_Theme::get\_stylesheet()](../wp_theme/get_stylesheet) wp-includes/class-wp-theme.php | Returns the directory name of the theme’s “stylesheet” files, inside the theme root. |
| [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. |
| [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. |
| [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. |
| programming_docs |
wordpress WP_REST_Global_Styles_Controller::__construct() WP\_REST\_Global\_Styles\_Controller::\_\_construct()
=====================================================
Constructor.
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'global-styles';
$this->post_type = 'wp_global_styles';
}
```
| 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_Global_Styles_Controller::get_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Global\_Styles\_Controller::get\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=================================================================================================================
Checks if a given request has access to read a single global style.
`$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-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function get_item_permissions_check( $request ) {
$post = $this->get_post( $request['id'] );
if ( is_wp_error( $post ) ) {
return $post;
}
if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
return new WP_Error(
'rest_forbidden_context',
__( 'Sorry, you are not allowed to edit this global style.' ),
array( 'status' => rest_authorization_required_code() )
);
}
if ( ! $this->check_read_permission( $post ) ) {
return new WP_Error(
'rest_cannot_view',
__( 'Sorry, you are not allowed to view this global style.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Global\_Styles\_Controller::get\_post()](get_post) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Get the post, if the ID is valid. |
| [WP\_REST\_Global\_Styles\_Controller::check\_update\_permission()](check_update_permission) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Checks if a global style can be edited. |
| [WP\_REST\_Global\_Styles\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Checks if a global style can be read. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [\_\_()](../../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.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::_sanitize_global_styles_callback( string $id_or_stylesheet ): string WP\_REST\_Global\_Styles\_Controller::\_sanitize\_global\_styles\_callback( string $id\_or\_stylesheet ): string
================================================================================================================
Sanitize the global styles ID or stylesheet to decode endpoint.
For example, `wp/v2/global-styles/twentytwentytwo%200.4.0` would be decoded to `twentytwentytwo 0.4.0`.
`$id_or_stylesheet` string Required Global styles ID or stylesheet. string Sanitized global styles ID or stylesheet.
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
public function _sanitize_global_styles_callback( $id_or_stylesheet ) {
return urldecode( $id_or_stylesheet );
}
```
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::get_item_schema(): array WP\_REST\_Global\_Styles\_Controller::get\_item\_schema(): array
================================================================
Retrieves the global styles type’ schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-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' => $this->post_type,
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'ID of global styles config.' ),
'type' => 'string',
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
'styles' => array(
'description' => __( 'Global styles.' ),
'type' => array( 'object' ),
'context' => array( 'view', 'edit' ),
),
'settings' => array(
'description' => __( 'Global settings.' ),
'type' => array( 'object' ),
'context' => array( 'view', 'edit' ),
),
'title' => array(
'description' => __( 'Title of the global styles variation.' ),
'type' => array( 'object', 'string' ),
'default' => '',
'context' => array( 'embed', 'view', 'edit' ),
'properties' => array(
'raw' => array(
'description' => __( 'Title for the global styles variation, as it exists in the database.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
),
'rendered' => array(
'description' => __( 'HTML title for the post, transformed for display.' ),
'type' => 'string',
'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 |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::get_available_actions(): array WP\_REST\_Global\_Styles\_Controller::get\_available\_actions(): array
======================================================================
Get the link relations available for the post and current user.
array List of link relations.
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
protected function get_available_actions() {
$rels = array();
$post_type = get_post_type_object( $this->post_type );
if ( current_user_can( $post_type->cap->publish_posts ) ) {
$rels[] = 'https://api.w.org/action-publish';
}
return $rels;
}
```
| 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. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Global\_Styles\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Prepare a global styles config output for response. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Global_Styles_Controller::get_post( int $id ): WP_Post|WP_Error WP\_REST\_Global\_Styles\_Controller::get\_post( int $id ): WP\_Post|WP\_Error
==============================================================================
Get the post, if the ID is valid.
`$id` int Required Supplied ID. [WP\_Post](../wp_post)|[WP\_Error](../wp_error) Post object if ID is valid, [WP\_Error](../wp_error) otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
protected function get_post( $id ) {
$error = new WP_Error(
'rest_global_styles_not_found',
__( 'No global styles config exist with that id.' ),
array( 'status' => 404 )
);
$id = (int) $id;
if ( $id <= 0 ) {
return $error;
}
$post = get_post( $id );
if ( empty( $post ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
return $error;
}
return $post;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Global\_Styles\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Checks if a given request has access to read a single global style. |
| [WP\_REST\_Global\_Styles\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Returns the given global styles config. |
| [WP\_REST\_Global\_Styles\_Controller::update\_item\_permissions\_check()](update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Checks if a given request has access to write a single global styles config. |
| [WP\_REST\_Global\_Styles\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Updates a single global style config. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress RSSCache::RSSCache( $base = '', $age = '' ) RSSCache::RSSCache( $base = '', $age = '' )
===========================================
PHP4 constructor.
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
public function RSSCache( $base = '', $age = '' ) {
self::__construct( $base, $age );
}
```
| Uses | Description |
| --- | --- |
| [RSSCache::\_\_construct()](__construct) wp-includes/rss.php | PHP5 constructor. |
wordpress RSSCache::file_name( $url ) RSSCache::file\_name( $url )
============================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function file_name ($url) {
return md5( $url );
}
```
| Used By | Description |
| --- | --- |
| [RSSCache::set()](set) wp-includes/rss.php | |
| [RSSCache::get()](get) wp-includes/rss.php | |
| [RSSCache::check\_cache()](check_cache) wp-includes/rss.php | |
wordpress RSSCache::unserialize( $data ) RSSCache::unserialize( $data )
==============================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function unserialize ( $data ) {
return unserialize( $data );
}
```
wordpress RSSCache::debug( $debugmsg, $lvl = E_USER_NOTICE ) RSSCache::debug( $debugmsg, $lvl = E\_USER\_NOTICE )
====================================================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function debug ($debugmsg, $lvl=E_USER_NOTICE) {
if ( MAGPIE_DEBUG ) {
$this->error("MagpieRSS [debug] $debugmsg", $lvl);
}
}
```
| Uses | Description |
| --- | --- |
| [RSSCache::error()](error) wp-includes/rss.php | |
| Used By | Description |
| --- | --- |
| [RSSCache::get()](get) wp-includes/rss.php | |
wordpress RSSCache::__construct( $base = '', $age = '' ) RSSCache::\_\_construct( $base = '', $age = '' )
================================================
PHP5 constructor.
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function __construct( $base = '', $age = '' ) {
$this->BASE_CACHE = WP_CONTENT_DIR . '/cache';
if ( $base ) {
$this->BASE_CACHE = $base;
}
if ( $age ) {
$this->MAX_AGE = $age;
}
}
```
| Used By | Description |
| --- | --- |
| [RSSCache::RSSCache()](rsscache) wp-includes/rss.php | PHP4 constructor. |
| [fetch\_rss()](../../functions/fetch_rss) wp-includes/rss.php | Build Magpie object based on RSS from URL. |
wordpress RSSCache::set( $url, $rss ) RSSCache::set( $url, $rss )
===========================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function set ($url, $rss) {
$cache_option = 'rss_' . $this->file_name( $url );
set_transient($cache_option, $rss, $this->MAX_AGE);
return $cache_option;
}
```
| Uses | Description |
| --- | --- |
| [set\_transient()](../../functions/set_transient) wp-includes/option.php | Sets/updates the value of a transient. |
| [RSSCache::file\_name()](file_name) wp-includes/rss.php | |
wordpress RSSCache::serialize( $rss ) RSSCache::serialize( $rss )
===========================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function serialize ( $rss ) {
return serialize( $rss );
}
```
wordpress RSSCache::error( $errormsg, $lvl = E_USER_WARNING ) RSSCache::error( $errormsg, $lvl = E\_USER\_WARNING )
=====================================================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function error ($errormsg, $lvl=E_USER_WARNING) {
$this->ERROR = $errormsg;
if ( MAGPIE_DEBUG ) {
trigger_error( $errormsg, $lvl);
}
else {
error_log( $errormsg, 0);
}
}
```
| Used By | Description |
| --- | --- |
| [RSSCache::debug()](debug) wp-includes/rss.php | |
wordpress RSSCache::get( $url ) RSSCache::get( $url )
=====================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function get ($url) {
$this->ERROR = "";
$cache_option = 'rss_' . $this->file_name( $url );
if ( ! $rss = get_transient( $cache_option ) ) {
$this->debug(
"Cache does not contain: $url (cache option: $cache_option)"
);
return 0;
}
return $rss;
}
```
| Uses | Description |
| --- | --- |
| [get\_transient()](../../functions/get_transient) wp-includes/option.php | Retrieves the value of a transient. |
| [RSSCache::file\_name()](file_name) wp-includes/rss.php | |
| [RSSCache::debug()](debug) wp-includes/rss.php | |
wordpress RSSCache::check_cache( $url ) RSSCache::check\_cache( $url )
==============================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function check_cache ( $url ) {
$this->ERROR = "";
$cache_option = 'rss_' . $this->file_name( $url );
if ( get_transient($cache_option) ) {
// object exists and is current
return 'HIT';
} else {
// object does not exist
return 'MISS';
}
}
```
| Uses | Description |
| --- | --- |
| [get\_transient()](../../functions/get_transient) wp-includes/option.php | Retrieves the value of a transient. |
| [RSSCache::file\_name()](file_name) wp-includes/rss.php | |
wordpress WP_Roles::remove_cap( string $role, string $cap ) WP\_Roles::remove\_cap( string $role, string $cap )
===================================================
Removes a capability from role.
`$role` string Required Role name. `$cap` string Required Capability name. Changing the capabilities of a role is persistent, meaning the removed capability will stay in effect until explicitly granted.
This setting is saved to the database (in table wp\_options, field 'wp\_user\_roles'), so you should run this only once, on theme/plugin activation and/or deactivation.
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
public function remove_cap( $role, $cap ) {
if ( ! isset( $this->roles[ $role ] ) ) {
return;
}
unset( $this->roles[ $role ]['capabilities'][ $cap ] );
if ( $this->use_db ) {
update_option( $this->role_key, $this->roles );
}
}
```
| Uses | Description |
| --- | --- |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| Used By | Description |
| --- | --- |
| [WP\_Role::remove\_cap()](../wp_role/remove_cap) wp-includes/class-wp-role.php | Removes a capability from a role. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_Roles::init_roles() WP\_Roles::init\_roles()
========================
Initializes all of the available roles.
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
public function init_roles() {
if ( empty( $this->roles ) ) {
return;
}
$this->role_objects = array();
$this->role_names = array();
foreach ( array_keys( $this->roles ) as $role ) {
$this->role_objects[ $role ] = new WP_Role( $role, $this->roles[ $role ]['capabilities'] );
$this->role_names[ $role ] = $this->roles[ $role ]['name'];
}
/**
* Fires after the roles have been initialized, allowing plugins to add their own roles.
*
* @since 4.7.0
*
* @param WP_Roles $wp_roles A reference to the WP_Roles object.
*/
do_action( 'wp_roles_init', $this );
}
```
[do\_action( 'wp\_roles\_init', WP\_Roles $wp\_roles )](../../hooks/wp_roles_init)
Fires after the roles have been initialized, allowing plugins to add their own roles.
| Uses | Description |
| --- | --- |
| [WP\_Role::\_\_construct()](../wp_role/__construct) wp-includes/class-wp-role.php | Constructor – Set up object properties. |
| [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\_Roles::for\_site()](for_site) wp-includes/class-wp-roles.php | Sets the site to operate on. Defaults to the current site. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
| programming_docs |
wordpress WP_Roles::add_role( string $role, string $display_name, bool[] $capabilities = array() ): WP_Role|void WP\_Roles::add\_role( string $role, string $display\_name, bool[] $capabilities = array() ): WP\_Role|void
==========================================================================================================
Adds a role name with capabilities to the list.
Updates the list of roles, if the role doesn’t already exist.
The capabilities are defined in the following format: `array( 'read' => true )`.
To explicitly deny the role a capability, set the value for that capability to false.
`$role` string Required Role name. `$display_name` string Required Role display name. `$capabilities` bool[] Optional List of capabilities keyed by the capability name, e.g. `array( 'edit_posts' => true, 'delete_posts' => false )`.
Default: `array()`
[WP\_Role](../wp_role)|void [WP\_Role](../wp_role) object, if the role is added.
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
public function add_role( $role, $display_name, $capabilities = array() ) {
if ( empty( $role ) || isset( $this->roles[ $role ] ) ) {
return;
}
$this->roles[ $role ] = array(
'name' => $display_name,
'capabilities' => $capabilities,
);
if ( $this->use_db ) {
update_option( $this->role_key, $this->roles );
}
$this->role_objects[ $role ] = new WP_Role( $role, $capabilities );
$this->role_names[ $role ] = $display_name;
return $this->role_objects[ $role ];
}
```
| Uses | Description |
| --- | --- |
| [WP\_Role::\_\_construct()](../wp_role/__construct) wp-includes/class-wp-role.php | Constructor – Set up object properties. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| Used By | Description |
| --- | --- |
| [add\_role()](../../functions/add_role) wp-includes/capabilities.php | Adds a role, if it does not exist. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_Roles::get_role( string $role ): WP_Role|null WP\_Roles::get\_role( string $role ): WP\_Role|null
===================================================
Retrieves a role object by name.
`$role` string Required Role name. [WP\_Role](../wp_role)|null [WP\_Role](../wp_role) object if found, null if the role does not exist.
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
public function get_role( $role ) {
if ( isset( $this->role_objects[ $role ] ) ) {
return $this->role_objects[ $role ];
} else {
return null;
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_User::get\_role\_caps()](../wp_user/get_role_caps) wp-includes/class-wp-user.php | Retrieves all of the capabilities of the user’s roles, and merges them with individual user capabilities. |
| [get\_role()](../../functions/get_role) wp-includes/capabilities.php | Retrieves role object. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_Roles::get_roles_data(): array WP\_Roles::get\_roles\_data(): array
====================================
Gets the available roles data.
array Roles array.
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
protected function get_roles_data() {
global $wp_user_roles;
if ( ! empty( $wp_user_roles ) ) {
return $wp_user_roles;
}
if ( is_multisite() && get_current_blog_id() != $this->site_id ) {
remove_action( 'switch_blog', 'wp_switch_roles_and_user', 1 );
$roles = get_blog_option( $this->site_id, $this->role_key, array() );
add_action( 'switch_blog', 'wp_switch_roles_and_user', 1, 2 );
return $roles;
}
return get_option( $this->role_key, array() );
}
```
| Uses | Description |
| --- | --- |
| [remove\_action()](../../functions/remove_action) wp-includes/plugin.php | Removes a callback function from an action hook. |
| [get\_blog\_option()](../../functions/get_blog_option) wp-includes/ms-blogs.php | Retrieve option value for a given blog id based on name of option. |
| [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. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Roles::for\_site()](for_site) wp-includes/class-wp-roles.php | Sets the site to operate on. Defaults to the current site. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Roles::add_cap( string $role, string $cap, bool $grant = true ) WP\_Roles::add\_cap( string $role, string $cap, bool $grant = true )
====================================================================
Adds a capability to role.
`$role` string Required Role name. `$cap` string Required Capability name. `$grant` bool Optional Whether role is capable of performing capability.
Default: `true`
Changing the capabilities of a role is persistent, meaning the added capability will stay in effect until explicitly revoked.
This setting is saved to the database (in table wp\_options, field wp\_user\_roles), so it might be better to run this on theme/plugin activation.
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
public function add_cap( $role, $cap, $grant = true ) {
if ( ! isset( $this->roles[ $role ] ) ) {
return;
}
$this->roles[ $role ]['capabilities'][ $cap ] = $grant;
if ( $this->use_db ) {
update_option( $this->role_key, $this->roles );
}
}
```
| Uses | Description |
| --- | --- |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| Used By | Description |
| --- | --- |
| [WP\_Role::add\_cap()](../wp_role/add_cap) wp-includes/class-wp-role.php | Assign role a capability. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_Roles::remove_role( string $role ) WP\_Roles::remove\_role( string $role )
=======================================
Removes a role by name.
`$role` string Required Role name. File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
public function remove_role( $role ) {
if ( ! isset( $this->role_objects[ $role ] ) ) {
return;
}
unset( $this->role_objects[ $role ] );
unset( $this->role_names[ $role ] );
unset( $this->roles[ $role ] );
if ( $this->use_db ) {
update_option( $this->role_key, $this->roles );
}
if ( get_option( 'default_role' ) == $role ) {
update_option( 'default_role', 'subscriber' );
}
}
```
| Uses | Description |
| --- | --- |
| [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 |
| --- | --- |
| [remove\_role()](../../functions/remove_role) wp-includes/capabilities.php | Removes a role, if it exists. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_Roles::__call( string $name, array $arguments ): mixed|false WP\_Roles::\_\_call( string $name, array $arguments ): mixed|false
==================================================================
Makes private/protected methods readable for backward compatibility.
`$name` string Required Method to call. `$arguments` array Required Arguments to pass when calling. mixed|false Return value of the callback, false otherwise.
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
public function __call( $name, $arguments ) {
if ( '_init' === $name ) {
return $this->_init( ...$arguments );
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Roles::\_init()](_init) wp-includes/class-wp-roles.php | Sets up the object properties. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Roles::get_site_id(): int WP\_Roles::get\_site\_id(): int
===============================
Gets the ID of the site for which roles are currently initialized.
int Site ID.
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
public function get_site_id() {
return $this->site_id;
}
```
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Roles::reinit() WP\_Roles::reinit()
===================
This method has been deprecated. Use [WP\_Roles::for\_site()](for_site) instead.
Reinitializes the object.
Recreates the role objects. This is typically called only by [switch\_to\_blog()](../../functions/switch_to_blog) after switching [wpdb](../wpdb) to a new site ID.
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
public function reinit() {
_deprecated_function( __METHOD__, '4.7.0', 'WP_Roles::for_site()' );
$this->for_site();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Roles::for\_site()](for_site) wp-includes/class-wp-roles.php | Sets the site to operate on. Defaults to the current site. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Use [WP\_Roles::for\_site()](for_site) |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_Roles::__construct( int $site_id = null ) WP\_Roles::\_\_construct( int $site\_id = null )
================================================
Constructor.
`$site_id` int Optional Site ID to initialize roles for. Default is the current site. Default: `null`
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
public function __construct( $site_id = null ) {
global $wp_user_roles;
$this->use_db = empty( $wp_user_roles );
$this->for_site( $site_id );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Roles::for\_site()](for_site) wp-includes/class-wp-roles.php | Sets the site to operate on. Defaults to the current site. |
| Used By | Description |
| --- | --- |
| [wp\_initialize\_site()](../../functions/wp_initialize_site) wp-includes/ms-site.php | Runs the initialization routine for a given site. |
| [wp\_roles()](../../functions/wp_roles) wp-includes/capabilities.php | Retrieves the global [WP\_Roles](../wp_roles) instance and instantiates it if necessary. |
| [install\_blog()](../../functions/install_blog) wp-includes/ms-deprecated.php | Install an empty blog. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | The `$site_id` argument was added. |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_Roles::get_names(): string[] WP\_Roles::get\_names(): string[]
=================================
Retrieves a list of role names.
string[] List of role names.
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
public function get_names() {
return $this->role_names;
}
```
| Used By | Description |
| --- | --- |
| [wp\_get\_users\_with\_no\_role()](../../functions/wp_get_users_with_no_role) wp-includes/user.php | Gets the user IDs of all users with no role on this site. |
| [WP\_Users\_List\_Table::get\_views()](../wp_users_list_table/get_views) wp-admin/includes/class-wp-users-list-table.php | Return an associative array listing all the views that can be used with this table. |
| [count\_users()](../../functions/count_users) wp-includes/user.php | Counts number of users who have each of the user roles. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_Roles::_init() WP\_Roles::\_init()
===================
This method has been deprecated. Use [WP\_Roles::for\_site()](for_site) instead.
Sets up the object properties.
The role key is set to the current prefix for the $[wpdb](../wpdb) object with ‘user\_roles’ appended. If the $wp\_user\_roles global is set, then it will be used and the role option will not be updated or used.
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
protected function _init() {
_deprecated_function( __METHOD__, '4.9.0', 'WP_Roles::for_site()' );
$this->for_site();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Roles::for\_site()](for_site) wp-includes/class-wp-roles.php | Sets the site to operate on. Defaults to the current site. |
| [\_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\_Roles::\_\_call()](__call) wp-includes/class-wp-roles.php | Makes private/protected methods readable for backward compatibility. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Use [WP\_Roles::for\_site()](for_site) |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Roles::is_role( string $role ): bool WP\_Roles::is\_role( string $role ): bool
=========================================
Determines whether a role name is currently in the list of available roles.
`$role` string Required Role name to look up. bool
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
public function is_role( $role ) {
return isset( $this->role_names[ $role ] );
}
```
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_Roles::for_site( int $site_id = null ) WP\_Roles::for\_site( int $site\_id = null )
============================================
Sets the site to operate on. Defaults to the current site.
`$site_id` int Optional Site ID to initialize roles for. Default is the current site. Default: `null`
File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/)
```
public function for_site( $site_id = null ) {
global $wpdb;
if ( ! empty( $site_id ) ) {
$this->site_id = absint( $site_id );
} else {
$this->site_id = get_current_blog_id();
}
$this->role_key = $wpdb->get_blog_prefix( $this->site_id ) . 'user_roles';
if ( ! empty( $this->roles ) && ! $this->use_db ) {
return;
}
$this->roles = $this->get_roles_data();
$this->init_roles();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Roles::get\_roles\_data()](get_roles_data) wp-includes/class-wp-roles.php | Gets the available roles data. |
| [WP\_Roles::init\_roles()](init_roles) wp-includes/class-wp-roles.php | Initializes all of the available roles. |
| [wpdb::get\_blog\_prefix()](../wpdb/get_blog_prefix) wp-includes/class-wpdb.php | Gets blog prefix. |
| [get\_current\_blog\_id()](../../functions/get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Used By | Description |
| --- | --- |
| [wp\_switch\_roles\_and\_user()](../../functions/wp_switch_roles_and_user) wp-includes/ms-blogs.php | Switches the initialized roles and current user capabilities to another site. |
| [WP\_Roles::\_\_construct()](__construct) wp-includes/class-wp-roles.php | Constructor. |
| [WP\_Roles::\_init()](_init) wp-includes/class-wp-roles.php | Sets up the object properties. |
| [WP\_Roles::reinit()](reinit) wp-includes/class-wp-roles.php | Reinitializes the object. |
| [WP\_User\_Query::prepare\_query()](../wp_user_query/prepare_query) wp-includes/class-wp-user-query.php | Prepares the query variables. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_User_Request::__construct( WP_Post|object $post ) WP\_User\_Request::\_\_construct( WP\_Post|object $post )
=========================================================
Constructor.
`$post` [WP\_Post](../wp_post)|object Required Post object. File: `wp-includes/class-wp-user-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-request.php/)
```
public function __construct( $post ) {
$this->ID = $post->ID;
$this->user_id = $post->post_author;
$this->email = $post->post_title;
$this->action_name = $post->post_name;
$this->status = $post->post_status;
$this->created_timestamp = strtotime( $post->post_date_gmt );
$this->modified_timestamp = strtotime( $post->post_modified_gmt );
$this->confirmed_timestamp = (int) get_post_meta( $post->ID, '_wp_user_request_confirmed_timestamp', true );
$this->completed_timestamp = (int) get_post_meta( $post->ID, '_wp_user_request_completed_timestamp', true );
$this->request_data = json_decode( $post->post_content, true );
$this->confirm_key = $post->post_password;
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_meta()](../../functions/get_post_meta) wp-includes/post.php | Retrieves a post meta field for the given post ID. |
| Used By | Description |
| --- | --- |
| [wp\_get\_user\_request()](../../functions/wp_get_user_request) wp-includes/user.php | Returns the user request object for the specified request ID. |
| Version | Description |
| --- | --- |
| [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
wordpress POMO_CachedIntFileReader::__construct( $filename ) POMO\_CachedIntFileReader::\_\_construct( $filename )
=====================================================
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( $filename ) {
parent::__construct( $filename );
}
```
| Uses | Description |
| --- | --- |
| [POMO\_CachedFileReader::\_\_construct()](../pomo_cachedfilereader/__construct) wp-includes/pomo/streams.php | PHP5 constructor. |
| Used By | Description |
| --- | --- |
| [POMO\_CachedIntFileReader::POMO\_CachedIntFileReader()](../pomo_cachedintfilereader/pomo_cachedintfilereader) wp-includes/pomo/streams.php | PHP4 constructor. |
| programming_docs |
wordpress POMO_CachedIntFileReader::POMO_CachedIntFileReader( $filename ) POMO\_CachedIntFileReader::POMO\_CachedIntFileReader( $filename )
=================================================================
This method has been deprecated. Use [POMO\_CachedIntFileReader::\_\_construct()](../pomo_cachedintfilereader/__construct) instead.
PHP4 constructor.
* [POMO\_CachedIntFileReader::\_\_construct()](../pomo_cachedintfilereader/__construct)
File: `wp-includes/pomo/streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/streams.php/)
```
public function POMO_CachedIntFileReader( $filename ) {
_deprecated_constructor( self::class, '5.4.0', static::class );
self::__construct( $filename );
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_constructor()](../../functions/_deprecated_constructor) wp-includes/functions.php | Marks a constructor as deprecated and informs when it has been used. |
| [POMO\_CachedIntFileReader::\_\_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 WP_Comment::to_array(): array WP\_Comment::to\_array(): array
===============================
Convert object to array.
array Object as array.
File: `wp-includes/class-wp-comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment.php/)
```
public function to_array() {
return get_object_vars( $this );
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Comment::populated_children( bool $set ) WP\_Comment::populated\_children( bool $set )
=============================================
Set the ‘populated\_children’ flag.
This flag is important for ensuring that calling `get_children()` on a childless comment will not trigger unneeded database queries.
`$set` bool Required Whether the comment's children have already been populated. File: `wp-includes/class-wp-comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment.php/)
```
public function populated_children( $set ) {
$this->populated_children = (bool) $set;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Comment::get_children( array $args = array() ): WP_Comment[] WP\_Comment::get\_children( array $args = array() ): WP\_Comment[]
==================================================================
Get the children of a comment.
`$args` array Optional Array of arguments used to pass to [get\_comments()](../../functions/get_comments) and determine format.
* `format`stringReturn value format. `'tree'` for a hierarchical tree, `'flat'` for a flattened array.
Default `'tree'`.
* `status`stringComment status to limit results by. Accepts `'hold'` (`comment_status=0`), `'approve'` (`comment_status=1`), `'all'`, or a custom comment status.
Default `'all'`.
* `hierarchical`stringWhether to include comment descendants in the results.
`'threaded'` returns a tree, with each comment's children stored in a `children` property on the `WP_Comment` object.
`'flat'` returns a flat array of found comments plus their children.
Pass `false` to leave out descendants.
The parameter is ignored (forced to `false`) when `$fields` is `'ids'` or `'counts'`.
Accepts `'threaded'`, `'flat'`, or false. Default: `'threaded'`.
* `orderby`string|arrayComment status or array of statuses. To use `'meta_value'` or `'meta_value_num'`, `$meta_key` must also be defined.
To sort by a specific `$meta_query` clause, use that clause's array key. Accepts `'comment_agent'`, `'comment_approved'`, `'comment_author'`, `'comment_author_email'`, `'comment_author_IP'`, `'comment_author_url'`, `'comment_content'`, `'comment_date'`, `'comment_date_gmt'`, `'comment_ID'`, `'comment_karma'`, `'comment_parent'`, `'comment_post_ID'`, `'comment_type'`, `'user_id'`, `'comment__in'`, `'meta_value'`, `'meta_value_num'`, the value of $meta\_key, and the array keys of `$meta_query`. Also accepts false, an empty array, or `'none'` to disable `ORDER BY` clause.
More Arguments from get\_comments( ... $args ) Array or query string of comment query parameters.
* `author_email`stringComment author email address.
* `author_url`stringComment author URL.
* `author__in`int[]Array of author IDs to include comments for.
* `author__not_in`int[]Array of author IDs to exclude comments for.
* `comment__in`int[]Array of comment IDs to include.
* `comment__not_in`int[]Array of comment IDs to exclude.
* `count`boolWhether to return a comment count (true) or array of comment objects (false). Default false.
* `date_query`arrayDate query clauses to limit comments by. See [WP\_Date\_Query](../wp_date_query).
Default null.
* `fields`stringComment fields to return. Accepts `'ids'` for comment IDs only or empty for all fields.
* `include_unapproved`arrayArray of IDs or email addresses of users whose unapproved comments will be returned by the query regardless of `$status`.
* `karma`intKarma score to retrieve matching comments for.
* `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.
* `number`intMaximum number of comments to retrieve.
Default empty (no limit).
* `paged`intWhen used with `$number`, defines the page of results to return.
When used with `$offset`, `$offset` takes precedence. Default 1.
* `offset`intNumber of comments to offset the query. Used to build LIMIT clause. Default 0.
* `no_found_rows`boolWhether to disable the `SQL_CALC_FOUND_ROWS` query.
Default: true.
* `orderby`string|arrayComment status or array of statuses. To use `'meta_value'` or `'meta_value_num'`, `$meta_key` must also be defined.
To sort by a specific `$meta_query` clause, use that clause's array key. Accepts:
+ `'comment_agent'`
+ `'comment_approved'`
+ `'comment_author'`
+ `'comment_author_email'`
+ `'comment_author_IP'`
+ `'comment_author_url'`
+ `'comment_content'`
+ `'comment_date'`
+ `'comment_date_gmt'`
+ `'comment_ID'`
+ `'comment_karma'`
+ `'comment_parent'`
+ `'comment_post_ID'`
+ `'comment_type'`
+ `'user_id'`
+ `'comment__in'`
+ `'meta_value'`
+ `'meta_value_num'`
+ The value of `$meta_key`
+ The array keys of `$meta_query`
+ false, an empty array, or `'none'` to disable `ORDER BY` clause. Default: `'comment_date_gmt'`.
* `order`stringHow to order retrieved comments. Accepts `'ASC'`, `'DESC'`.
Default: `'DESC'`.
* `parent`intParent ID of comment to retrieve children of.
* `parent__in`int[]Array of parent IDs of comments to retrieve children for.
* `parent__not_in`int[]Array of parent IDs of comments \*not\* to retrieve children for.
* `post_author__in`int[]Array of author IDs to retrieve comments for.
* `post_author__not_in`int[]Array of author IDs \*not\* to retrieve comments for.
* `post_id`intLimit results to those affiliated with a given post ID.
Default 0.
* `post__in`int[]Array of post IDs to include affiliated comments for.
* `post__not_in`int[]Array of post IDs to exclude affiliated comments for.
* `post_author`intPost author ID to limit results by.
* `post_status`string|string[]Post status or array of post statuses to retrieve affiliated comments for. Pass `'any'` to match any value.
* `post_type`string|string[]Post type or array of post types to retrieve affiliated comments for. Pass `'any'` to match any value.
* `post_name`stringPost name to retrieve affiliated comments for.
* `post_parent`intPost parent ID to retrieve affiliated comments for.
* `search`stringSearch term(s) to retrieve matching comments for.
* `status`string|arrayComment statuses to limit results by. Accepts an array or space/comma-separated list of `'hold'` (`comment_status=0`), `'approve'` (`comment_status=1`), `'all'`, or a custom comment status. Default `'all'`.
* `type`string|string[]Include comments of a given type, or array of types.
Accepts `'comment'`, `'pings'` (includes `'pingback'` and `'trackback'`), or any custom type string.
* `type__in`string[]Include comments from a given array of comment types.
* `type__not_in`string[]Exclude comments from a given array of comment types.
* `user_id`intInclude comments for a specific user ID.
* `hierarchical`bool|stringWhether to include comment descendants in the results.
+ `'threaded'` returns a tree, with each comment's children stored in a `children` property on the `WP_Comment` object.
+ `'flat'` returns a flat array of found comments plus their children.
+ Boolean `false` leaves out descendants. The parameter is ignored (forced to `false`) when `$fields` is `'ids'` or `'counts'`. Accepts `'threaded'`, `'flat'`, or false. Default: false.
* `cache_domain`stringUnique cache key to be produced when this query is stored in an object cache. Default is `'core'`.
* `update_comment_meta_cache`boolWhether to prime the metadata cache for found comments.
Default true.
* `update_comment_post_cache`boolWhether to prime the cache for comment posts.
Default false.
Default: `array()`
[WP\_Comment](../wp_comment)[] Array of `WP_Comment` objects.
File: `wp-includes/class-wp-comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment.php/)
```
public function get_children( $args = array() ) {
$defaults = array(
'format' => 'tree',
'status' => 'all',
'hierarchical' => 'threaded',
'orderby' => '',
);
$_args = wp_parse_args( $args, $defaults );
$_args['parent'] = $this->comment_ID;
if ( is_null( $this->children ) ) {
if ( $this->populated_children ) {
$this->children = array();
} else {
$this->children = get_comments( $_args );
}
}
if ( 'flat' === $_args['format'] ) {
$children = array();
foreach ( $this->children as $child ) {
$child_args = $_args;
$child_args['format'] = 'flat';
// get_children() resets this value automatically.
unset( $child_args['parent'] );
$children = array_merge( $children, array( $child ), $child->get_children( $child_args ) );
}
} else {
$children = $this->children;
}
return $children;
}
```
| Uses | Description |
| --- | --- |
| [get\_comments()](../../functions/get_comments) wp-includes/comment.php | Retrieves a list of comments. |
| [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. |
wordpress WP_Comment::__get( string $name ): mixed WP\_Comment::\_\_get( string $name ): mixed
===========================================
Magic getter.
If `$name` matches a post field, the comment post will be loaded and the post’s value returned.
`$name` string Required mixed
File: `wp-includes/class-wp-comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment.php/)
```
public function __get( $name ) {
if ( in_array( $name, $this->post_fields, true ) ) {
$post = get_post( $this->comment_post_ID );
return $post->$name;
}
}
```
| Uses | Description |
| --- | --- |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Comment::get_child( int $child_id ): WP_Comment|false WP\_Comment::get\_child( int $child\_id ): WP\_Comment|false
============================================================
Get a child comment by ID.
`$child_id` int Required ID of the child. [WP\_Comment](../wp_comment)|false Returns the comment object if found, otherwise false.
File: `wp-includes/class-wp-comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment.php/)
```
public function get_child( $child_id ) {
if ( isset( $this->children[ $child_id ] ) ) {
return $this->children[ $child_id ];
}
return false;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Comment::__isset( string $name ): bool WP\_Comment::\_\_isset( string $name ): bool
============================================
Check whether a non-public property is set.
If `$name` matches a post field, the comment post will be loaded and the post’s value checked.
`$name` string Required Property name. bool
File: `wp-includes/class-wp-comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment.php/)
```
public function __isset( $name ) {
if ( in_array( $name, $this->post_fields, true ) && 0 !== (int) $this->comment_post_ID ) {
$post = get_post( $this->comment_post_ID );
return property_exists( $post, $name );
}
}
```
| Uses | Description |
| --- | --- |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Comment::__construct( WP_Comment $comment ) WP\_Comment::\_\_construct( WP\_Comment $comment )
==================================================
Constructor.
Populates properties with object vars.
`$comment` [WP\_Comment](../wp_comment) Required Comment object. File: `wp-includes/class-wp-comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment.php/)
```
public function __construct( $comment ) {
foreach ( get_object_vars( $comment ) as $key => $value ) {
$this->$key = $value;
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Comment::get\_instance()](get_instance) wp-includes/class-wp-comment.php | Retrieves a [WP\_Comment](../wp_comment) instance. |
| [get\_comment()](../../functions/get_comment) wp-includes/comment.php | Retrieves comment data given a comment ID or comment object. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Comment::get_instance( int $id ): WP_Comment|false WP\_Comment::get\_instance( int $id ): WP\_Comment|false
========================================================
Retrieves a [WP\_Comment](../wp_comment) instance.
`$id` int Required Comment ID. [WP\_Comment](../wp_comment)|false Comment object, otherwise false.
File: `wp-includes/class-wp-comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment.php/)
```
public static function get_instance( $id ) {
global $wpdb;
$comment_id = (int) $id;
if ( ! $comment_id ) {
return false;
}
$_comment = wp_cache_get( $comment_id, 'comment' );
if ( ! $_comment ) {
$_comment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment_id ) );
if ( ! $_comment ) {
return false;
}
wp_cache_add( $_comment->comment_ID, $_comment, 'comment' );
}
return new WP_Comment( $_comment );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Comment::\_\_construct()](__construct) wp-includes/class-wp-comment.php | Constructor. |
| [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. |
| Used By | Description |
| --- | --- |
| [get\_comment()](../../functions/get_comment) wp-includes/comment.php | Retrieves comment data given a comment ID or comment object. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Comment::add_child( WP_Comment $child ) WP\_Comment::add\_child( WP\_Comment $child )
=============================================
Add a child to the comment.
Used by `WP_Comment_Query` when bulk-filling descendants.
`$child` [WP\_Comment](../wp_comment) Required Child comment. File: `wp-includes/class-wp-comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment.php/)
```
public function add_child( WP_Comment $child ) {
$this->children[ $child->comment_ID ] = $child;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Sidebars_Controller::get_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Sidebars\_Controller::get\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=====================================================================================================
Retrieves one sidebar from the collection.
`$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-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( $request ) {
$this->retrieve_widgets();
$sidebar = $this->get_sidebar( $request['id'] );
if ( ! $sidebar ) {
return new WP_Error( 'rest_sidebar_not_found', __( 'No sidebar exists with that id.' ), array( 'status' => 404 ) );
}
return $this->prepare_item_for_response( $sidebar, $request );
}
```
| 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::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. |
| [\_\_()](../../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.8.0](https://developer.wordpress.org/reference/since/5.8.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.